views:

171

answers:

4

I am working on a project that requires file uploads. I want to make sure it's secure and that only PDF files are being uploaded. I am already checking file extension but i want to make sure the file really is a pdf file.

What is the best way to check the mime type in php? I am using PHP 5.2.5 and can't seem to get fileinfo or mime_content_type() working.

for fileinfo i keep getting this:

Warning: finfo_open() [function.finfo-open]: Failed to load magic database
at '(null)'. in [snipped filename]  on line 35
+3  A: 

mime types are not reliable for checking type of files. A client's browser might report it wrongly.

Check for Magic Number. PDF files start with "%PDF" (25 50 44 46).

Ankit Jain
reading the mime type from the $_FILE variable would get it from the browser. this is what i was doing. What i want to do is read the header of the file to see if it really is a pdf file.
Samuel
Yes. That's what's being suggested here.
recursive
@recursive for the record, the second line of this answer wasn't there when i posted the comment.
Samuel
There were no edits reported, but I guess there is a grace period after an answer is submitted in which edits do not go on the record. Anyway, no harm done. I just hope you are able to solve your problem.
recursive
ooh... yes. i added the last line after some research!
Ankit Jain
For what it's worth, this is not spec compliant. Here's a question that includes the full explanation: http://stackoverflow.com/questions/2731917/how-to-detect-if-a-file-is-pdf-or-tiff
plinth
A: 

An easy way to get the MIME type is directly from $_FILES. If the mime type contains the word 'pdf' then you can consider it a valid PDF.

$contentType = $_FILES['myFile']['type'];
if(isValidPDF($contentType)) {
    die('It is a PDF');
} else {
    die('It is not a PDF');
}

function isValidPDF($mime) {
    return strpos($mime, 'pdf') !== false;
}
Paul Dragoonis
This is an insecure method. $_FILES get's it's mime type from the browser and not the file itself.
buggedcom
A: 

Indeed, MIME type's aren't the best way of making sure that a user has uploaded a valid file since this can be easily faked if you know how.

But when the file is being posted, you can always check the mime type this way:

$Type = $_FILES['someFile']['type'];

Maybe you could use a php class to determine it's a valid PDF something like FPDF( http://www.fpdf.org/)

Well, good luck anyways :)

Stephen
A: 

It probably means that the MAGIC environment variable is not set, and your magic file isn't at /usr/share/misc/magic . Either set the value of MAGIC to point to the correct magic file, or pass the magic file as a second parameter to your finfo constructor

$finfo = new finfo(FILEINFO_MIME, "/usr/share/misc/magic");

or

$finfo = finfo_open(FILEINFO_MIME, "/usr/share/misc/magic"); 
Mark Baker