Same name and namespace in other branches
  1. 6.x includes/file.inc \file_validate_extensions()
  2. 7.x includes/file.inc \file_validate_extensions()
  3. 8.9.x core/modules/file/file.module \file_validate_extensions()
  4. 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.

Deprecated

in drupal:10.2.0 and is removed from drupal:11.0.0. Use the 'file.validator' service instead.

See also

https://www.drupal.org/node/3363700

hook_file_validate()

2 calls to file_validate_extensions()
LegacyValidatorTest::testFileValidateExtensions in core/modules/file/tests/src/Kernel/LegacyValidatorTest.php
Tests the file_validate_extensions() function.
LegacyValidatorTest::testFileValidateExtensionsOnUri in core/modules/file/tests/src/Kernel/LegacyValidatorTest.php
Tests the file_validate_extensions() function.
3 string references to 'file_validate_extensions'
LegacyFileThemeTest::testTemplatePreprocessFileUploadHelp in core/modules/file/tests/src/Kernel/LegacyFileThemeTest.php
@covers ::template_preprocess_file_upload_help
ManagedFile::processManagedFile in core/modules/file/src/Element/ManagedFile.php
Render API callback: Expands the managed_file element type.
template_preprocess_file_upload_help in core/modules/file/file.module
Prepares variables for file upload help text templates.

File

core/modules/file/file.module, line 152
Defines a "managed_file" Form API field and a "file" field for Field module.

Code

function file_validate_extensions(FileInterface $file, $extensions) {
  @trigger_error(__FUNCTION__ . '() is deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use the \'file.validator\' service instead. See https://www.drupal.org/node/3363700', E_USER_DEPRECATED);
  $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;
}