function file_validate_extensions

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

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 308

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;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.