function file_validate_extensions in Drupal 10
Same name and namespace in other branches
- 8 core/modules/file/file.module \file_validate_extensions()
- 6 includes/file.inc \file_validate_extensions()
- 7 includes/file.inc \file_validate_extensions()
- 9 core/modules/file/file.module \file_validate_extensions()
Checks that the filename ends with an allowed extension.
Parameters
\Drupal\file\FileInterface $file: A file entity.
string $extensions: A string with a space separated list of allowed extensions.
Return value
array An empty array if the file extension is allowed or an array containing an error message if it's not.
See also
2 calls to file_validate_extensions()
- ValidatorTest::testFileValidateExtensions in core/
modules/ file/ tests/ src/ Kernel/ ValidatorTest.php - Tests the file_validate_extensions() function.
- ValidatorTest::testFileValidateExtensionsOnUri in core/
modules/ file/ tests/ src/ Kernel/ ValidatorTest.php - Tests the file_validate_extensions() function.
17 string references to 'file_validate_extensions'
- EditorImageDialog::buildForm in core/
modules/ editor/ src/ Form/ EditorImageDialog.php - FileItem::getUploadValidators in core/
modules/ file/ src/ Plugin/ Field/ FieldType/ FileItem.php - Retrieves the upload validators for a file field.
- FileTestForm::submitForm in core/
modules/ file/ tests/ file_test/ src/ Form/ FileTestForm.php - Form submission handler.
- FileTestSaveUploadFromForm::validateForm in core/
modules/ file/ tests/ file_test/ src/ Form/ FileTestSaveUploadFromForm.php - Form validation handler.
- FileUploadHandler::handleExtensionValidation in core/
modules/ file/ src/ Upload/ FileUploadHandler.php - Gets the list of allowed extensions and updates the validators.
File
- core/
modules/ file/ file.module, line 159 - Defines a "managed_file" Form API field and a "file" field for Field module.
Code
function file_validate_extensions(FileInterface $file, $extensions) {
$errors = [];
$regex = '/\\.(' . preg_replace('/ +/', '|', preg_quote($extensions)) . ')$/i';
// Filename may differ from the basename, for instance in case files migrated
// from D7 file entities. Because of that new files are saved temporarily with
// a generated file name, without the original extension, we will use the
// generated filename property for extension validation only in case of
// temporary files; and use the file system file name in case of permanent
// files.
$subject = $file
->isTemporary() ? $file
->getFilename() : $file
->getFileUri();
if (!preg_match($regex, $subject)) {
$errors[] = t('Only files with the following extensions are allowed: %files-allowed.', [
'%files-allowed' => $extensions,
]);
}
return $errors;
}