You are here

function file_validate_extensions in Drupal 9

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

hook_file_validate()

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.

File

core/modules/file/file.module, line 338
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;
}