8.3.x file.module file_validate_extensions(FileInterface $file, $extensions)
8.0.x file.module file_validate_extensions(FileInterface $file, $extensions)
8.1.x file.module file_validate_extensions(FileInterface $file, $extensions)
8.2.x file.module file_validate_extensions(FileInterface $file, $extensions)
8.4.x file.module file_validate_extensions(FileInterface $file, $extensions)
6.x file.inc file_validate_extensions($file, $extensions)
7.x file.inc file_validate_extensions(stdClass $file, $extensions)

Checks that the filename ends with an allowed extension.

Parameters

$file: A Drupal file object.

$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

2 calls to file_validate_extensions()
FileValidatorTest::testFileValidateExtensions in modules/simpletest/tests/file.test
Test the file_validate_extensions() function.
hook_file_insert in modules/system/system.api.php
Respond to a file being added.
10 string references to 'file_validate_extensions'
aggregator_form_opml_submit in modules/aggregator/aggregator.admin.inc
Form submission handler for aggregator_form_opml().
file_field_widget_upload_validators in modules/file/file.field.inc
Retrieves the upload validators for a file field.
file_managed_file_process in modules/file/file.module
Process function to expand the managed_file element type.
file_save_upload in includes/file.inc
Saves a file upload to a new location.
image_field_widget_form in modules/image/image.field.inc
Implements hook_field_widget_form().

... See full list

File

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

Code

function file_validate_extensions(stdClass $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;
}

Comments

songyy’s picture

If you want to use this function to validate the uploaded_file, you may do something like this:

    // suppose you want to allow image files only
    $form['file_upload'] = array(
      '#type'   => "managed_file",
      '#title'  => t("Upload Image"),
      '#descripion' => t("Only Image Files are allowed."),
      '#upload_location'    => "public://img/",
      "#upload_validators"  => array("file_validate_extensions" => array("png gif jpg")),
    );
Bevan’s picture

Alternatively, '#upload_validators' => array('file_validate_is_image' => array()).

If dealing with an uploaded file in a form validate handler, you could also call file_save_upload() directly with $validators = array('file_validate_is_image', ...).