Search code examples
phpuploaddoc

How can I permit only .doc files for uploading?


Well this is my code but when I am trying to upload the doc file, the response is "Invalid file".....Thanks a lot. By the way my second question deals with rename of uploaded file to desired format "actual time + the original title" $date.

<?php
$datum = Date("j/m/Y/H/i/s", Time());
echo($date);

$allowedExts = array("doc");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "application/msword"))
&& ($_FILES["file"]["size"] < 2000000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{    
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("uploaded_papers/" . $_FILES["file"]["name"]))
  {
  echo $_FILES["file"]["name"] . " already exists. ";
  }
else
  {
  move_uploaded_file($_FILES["file"]["tmp_name"],
  "uploaded_papers/" . $_FILES["file"]["name"]);
  echo "Stored in: " . "uploaded_papers/" . $_FILES["file"]["name"];
  }
  }
  }                                          
  else
  {
  echo "Invalid file";
  }
  ?> 

Solution

  • Change this:

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

    To:

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

    Array_pop gives the last element from the array.

    As to the proper MIME type for the Word document: http://filext.com/faq/office_mime_types.php

    .doc
    application/msword
    .docx
    application/vnd.openxmlformats-officedocument.wordprocessingml.document
    

    So I would go for something like this:

    $allowedMimes = array( "application/msword" , "application/vnd.openxmlformats-officedocument.wordprocessingml.document" , "application/vnd.ms-word");
    
    if ($_FILES["file"]["size"] < 2000000
    && in_array($_FILES["file"]["type"], $allowedMimes))
    

    To see the MIME type of the uploaded file, just echo $_FILES["file"]["type"]; and see that it's not an image. Please post back the mimetype so we can see what the "normal" doc is. Updated the allowedMimes array with your own result.