You are here

File interface in Drupal 10

Same name and namespace in other branches
  1. 8 core/includes/file.inc \file
  2. 4 includes/file.inc \file
  3. 5 includes/file.inc \file
  4. 6 includes/file.inc \file
  5. 7 includes/file.inc \file
  6. 9 core/includes/file.inc \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 hook implementations of hook_file_validate().
  • 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' => [
    'file_validate_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.html

\hook_file_validate()

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
Hooks for file module.

Functions

Namesort descending Location Description
file_get_file_references core/modules/file/file.module Retrieves a list of references to a file.

Classes

Namesort descending Location Description
File core/modules/file/src/Entity/File.php Defines the file entity class.

Interfaces

Namesort descending Location Description
FileInterface core/modules/file/src/FileInterface.php Defines getter and setter methods for file entity base fields.