You are here

function filefield_validate_extensions in FileField 6.3

An #upload_validators callback. Check the file matches an allowed extension.

If the mimedetect module is available, this will also validate that the content of the file matches the extension. User #1 is included in this check.

Parameters

$file: A Drupal file object.

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

Return value

An array of any errors cause by this file if it failed validation.

File

./filefield.module, line 752
FileField: Defines a CCK file field type.

Code

function filefield_validate_extensions($file, $extensions) {
  global $user;
  $errors = array();
  if (!empty($extensions)) {
    $regex = '/\\.(' . preg_replace('/ +/', '|', preg_quote($extensions)) . ')$/i';
    $matches = array();
    if (preg_match($regex, $file->filename, $matches)) {
      $extension = $matches[1];

      // If the extension validates, check that the mimetype matches.
      if (module_exists('mimedetect')) {
        $type = mimedetect_mime($file);
        if ($type != $file->filemime) {
          $errors[] = t('The file contents (@type) do not match its extension (@extension).', array(
            '@type' => $type,
            '@extension' => $extension,
          ));
        }
      }
    }
    else {
      $errors[] = t('Only files with the following extensions are allowed: %files-allowed.', array(
        '%files-allowed' => $extensions,
      ));
    }
  }
  return $errors;
}