PHP 上传文件类型、大小和存在?

PHP Upload File Type, Size and Existence?

我目前正在使用这个 PHP 代码来实现上传功能。我需要知道如何为 1) 扩展名、2) 文件大小限制和 3) 添加一些文件类型验证以检查是否确实选择了要上传的文件。

感谢您的帮助。

<?php
if(isset($_POST['submit'])){
    if(count($_FILES['upload']['name']) > 0){
        //Loop through each file
        for($i=0; $i<count($_FILES['upload']['name']); $i++) {
          //Get the temp file path
            $tmpFilePath = $_FILES['upload']['tmp_name'][$i];

            //Make sure we have a filepath
            if($tmpFilePath != "tmp/"){

                //save the filename
                $shortname = $_FILES['upload']['name'][$i];

                //save the url and the file
                $filePath = "uploads/" . date('d-m-Y-H-i-s').'-'.$_FILES['upload']['name'][$i];

                //Upload the file into the temp dir
                if(move_uploaded_file($tmpFilePath, $filePath)) {

                    $files[] = $shortname;
                    //insert into db 
                    //use $shortname for the filename
                    //use $filePath for the relative url to the file

                }
              }
        }
    }

          header('Location: http://localhost/FloodMap/report.html');
          exit;
}
?>

检查文件扩展名

$tmpFilePath = $_FILES['upload']['tmp_name'][$i];

    $imageFileType = pathinfo($tmpFilePath,PATHINFO_EXTENSION);

    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
        echo "Only JPG, JPEG, PNG & GIF files are allowed.";
    }

检查文件大小

if ($_FILES["upload"]["size"][$i] > 500000) {
    echo "Sorry, your file is too large.";
}

检查是否收到文件

if($_FILES['upload']['tmp_name'][$i]!=""){


}
  • 正在检查文件是否已成功上传

According to the manual PHP returns $_FILES 数组中的错误代码。例如...

if ($_FILES['upload']['error'] == UPLOAD_ERR_OK) {
    /* the file was uploaded successfully */
}
  • 检查文件扩展名

虽然 $_FILES 数组确实提供了扩展,但重要的是要记住这是 客户端提供的数据 因此它不能被信任。事实上,该数组中您唯一可以信任的是错误和 tmp_name,它由 PHP 提供。其他一切都来自客户端。

因此,要验证文件是否符合您的预期,您必须根据 finfo_file

之类的内容检查文件的魔术 MIME 字节
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $_FILES['upload']['tmp_name']);

$allowedMimes = ['image/jpg','image/gif','image/png'];

if (!in_array($mimeType, $allowedMimes, true)) {
    throw new FileException("File not allowed...");
}
  • 检查文件大小

同样,如前所述,虽然 $_FILES 数组为上传提供了大小键,但这是客户端提供的数据,不应被信任。相反,只需检查 filesize($_FILES['upload']['tmp_name']) 即可。这样您就可以检查文件的实际大小。


奖金

FWIW,在服务器级别检查文件大小(如果唯一的目的是告诉用户此文件太大)会带来相当糟糕的用户体验。最好先在客户端级别做这种事情,这样他们甚至在上传文件之前就知道文件是否太大了。

在HTML5中我们可以用File API来做到这一点。在您的表单中,只需附加一些事件侦听器,例如 onchange 或其他内容,然后检查 File.files[0].size 以提醒用户。您也可以对文件类型执行相同的操作。

当然,如果您需要用于其他目的,我并不是建议您不要在服务器端检查文件大小限制。只是说,就其本身而言,如果它是告诉用户他们上传的文件太大的唯一方式,它会削弱用户体验。