How to check downloaded pdf file type

Possible duplicate:
How to check file types of uploaded files in PHP?

I have a download function on my site and only PDF download is allowed. How to verify that the downloaded file is only pdf. Just as getimagesize() to write image files. Is there a way to check the file, which will be a PDF. my code is shown below.

 $whitelist = array(".pdf"); foreach ($whitelist as $item) { if (preg_match("/$item\$/i", $_FILES['uploadfile']['name'])) { } else { redirect_to("index.php"); } } $uploaddir='uploads/'; $uploadfile = mysql_prep($uploaddir . basename($_FILES['uploadfile']['name'])); if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $uploadfile)) { echo "succussfully uploaded"; } 

in this redirect_to and mysql_prep is a function defined by me. But the mime type can be changed using headers.So is there a way to check the file, which will be orignal pdf?

+8
html php pdf
source share
3 answers

You can check the MIME file type using the PHP File Information Functions . If it returns with type 'application / pdf', then it must be a PDF.

File information functions were added in PHP 5.3, but before that you can use the mime_content_type function.

+14
source share
 mime_content_type('file.ext'); 

mime_content_type ()

+8
source share

Find the PDF magic number by opening the file and reading the first few bytes of data. Most files have a specific format, and PDF files start with % PDF .

You can check the first 5 characters of a file if they are β€œ% PDF-”, this is most likely a real PDF (however, this does not give definitive confirmation that it is a PDF file, since any file can start with these 5 characters). The next 4 characters in the correct PDF file contain the version number (i.e. 1.2).

+7
source share

All Articles