WordPress File Uploads Checked By MIME Type

Building a custom HTML form for WordPress is something I do fairly regularly. When adding an upload form, it’s important to check for allowed file types. You wouldn’t want anyone uploading a malicious PHP script, right? Wouldn’t it be great if WordPress did that for you? Of course it would.

Enter get_allowed_mime_types

get_allowed_mime_types() is a function that returns an extensive array of acceptable document types. When using it in your document upload script, it can help you perform a basic file type check like this:

// FIND THE FILE TYPE
$file_type = $_FILES['app_attachment']['type'][$key];
// FOR EACH OF THE MIME TYPES
foreach ( get_allowed_mime_types( ) as $exts) {
  // IF THERE IS A MATCH FOUND
  if ( preg_match( '!^(' . $exts . ')$!i', $file_type ) ) {
    // CREATE A VARIABLE TO GIVE THE GO AHEAD
    $go_ahead = 1;
    // NOW IT'S OKAY TO STOP RUNNING THE FOREACH
    break;
  }
}
// IF NO MATCH WAS FOUND
if (!$go_ahead) {
  // SEND THE VISITOR BACK TO THE UPLOAD PAGE WITH AN ERROR MESSAGE
  header( "Location: /insert-your-path/?error=1" );
  // STOP RUNNING SCRIPTS
  exit;
}

Final Thoughts

This method only looks for allowed file extensions. It isn’t as thorough as some other methods of file checking such as using the PHP finfo() function. I would like to something similar that uses the finfo() function.

Published by

Tim Bunch

Tim Bunch is a Web Developer from Boise, Idaho. As a web standards fanatic, he passionately pursues best practices. He also actively engages people on a wide range of topics in a variety of social media networks. Tim is also an avid Wordpress developer, music maker, coffee drinker, and child raiser. @timbunch

Leave a Reply

Your email address will not be published. Required fields are marked *