PHP file upload: mime or extension based verification?

Okay, so to all the geniouses here yapping something about “SCREW EXTENSIONS, CHECK MIME! FILEINFO RLZ!”, I’ve prepared some tutorial:

  1. Download this pretty php logo I drew
  2. View it. Pretty nice, isn’t it?
  3. Rename it to whatever_you_like.php
  4. Put it through all your awesome mime type/whatever checkers
  5. Run it

In conclusion, you should NEVER EVER EVER rely on MIME type. You web server doesn’t care about MIME type, it determines what to do by EXTENSION, the ultimately downvoted @Col. Shrapnel‘s answer is actually right. Any information provided to you by something checking MIME is absolutely irrelevant to your webserver when it comes to execution.

EDIT: the not-as-uncommon-code-as-you’d-want-it-to-be that opens a website to this type of attack:

<?php

$mimetype = mime_content_type($_FILES['file']['tmp_name']);
if(in_array($mimetype, array('image/jpeg', 'image/gif', 'image/png'))) {
   move_uploaded_file($_FILES['file']['tmp_name'], '/whatever/something/imagedir/' . $_FILES['file']['name']);
   echo 'OK';

} else {
    echo 'Upload a real image, jerk!';
}

Leave a Comment