24

我可以很好地上传图像,但是当我将类型从 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."
}
4

7 回答 7

40

不要使用该['type']参数来验证上传。该字段是用户提供的,可以轻松伪造,允许上传任何类型的文件。参数也是如此['name']- 这是用户提供的文件名。伪造也是微不足道的,所以用户发送nastyvirus.exe和调用它cutekittens.jpg

验证上传的正确方法是使用服务器端 mime-type 确定,例如通过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(...);

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

于 2012-07-22T15:17:17.000 回答
9

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

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

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

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

$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].');
}
于 2012-07-22T15:09:01.040 回答
7
$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";
}
于 2015-12-18T08:01:51.700 回答
2

你的条件之一是失败。检查文件的 mime-type 值。
尝试使用应用程序/pdf,而不是文本/pdf。请参阅PDF 文件的正确 MIME 媒体类型

于 2012-07-22T15:05:02.990 回答
1

您可以使用

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

如果发生任何类型的错误,则返回 'error' 否则返回 1,2,3,4 或 1 如果完成

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

于 2016-01-06T19:11:37.483 回答
0
    <?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]
于 2019-01-04T12:04:31.383 回答
-1

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

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

...它工作正常。

于 2014-07-22T18:56:31.557 回答