The SitePoint Forums have moved.

You can now find them here.
This forum is now closed to new posts, but you can browse existing content.
You can find out more information about the move and how to open a new account (if necessary) here.
If you get stuck you can get support by emailing forums@sitepoint.com

If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

A Quick and Dirty MIME Type Validator

Yesterday, I found myself in the unenviable position of being unable to get the MIME type of a video file uploaded to my production server. The fileinfo functions on that server will only work with the magic.mime file at /usr/share/file/magic for some reason. The sysadmin claimed he had added the requested lines to this file to detect FLV, WMV, ASF, etc., but a quick perusal of the file using UltraEdit's find function showed that this wasn't the case. What's worse, he changed mime_magic.magicfile to an empty file at /etc/magic, so I can't use mime_content_type now either! Since my application is targeted at non-technical users, it would be unthinkable to expect them to jump through the same hoops I've had to jump through (in vain) in order to get the package working. What to do?

I decided I needed a reliable platform-independent solution to the problem. Enter the MimeValidator class. What this class does is take hints from the browser that uploaded a file - $_FILES['userfile']['type'] and the extension in $_FILES['userfile']['name'] - and confirm whether the file contents match the type that the browser says the file is.

The constructor simply builds the magic SQLite database if it doesn't exist. Since I am only concerned with a handful of video file types that I want to allow here, I elected not to place magic numbers for every possible file type in the table. (Yes, magic.mime could conceivably waste MIPS by checking your file against such irrelevant types as Doom and Adventure game files!)

The validateX() functions look up the MIME type or extension passed by the browser in the mime_type table. If it isn't in the table, then it isn't an allowed type, so we just return false. If it is in the table, then these functions read the appropriate bytes from the file and compare them to the magic numbers in the table. Simple!