Possible Duplicate:
How to check file types of uploaded files in PHP?
I have uploading features on my site and only PDF uploads are allowed. How can I check that the uploaded file is only a PDF? Just like getimagesize()
can verify image files.
Is there any way to check the file is a PDF? My code is 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";
}
Functions redirect_to
and mysql_prep
are defined by me. But mime type can be changed using headers. So is there any way to check the file to be an original pdf?
You can check the MIME type of the file using PHP's File Info Functions. If it returns with the type 'application/pdf' then it should be a PDF.
Using JavaScript, you can easily check the selected file extension with allowed file extensions and can restrict the user to upload only the allowed file types. For this we will use fileValidation() function. We will create fileValidation() function that contains the complete file type validation code.
You can simply use an OR statement, i.e. return ($file['content-type'] == 'image/*' || $file['content-type'] == 'application/pdf'); This is assuming you still just want to return true/false. So the caller will know that the file was either a PDF or an image.
Look for 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 the file, if they equal "%PDF-", it is likely a real PDF (however, this does not definitively prove that it is a PDF file, as any file can begin with those 5 characters). The next 4 characters in a proper PDF file contain the version number (i.e. 1.2).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With