Jump to content

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
?>
Edited by NotionCommotion
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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.