Determining a file’s mimetype with UNIX and PHP

In a recent project, I screwed up bigtime – I created a file upload feature which would store a file’s contents in the database (as BLOBs) but I forgot to keep track of the filename. Needless to say, after beating myself with a stick – the problem had not solved itself so I decided to try remedy the situation.

EDIT: My buddy Rob Cesaric has informed me that PHP actually has this feature built in:

See: http://us3.php.net/manual/en/function.finfo-file.php and http://us3.php.net/manual/en/ref.fileinfo.php

So here’s the problem – I’m lazy as hell, and far less intelligent and well-versed with file formats than the guys who wrote all the UNIX tools, so I decided to see if there was a solution to this problem there. As it turns out, I’m running on a Mac and often it will correctly determine the file type of a file, even if I don’t give it an extension. This got me thinking – there must be a tool in UNIX/Linux that reads the headers of files and determines their type or mimetype.

After a few seconds’ googling, I found this – the file command:
http://linux.about.com/library/cmd/blcmdl1_file.htm

That sound you’re hearing is the sound of UNIX angels singing from the heavens alongside the great Dennis Ritchie.

So, time to roll up the sleeves and get this little script working! I’m pleased to report that it worked exceptionally well – here’s a bit of sample code:

1
2
3
4
5
<?php
    $filetype = exec("file $filename" -z -b --mime-type");
    // returns the mimetype of the given file
    // use --mime-type on Mac, --mime on Linux (and expect slightly different outputs!)
?>

Simple once you know how! This should work on all UNIX-like (Linux/Mac/FreeBSD).