Jump to content

Using fread to detect file type


NotionCommotion

Recommended Posts

I had some problems detecting file type for a Microsoft Outlook document, and requinix recommended using doing the MIME magic manually instead of using finfo (reference http://forums.phpfreaks.com/topic/294730-mime-type-for-outlook-msg-file/).

 

Seemed to work fine, but recently found that more than one file type (i.e. an old Microsoft document file) has the same magic constant as an Outlook file.  How can I find the correct "magic" strings that represent different file types?

<?php
function test($file)
{
    $h = fopen($file, 'rb');
    $magic = "\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1\x00";    //How do I determine the correct string for different file types?
    $bytes = fread($h, strlen($magic));
    fclose($h);
    echo($file.' '.($magic==$bytes?'equal':'not equal').'<br>');    
}
test('test.msg');  //echos equal
test('test.DOC');  //echos equal
test('test.doc');  //echos equal
test('magic.php');  //echos not equal
?>
Link to comment
https://forums.phpfreaks.com/topic/295120-using-fread-to-detect-file-type/
Share on other sites

.msg and .doc and others all use the Compound File Binary File Format. They all have that same 9 byte header.

 

To properly detect each type within you'll have to parse the file and look for identifying information. For example, it seems .doc files can be identified by a 0xA5EC at a certain location I've yet to pinpoint since it probably requires knowing more about the CFB format.

Thanks Requinix,  This is getting a bit more complicated than I want it to be.  My main purpose for doing this is to ensure that uploaded files have extensions which match the file type so that that I could restrict files based on extension and be assured that I am really restricting that real file.  What I will probably do is if the file extension is msg, then manually check it, but if doc, then use finfo.

There are other problematic file types too, like DOCX and its siblings will be reported as application/zip. (Which is actually what they are.)

 

Use MIME detection for many things, MIME + file extensions for the exceptions.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.