Re: [PHP] best way to determine (MIME) content type of a stream ofbytes?

[email protected] (Auke van Slooten)
Newsgroups php.general
Message-ID <[email protected]>
Robert P. J. Day wrote:
> On Mon, 8 Mar 2010, Ashley Sheridan wrote:
> 
>> What about writing the first n bytes to a file and then passing that
>> to the command line? I'm assuming a Linux server here, but it should
>> do the trick.
> 
>    gaaaaah!  i was hoping for something that wouldn't make me want to
> gouge out my eyes with a soup spoon. :-)

Maybe slightly less painfull, you can always write your own 'mimemagic' 
detection method. The magic.mime file is relatively easy to parse. This 
is the route we took some years ago to make our mime detection OS 
independant. We've made a php script which parses the mime.types file 
and the magic.mime file and it generates a php module which uses that 
information to figure out the correct mimetype.

The resulting php module has a large array, which looks like this:

     ...
     $mimemagic_data[0][4]["\0\0\1\273"]="video/mpeg";
     $mimemagic_data[0][4]["\0\0\2\0"]="application/x-123";
     $mimemagic_data[0][4]["\0\0\32\0"]="application/x-123";
     $mimemagic_data[0][4]["\0\6\25\141"]="application/x-dbm";
     $mimemagic_data[0][4]["\101\104\111\106"]="audio/X-HX-AAC-ADIF";
     $mimemagic_data[0][4]["\103\120\103\262"]="image/x-cpi";
     ...

with the first key as the offset to start, the next key is the length of 
  the snippet to check (I guess that could have been skipped...) and the 
final key is the exact string to match.

The magic.mime file is no magic bullet though, there are occasions when 
it won't match with a file, but that's usually with more complex types 
like microsoft office documents, not with images.

If you're interested, the mimemagic module can be found here:
http://svn.muze.nl/trunk/lib/modules/mod_mimemagic.php?revision=4299&root=ariadne-php5

And the builder script (which you should run on a unix system with 
magic.mime and mime.types file) is here:
http://svn.muze.nl/trunk/bin/utils/build_mimemagic_script.php?revision=4299&root=ariadne-php5

Hope this helps,
Auke van Slooten
Muze
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.