Skip to content

Instantly share code, notes, and snippets.

@anxp
Last active January 13, 2019 13:57
Show Gist options
  • Save anxp/436532ab0d0bc47f229d94a479706f8b to your computer and use it in GitHub Desktop.
Save anxp/436532ab0d0bc47f229d94a479706f8b to your computer and use it in GitHub Desktop.
Drupal 7 MIME type missed validation function
<?php
/**
* Checks that the file has allowed MIME type.
*
* @param $file
* A Drupal file object.
* @param $mimetypes_string
* A string with a space separated list of allowed MIME types.
*
* @return
* An array. If the file MIME type is not allowed, it will contain an error
* message.
*
* @see hook_file_validate()
*/
function mymodule_mimetype_validate(stdClass $file, $mimetypes_string) {
$errors = array(); //At begin our errors array is empty. If it will remain empty at the end of the function -> we conclude here is no errors with MIME type.
$allowed_mime_types = explode(' ', $mimetypes_string);
if (!in_array(mime_content_type($file->uri), $allowed_mime_types)) {
$errors[] = t('Only files of following MIME types are allowed: %files-allowed.', array('%files-allowed' => $mimetypes_string));
}
return $errors;
}
//Usage example. Such function can be attached to form submit button as custom validate function:
function mymodule_validate_csv($form, &$form_state) {
//At first - check $_FILES array and if there is no file -> set_form_error().
//Other errors will be handled in file_save_upload(), see: https://api.drupal.org/api/drupal/includes%21file.inc/function/file_save_upload/7.x
if ($_FILES['files']['error']['file'] === UPLOAD_ERR_NO_FILE) {
form_set_error('file', t('File field can\'t be empty.'));
}
//This is array of validation functions and their arguments, this array will be passed as second argument to file_save_upload().
//"file_validate_extensions" is standard system validator, "mymodule_mimetype_validate" is our custom one.
$validators_array = array(
'file_validate_extensions' => array('csv txt'),
'mymodule_mimetype_validate' => array('text/plain'),
);
$file = file_save_upload('file', $validators_array, 'public://');
if ($file) {
//Save the file for use in the submit handler.
$form_state['storage']['file'] = $file;
drupal_set_message(t('File successfully uploaded.'));
} else {
form_set_error('file', t('File was not uploaded.'));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment