File interface
Same name in other branches
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',
],
],
],
];
- Use file_save_upload() to trigger the FileUploadSanitizeNameEvent event and \Drupal\file\Validation\FileValidatorInterface::validate().
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
\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/ |
Retrieves a list of references to a file. |
Classes
Title Sort descending | File name | Summary |
---|---|---|
File | core/ |
Defines the file entity class. |
Interfaces
Title Sort descending | File name | Summary |
---|---|---|
FileInterface | core/ |
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.