How to upload only pdf files in PHP

2020-07-27 20:25发布

I know this must be a repeated question but I have a different requirement here. What I want is when a user clicks on the Upload button, the dialog-box that appears only allows the user to upload the PDF file type only and nothing else.

What I've seen so far is once the user uploads a file, then there is a check done for file-type. I don't want to allow the user to upload files other than the pdf.

<?php
$allowedExts = array("pdf");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if (($_FILES["file"]["type"] == "application/pdf") && ($_FILES["file"]["size"] < 200000) && 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("doc_libraray/" . $_FILES["file"]["name"]))
      {
         echo $_FILES["file"]["name"] . " already exists. ";
         header('Location: '.site_url());
      }
      else
      {
          move_uploaded_file($_FILES["file"]["tmp_name"],
      "doc_libraray/" . $_FILES["file"]["name"]);
          echo "Stored in: " . "doc_libraray/" . $_FILES["file"]["name"];
          header('Location: '.$newURL);
      }
    }
}
else
{
    echo "Invalid file";
}
?>

Please suggest a way to achieve it!

2条回答
我只想做你的唯一
2楼-- · 2020-07-27 21:16
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['file']['TMP_NAME']);
switch ($mime) {

   case 'application/pdf':

   default:
       die("Unknown/not permitted file type");
}
查看更多
相关推荐>>
3楼-- · 2020-07-27 21:20

What you want is HTML5 which has a file type selector used for the dialog box in the <input type="file" ... > HTML code.

please see MDN documentation.

Example:

<input type="file" name="pdf" id="pdf" accept="application/pdf" >

From https://stackoverflow.com/a/7575533/3536236 Please note that due to the age of this answer they state "this is not widely accepted" but that is not so, input accept is now very widely accepted in HTML5 markup.

This is not a PHP issue as PHP can only play with the file once it's been uploaded. PHP should also check the file type once uploaded as the HTML accept can be duped.

To further clarify - PHP can not check the file that is to be uploaded before it is uploaded because PHP works on the server side only. Hence I suggest using HTML5 markup to select only files that (look like) PDFs, then once uploaded your PHP script can check the file type validity and then handle the outcomes.

PHP has no place in choosing the file before it is uploaded, that is entirely down to the end user browser and HTML.

查看更多
登录 后发表回答