使用 PHP 上传 DOC 或 PDF

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11601342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:51:04  来源:igfitidea点击:

Upload DOC or PDF using PHP

phppdfuploaddocfile-type

提问by user961627

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.

我可以很好地上传图像,但是当我将类型从 image/jpg、image/gif 更改为 application/msword 和 application/pdf 时,它不起作用。这是我的代码。完全相同的代码适用于图像,但对于上传文档和 pdf,它会输出“无效文件”。这里发生了什么?我的文件只有大约 30kb,并且远远低于此处的文件大小限制。

$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"]); 
}
else
{
echo "Invalid file."
}

回答by Marc B

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.exeand calling it cutekittens.jpg.

不要使用该['type']参数来验证上传。该字段是用户提供的,可以轻松伪造,允许上传任何类型的文件。这同样适用于在['name']参数-这是该文件的名称由用户提供。伪造也是微不足道的,所以用户发送nastyvirus.exe和调用它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:

验证上传的正确方法是使用服务器端 MIME 类型确定,例如通过fileinfo,加上正确的上传成功检查,您没有:

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;
   default:
       die("Unknown/not permitted file type");
}
move_uploaded_file(...);

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.

您还使用用户提供的文件名作为 move_uploaded_files 最终目的地的一部分。将路径数据嵌入到该文件名中也很简单,然后您可以盲目地使用它。这意味着恶意的远程用户可以在他们知道路径的服务器上的任何文件上乱涂乱画,并植入新文件。

回答by SteAp

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

请在您的代码中添加正确的 MIME 类型 - 至少是这些:

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

A list of mime-types can be found here.

可以在此处找到 MIME 类型列表。

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

此外,简化代码的逻辑并报告错误号,以帮助一级支持跟踪问题:

$allowedExts = array(
  "pdf", 
  "doc", 
  "docx"
); 

$allowedMimeTypes = array( 
  'application/msword',
  'text/pdf',
  'image/gif',
  'image/jpeg',
  'image/png'
);

$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"]); 
}
else
{
die('Please provide another file type [E/3].');
}

回答by Deepak Kr

$folder = "Resume/";
$temp = explode(".", $_FILES["uploaded"]["name"]);
$newfilename = round(microtime(true)).'.'. end($temp);
$db_path ="$folder".$newfilename  ;
//remove the .
$listtype = array(
'.doc'=>'application/msword',
'.docx'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'.rtf'=>'application/rtf',
'.pdf'=>'application/pdf'); 
if ( is_uploaded_file( $_FILES['uploaded']['tmp_name'] ) )
{
if($key = array_search($_FILES['uploaded']['type'],$listtype))
{if (move_uploaded_file($_FILES['uploaded']  ['tmp_name'],"$folder".$newfilename))
{
include('connection.php');
$sql ="INSERT INTO tb_upload
(filePath) VALUES ('$db_path')";
}
}
else    
{
echo "File Type Should Be .Docx or .Pdf or .Rtf Or .Doc";
}

回答by Anirudh Ramanathan

One of your conditions is failing. Check the value of mime-type for your files.
Try using application/pdf, not text/pdf. Refer to Proper MIME media type for PDF files

你的条件之一不合格。检查文件的 mime-type 值。
尝试使用 application/pdf,而不是 text/pdf。请参阅PDF 文件的正确 MIME 媒体类型

回答by Amit

You can use

您可以使用

$_FILES['filename']['error'];

If any type of error occurs then it returns 'error' else 1,2,3,4 or 1 if done

如果发生任何类型的错误,则返回“错误”,否则返回 1,2,3,4 或 1(如果完成)

1 : if file size is over limit .... You can find other options by googling

1 : 如果文件大小超过限制.... 您可以通过谷歌搜索找到其他选项

回答by Bhaskar Reddy

    <?php

    //create table

    /*

    --
    -- Database: `mydb`
    --

    -- --------------------------------------------------------

    --
    -- Table structure for table `tbl_user_data`
    --

    CREATE TABLE `tbl_user_data` (
      `attachment_id` int(11) NOT NULL,
      `attachment` varchar(200) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

    --
    -- Indexes for dumped tables
    --

    --
    -- Indexes for table `tbl_user_data`
    --
    ALTER TABLE `tbl_user_data`
      ADD PRIMARY KEY (`attachment_id`);

    --
    -- AUTO_INCREMENT for dumped tables
    --

    --
    -- AUTO_INCREMENT for table `tbl_user_data`
    --
    ALTER TABLE `tbl_user_data`
      MODIFY `attachment_id` int(11) NOT NULL AUTO_INCREMENT;

      */
    $servername = "localhost";
    $username = "root";
    $password = "";
    // Create connection
    $dbname = "myDB";
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 

    if(isset($_POST['submit'])){

      $fileName=$_FILES["resume"]["name"];
      $fileSize=$_FILES["resume"]["size"]/1024;
      $fileType=$_FILES["resume"]["type"];
      $fileTmpName=$_FILES["resume"]["tmp_name"];
      $statusMsg = '';
      $random=rand(1111,9999);
      $newFileName=$random.$fileName;

      //file upload path
      $targetDir = "resumeUpload/";
      $fileName = basename($_FILES["resume"]["name"]);
      $targetFilePath = $targetDir . $newFileName;
      $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);

      if(!empty($_FILES["resume"]["name"])) {
          //allow certain file formats
          //$allowTypes = array('jpg','png','jpeg','gif','pdf','docx','doc');
          $allowTypes = array('pdf','docx','doc');
          if(in_array($fileType, $allowTypes)){
              //upload file to server
              if(move_uploaded_file($_FILES["resume"]["tmp_name"], $targetFilePath)){
                  $statusMsg = "The file ".$fileName. " has been uploaded.";
              }else{
                  $statusMsg = "Sorry, there was an error uploading your file.";
              }
          }else{
              $statusMsg = 'Sorry, only DOC,DOCX, & PDF files are allowed to upload.';
          }
      }else{
          $statusMsg = 'Please select a file to upload.';
      }

      //display status message
      echo $statusMsg;

      $sql="INSERT INTO `tbl_user_data` (`attachment_id`, `attachment`) VALUES
      ('NULL', '$newFileName')";

      if (mysqli_query($conn, $sql)) {

       $last_id = mysqli_insert_id($conn);
         echo "upload success";
      } else {
          echo "Error: " . $sql . "<br>" . mysqli_error($conn);
      }


    }

    ?>
    <form id="frm_upload" action="" method="post" enctype="multipart/form-data">
    Upload Resume:<input type="file" name="resume" id="resume">
    <button type="submit" name="submit">Apply  Now</button> 
    </form>

     //output sample[![check here for sample output][1]][1]

回答by Turcko007

For application/msword and application/vnd.ms-excel, when I deleted the size restriction:

对于 application/msword 和 application/vnd.ms-excel,当我删除大小限制时:

($_FILES["file"]["size"] < 20000)

...it worked ok.

...它工作正常。