1.20.x file.inc file_validate_extensions(File $file, $extensions)

Checks that the filename ends with an allowed extension.

Parameters

File $file: A file entity.

$extensions: A string with a space separated list of allowed extensions.

Return value

An array. If the file extension is not allowed, it will contain an error: message.

See also

hook_file_validate()

Related topics

File

includes/file.inc, line 1821
API for handling file uploads and server file management.

Code

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

  $regex = '/\.(' . preg_replace('/ +/', '|', preg_quote($extensions)) . ')$/i';
  if (!preg_match($regex, $file->filename)) {
    $errors[] = t('Only files with the following extensions are allowed: %files-allowed.', array('%files-allowed' => $extensions));
  }
  return $errors;
}