File interface in Drupal 10
Same name and namespace in other branches
- 8 core/includes/file.inc \file
- 4 includes/file.inc \file
- 5 includes/file.inc \file
- 6 includes/file.inc \file
- 7 includes/file.inc \file
- 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',
],
],
];
- Use file_save_upload() to trigger the FileUploadSanitizeNameEvent event and hook_file_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.html
\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
Name | Location | Description |
---|---|---|
file_get_file_references |
core/ |
Retrieves a list of references to a file. |
Classes
Interfaces
Name | Location | Description |
---|---|---|
FileInterface |
core/ |
Defines getter and setter methods for file entity base fields. |