Upload DOC or PDF using PHP


I'm able to upload images fine, but when when I change the types from image/jpg, image/gif to application/msword and application/pdf, it doesn't work. Here's my code. The exact same code works for images, but for uploading docs and pdf, it outputs "Invalid File." What's going on here? My file is only approx 30kb and is well under the file size limit here.

$allowedExts = array("pdf", "doc", "docx"); 
$extension = end(explode(".", $_FILES["file"]["name"]));

if ( ( ($_FILES["file"]["type"] == "application/msword") || ($_FILES["file"]["type"] == "text/pdf") ) 
&& ($_FILES["file"]["size"] < 20000) && in_array($extension, $allowedExts))
 move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); 
echo "Invalid file."

This question is tagged with php pdf upload doc file-type

~ Asked on 2012-07-22 15:00:27

The Best Answer is


Don't use the ['type'] parameter to validate uploads. That field is user-provided, and can be trivially forged, allowing ANY type of file to be uploaded. The same goes for the ['name'] parameter - that's the name of the file as provided by the user. It is also trivial to forge, so the user's sending nastyvirus.exe and calling it cutekittens.jpg.

The proper method for validating uploads is to use server-side mime-type determination, e.g. via fileinfo, plus having proper upload success checking, which you do not:

if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    die("Upload failed with error " . $_FILES['file']['error']);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['file']['tmp_name']);
$ok = false;
switch ($mime) {
   case 'image/jpeg':
   case 'application/pdf'
   case etc....
        $ok = true;
       die("Unknown/not permitted file type");

You are also using the user-provided filename as part of the final destination of the move_uploaded_files. it is also trivial to embed path data into that filename, which you then blindly use. That means a malicious remote user can scribble on ANY file on your server that they know the path for, plus plant new files.

~ Answered on 2012-07-22 15:17:17


Please add the correct mime-types to your code - at least these ones:

.jpeg -> image/jpeg
.gif  -> image/gif
.png  -> image/png

A list of mime-types can be found here.

Furthermore, simplify the code's logic and report an error number to help the first level support track down problems:

$allowedExts = array(

$allowedMimeTypes = array( 

$extension = end(explode(".", $_FILES["file"]["name"]));

if ( 20000 < $_FILES["file"]["size"]  ) {
  die( 'Please provide a smaller file [E/1].' );

if ( ! ( in_array($extension, $allowedExts ) ) ) {
  die('Please provide another file type [E/2].');

if ( in_array( $_FILES["file"]["type"], $allowedMimeTypes ) ) 
 move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); 
die('Please provide another file type [E/3].');

~ Answered on 2012-07-22 15:09:01

Most Viewed Questions: