首页 > 解决方案 > PHP中文件上传If语句的测试错误

问题描述

这是我在 Stack Overflow 上的第一篇文章,所以请耐心等待我 - 我已经求助于发布,因为否则我无法通过 Google/Stack Overflow 找到答案。

我是 PHP 新手,正在学习如何添加文件上传。我有一个非常基本的 html 表单,它指向一个 PHP 页面。

            <form action="UploadPage.php" method="post" enctype="multipart/form-data">
            <input type="hidden" name="MAX_FILE_SIZE" value="100000"/>
            <input type="file" name="uploadedXML"/>
            <input type="submit" value="Upload"/>

处理文件上传的 PHP 代码有一系列 if 语句来检查文件的类型大小是否正确等。如果有错误,则会在错误页面上生成相应的错误消息。

我一直在测试上传各种文件类型,以确定错误语句是否正确发生,第二个(检查文件类型)和第三个(检查文件大小)有问题。

如果文件类型检查 if 语句首先出现,我发现如果我上传大于最大大小(100kb)的 XML 文件,我仍然会收到与文件类型检查有关的错误消息 - 当我应该收到错误消息时与文件大小有关。

但是,如果我交换 IF 语句以便文件大小检查在文件类型检查之前进行,如果我上传不正确的文件类型但大小合适(例如小图像),我会收到与文件太大有关的错误消息,当我期待与文件类型有关的文件不正确时。

<?php

        const UploadKey = 'uploadedXML';
        const AllowedTypes = ['application/xml','text/xml'];

session_start();


/*Checking for errors*/

if (empty($_FILES[UploadKey]['name'])){//check file actually been uploaded
    header("Location: ErrorPage.php"); 
    $_SESSION['errorMessage']="You forgot to add your file!";
    die();
}

if (!in_array($_FILES[UploadKey]['type'],AllowedTypes)){//Check correct type of file
    header("Location: ErrorPage.php"); 
    $_SESSION['errorMessage']="We only accept XML files I'm afraid";
    die();
    }


if ($_FILES[UploadKey]['error'] == 2) {//Check if size too big
header("Location: ErrorPage.php"); 
       $_SESSION['errorMessage']="Your file is too big for us to handle, awkward! Please choose a file under 100KB.";
        die();
       }

$tempFileLoc = $_FILES[UploadKey]['tmp_name'];
$destFileLoc = 'Uploads/'.$_FILES[UploadKey]['name'];

if (file_exists($destFileLoc)) {// Check if file already exists
    header("Location: ErrorPage.php"); 
    $_SESSION['errorMessage']="We've already got this file, thanks though";
    die();
    }

if ($_FILES[UploadKey]['error']>0){
    header("Location: ErrorPage.php"); 
    $_SESSION['errorMessage']="Unfortunately there's been an error with the uploading process";
    die();
    }

如果您需要查看我的更多代码来帮助回答,请告诉我。

首先十分感谢!

标签: phpformsfileupload

解决方案


That issue was caused as a result of the MAX_FILE_SIZE you included in the HTML form.

If the file you are uploading exceeds the MAX_FILE_SIZE set in the form, PHP automatically empties the tmp_name and type and also turns size to 0 for the file ($_FILES).

So $_FILES[UploadKey]['type'] is empty, thereby the condition you are using to check whether the file type is allowed will return false.

To correct that, you should also check to make sure the type is not empty as well if (!empty($_FILES[UploadKey]['type']) && !in_array($_FILES[UploadKey]['type'],AllowedTypes)

Something like this:

<?php

  if (!empty($_FILES[UploadKey]['type']) && !in_array($_FILES[UploadKey]['type'],AllowedTypes)){// Make sure the file type is not empty
    header("Location: ErrorPage.php"); 
    $_SESSION['errorMessage']="We only accept XML files I'm afraid";
    die();
  }


推荐阅读