file_validate_extensions

file_validate_extensions(FileInterface $file, $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()

File

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

Code

function file_validate_extensions(FileInterface $file, $extensions) {
  $errors = array();

  $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.', array('%files-allowed' => $extensions));
  }
  return $errors;
}
doc_Drupal
2016-10-29 09:14:19
Comments
Leave a Comment

Please login to continue.