Same name and namespace in other branches
  1. 4.6.x includes/file.inc \file
  2. 4.7.x includes/file.inc \file
  3. 5.x includes/file.inc \file
  4. 6.x includes/file.inc \file
  5. 7.x includes/file.inc \file
  6. 8.9.x core/includes/file.inc \file
  7. 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 \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.html

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

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.