PHP 上传文件类型和大小检查

PHP Upload with file type and size check

我需要一个其他人可以使用的上传表格,以便将他们的文件交给我。

HTML:

<form method="post" action="upload.php" enctype="multipart/form-data" id="form">
<table>
<tr><td><p>your name:</p></td></tr>
<tr><td><input name="name" type="text" size="50" style="height: 30px;"></td></tr>
<tr><td><p>your mail-adress:</p></td></tr>
<tr><td><input name="mail" type="text" size="50" style="height: 30px;"></td></tr>
<tr><td><p>your document:</p></td></tr>
<tr><td><input type="file" name="file" value="" /><br /><h6 style="margin-top: 5px; margin-bottom: 2px;">max. filesize: 2 MB<br />allowed filetypes: .doc, .docx, .pdf, .rtf, .odt</h6></td></tr>
</table>
<br />
<input type="submit" value="Send">
</form>

PHP:

<?php
$fehler = "";
$name = $_POST['name'];
$mail = $_POST['mail'];
$file = $_POST['file'];
$maxsize = "2097152";   /* 2MB in Bytes */
$allowedext =  array('doc','docx' ,'pdf', 'rtf', 'odt');

  if (empty($name)) {
   $fehler .= "<p>&bull; no name given!</p>" ;
  }
  if (empty($mail)) {
   $error .= "<p>&bull; no e-mail adress given</p>" ;
  }
  if (empty($file)) {
   $error .= "<p>&bull; choose a file!</p>" ;
  }
  if (empty($error)) {
   if (!in_array(filetype($file), $allowedext) { /* check filetype */
   $error .= "<p>&bull; filetype is not allowed</p>" ;
}
if (empty($error)) {
   if (filesize($file) > $maxsize) { /* check filesize */
    $error .= "<p>&bull; file is too big</p>" ;
   }
   if (empty($error)) {
    /* send data via mail */
    echo("your document has been send.");
   }
  }
}
echo($error);
echo ('<p><a href="../send_article">back</a></p>');
?>

我想在上传前检查文件类型和大小。当我将 upload.php 文件上传到我的服务器时,如果我尝试使用此表单,我只会看到一个没有任何错误的白屏。

此答案提供了在将数据上传到服务器之前检查大小的解决方案。这是有道理的。如果您进行客户端检查,则可以消除向您的服务器发送不必要的帖子。仍然需要对服务器进行完整性检查,可以更改客户端上的 JavaScript 代码。其他答案提供了有关如何改进服务器端代码的说明。

var mimeTypes = [
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document", //docx
    "application/pdf", //pdf
    "application/msword", //doc
    "rtf;application/rtf", //rtf
    "rtf;application/x-rtf",
    "rtf;text/richtext",
    "application/vnd.oasis.opendocument.text" //odt
    ]

function readFiles(files)
{
    var iMax = files.length;
    var sum = "";
    var max = 2097152;
    for (var i = 0; i < iMax; i++) 
    {
        var fileType = files[i].type;
        var fileSize = files[i].size;
        sum += parseInt(fileSize);

        if (mimeTypes.indexOf(files[i].type) == -1)
        {   
            alert("Invalid file selected");
            return false;
        }
    }
    if (sum > max)
    {
        alert("Total file size exceeds maximum upload size.");
        return false;
    }

    return true;
}
document.getElementById("form").querySelector("input[type='file']").addEventListener("change", readFiles, false);

readFiles 每当 change 事件 在文件输入上触发时触发。在支持 HTML5 输入元素的浏览器中 你可以读出 file typefile size 属性。它们继承自 Blob 对象。您甚至可以将文件传递给 FileReader 对象,从而允许您读取文件的内容。

Bug in IE 10, 11. On IE10 and 11 there is a bug present that returns an empty string on file-type when used on images. You can work around this by checking the extension.

有趣....我喜欢更少的代码行...

<form method="post" action="upload.php" enctype="multipart/form-data" id="form">
<table>
<tr><td><p>your name:</p></td></tr>
<tr><td><input required="required" name="name" type="text" size="50" style="height: 30px;"></td></tr>
<tr><td><p>your mail-adress:</p></td></tr>
<tr><td><input required="required" name="mail" type="text" size="50" style="height: 30px;"></td></tr>
<tr><td><p>your document:</p></td></tr>
<tr><td><input required="required" type="file" name="file" value="" /><br /><h6 style="margin-top: 5px; margin-bottom: 2px;">max. filesize: 2 MB<br />allowed filetypes: .doc, .docx, .pdf, .rtf, .odt</h6></td></tr>
</table>
<br />
<input type="submit" value="Send">
</form>

php :

<?php
define('MB', 1048576);
$name = $_POST['name'];
$mail = $_POST['mail'];
$file = $_FILES['file'];
$allowedext =  array('doc','docx' ,'pdf', 'rtf', 'odt');
$filename = $file['tmp_name'];
$ext=explode(".",$filename);
if( empty($name) || empty($mail) || empty($file) || $_FILES['file']['size'] > 2*MB || !in_array($ext[1],$allowedext) )
{
echo "check file extension or check whether all fields are filled correctly!";
exit;
}
else
{
 move_uploaded_file(name, name);
 echo "File has been uploaded successfully!";
}
?>

将您的 $_POST['file'] 更改为 $_FILES['file']

并尝试:

// check maximum size 
        if($_FILES['file']['size'] > $maxsize) 
         die('The file is too large');
// check file format
        elseif( !in_array(pathinfo(strtolower($_FILES['files']['name']), PATHINFO_EXTENSION),$allowedex))
         die($_FILES['files']['name'].' is not a valid format.');