File interface

Same name and namespace in other branches
  1. 7.x includes/file.inc \file
  2. 9 core/includes/file.inc \file
  3. 8.9.x core/includes/file.inc \file
  4. 11.x core/modules/file/file.api.php \file

Common file handling functions.

Uploading files and security considerations

Using \Drupal\file\Element\ManagedFile field with a defined list of allowed extensions is best way to provide a file upload field. It will ensure that:

  • File names are sanitized by the FileUploadSanitizeNameEvent event.
  • Files are validated by \Drupal\file\Validation\FileValidatorInterface().
  • Files with insecure extensions will be blocked by default even if they are listed. If .txt is an allowed extension such files will be renamed.

The \Drupal\Core\Render\Element\File field requires the developer to ensure security concerns are taken care of. To do this, a developer should:

  • Add the #upload_validators property to the form element. For example,

$form['file_upload'] = [
  '#type' => 'file',
  '#title' => $this->t('Upload file'),
  '#upload_validators' => [
    'FileExtension' => [
       'extensions' => 'png gif jpg',
      ],
    ],
  ],
];

Important considerations, regardless of the form element used:

  • Always use and validate against a list of allowed extensions.
  • If the configuration system.file:allow_insecure_uploads is set to TRUE then potentially insecure files will not be renamed. This setting is not recommended.

See also

https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet…

\Drupal\file\Validation\FileValidatorInterface

file_save_upload()

\Drupal\Core\File\Event\FileUploadSanitizeNameEvent

\Drupal\system\EventSubscriber\SecurityFileUploadEventSubscriber

\Drupal\file\Element\ManagedFile

\Drupal\Core\Render\Element\File

File

core/modules/file/file.api.php, line 8

Functions

Title Sort descending File name Summary
file_get_file_references core/modules/file/file.module Retrieves a list of references to a file.

Classes

Title Sort descending File name Summary
File core/modules/file/src/Entity/File.php Defines the file entity class.

Interfaces

Title Sort descending File name Summary
FileInterface core/modules/file/src/FileInterface.php Defines getter and setter methods for file entity base fields.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.