You are here

function file_validate in Drupal 7

Same name and namespace in other branches
  1. 8 core/modules/file/file.module \file_validate()
  2. 9 core/modules/file/file.module \file_validate()

Checks that a file meets the criteria specified by the validators.

After executing the validator callbacks specified hook_file_validate() will also be called to allow other modules to report errors about the file.

Parameters

$file: A Drupal file object.

$validators: An optional, associative array of callback functions used to validate the file. The keys are function names and the values arrays of callback parameters which will be passed in after the file object. The functions should return an array of error messages; an empty array indicates that the file passed validation. The functions will be called in the order specified.

Return value

An array containing validation error messages.

See also

hook_file_validate()

Related topics

3 calls to file_validate()
FileValidateTest::testCallerValidation in modules/simpletest/tests/file.test
Test that the validators passed into are checked.
FileValidateTest::testInsecureExtensions in modules/simpletest/tests/file.test
Tests hard-coded security check in file_validate().
file_save_upload in includes/file.inc
Saves a file upload to a new location.

File

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

Code

function file_validate(stdClass &$file, $validators = array()) {

  // Call the validation functions specified by this function's caller.
  $errors = array();
  foreach ($validators as $function => $args) {
    if (function_exists($function)) {
      array_unshift($args, $file);
      $errors = array_merge($errors, call_user_func_array($function, $args));
    }
  }

  // Let other modules perform validation on the new file.
  $errors = array_merge($errors, module_invoke_all('file_validate', $file));

  // Ensure the file does not contain a malicious extension. At this point
  // file_save_upload() will have munged the file so it does not contain a
  // malicious extension. Contributed and custom code that calls this method
  // needs to take similar steps if they need to permit files with malicious
  // extensions to be uploaded.
  if (empty($errors) && !variable_get('allow_insecure_uploads', 0) && preg_match('/\\.(php|phar|pl|py|cgi|asp|js)(\\.|$)/i', $file->filename)) {
    $errors[] = t('For security reasons, your upload has been rejected.');
  }
  return $errors;
}