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. 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

hook_file_validate()

4 calls to file_validate_extensions()
FileUploadResource::prepareFilename in core/modules/file/src/Plugin/rest/resource/FileUploadResource.php
Prepares the filename to strip out any malicious extensions.
TemporaryJsonapiFileFieldUploader::prepareFilename in core/modules/jsonapi/src/Controller/TemporaryJsonapiFileFieldUploader.php
Prepares the filename to strip out any malicious extensions.
ValidatorTest::testFileValidateExtensions in core/modules/file/tests/src/Kernel/ValidatorTest.php
Test the file_validate_extensions() function.
_file_save_upload_single in core/modules/file/file.module
Saves a file upload to a new location.
3 string references to 'file_validate_extensions'
FileItem::getUploadValidators in core/modules/file/src/Plugin/Field/FieldType/FileItem.php
Retrieves the upload validators for a file field.
ImageWidget::formElement in core/modules/image/src/Plugin/Field/FieldWidget/ImageWidget.php
Returns the form for a single field widget.
ThemeSettingsForm::buildForm in core/modules/system/src/Form/ThemeSettingsForm.php

File

core/modules/file/file.module, line 383
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';
  if (!preg_match($regex, $file
    ->getFilename())) {
    $errors[] = t('Only files with the following extensions are allowed: %files-allowed.', [
      '%files-allowed' => $extensions,
    ]);
  }
  return $errors;
}