Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check the uploaded file type is pdf [duplicate]

Tags:

html

php

pdf

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?

like image 548
StaticVariable Avatar asked Jun 14 '12 18:06

StaticVariable


People also ask

How do you check the uploaded file type is 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.

How do you validate a file type?

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.

How can I tell if image is PDF or PHP?

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.


1 Answers

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).

like image 64
Mike Avatar answered Oct 29 '22 17:10

Mike