NotionCommotion Posted March 5, 2015 Share Posted March 5, 2015 (edited) 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 March 5, 2015 by NotionCommotion Quote Link to comment Share on other sites More sharing options...
requinix Posted March 5, 2015 Share Posted March 5, 2015 .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. Quote Link to comment Share on other sites More sharing options...
NotionCommotion Posted March 5, 2015 Author Share Posted March 5, 2015 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. Quote Link to comment Share on other sites More sharing options...
requinix Posted March 5, 2015 Share Posted March 5, 2015 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. Quote Link to comment Share on other sites More sharing options...
NotionCommotion Posted March 6, 2015 Author Share Posted March 6, 2015 Yea, learned early 'bot docx and cousin, but msg took me for a loop. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.