Finfo_file return incorrect type

Viewed 534

Good day!

My code return incorrect type for this pdf file. For another pdf file this code is good.

    $finfo = @finfo_open(FILEINFO_MIME);
    $mime = @finfo_file($finfo, 'upload/123.pdf');
    finfo_close($finfo);

    print_r($mime);

This is answer: application/octet-stream; charset=binary

This is what i need: application/pdf

This is pdf file https://dropmefiles.com/x6slw

Thank you!

1 Answers

Well I was curious, downloaded your file and yes on running your code it didn't give me application/pdf but instead application/octet-stream; charset=binary

Since the finfo function relies on the file signature (bytes) to find out the file MIME type I made a guess - something must be wrong with the signature so I analyzed it under a Hex-viewer and this is what I found

Your file enter image description here

Normal file enter image description here

To be identified properly the PDF signature should be present at the very start but in your file it was offset by 4 bytes. Since finfo could not find the correct MIME type it fell back to its generic "application/octet-stream; charset=binary"

So how to fix?

I must admit that php's inbuilt functions are pretty good for usual tasks but sometimes here and there you may encounter those "edge case" that's where 3rd party open source libraries come in and here I found which can fix it for you.

PhpMimeType : https://github.com/katzien/PhpMimeType

$type = \MimeType\MimeType::getType('123.pdf');
print_r($type); //"application/pdf"
                // Yay!
Related