9

这是我的上传表格:

<form action="uploads.php" method="post" enctype="multipart/form-data">
    <input name="fileupload" type="file" multiple>
    <button>Upload</button>
</form>

我的最大上传大小设置如下:

; Maximum allowed size for uploaded files.
upload_max_filesize = 5M

; Must be greater than or equal to upload_max_filesize
post_max_size = 5M

如果我上传一个更大的文件,那么 5Mvar_dump($_FILES)是空的。我可以这样做:

if($_FILES){
    echo "Upload done!";
}

$_FILES如果文件大于 5M,则不设置。但这有点奇怪。你会怎么做?

编辑:

超过 5M 的文件的 var_dump:

array(0) {
}

文件的 var_dump <= 5M:

array(1) {
  ["fileupload"]=>
  array(5) {
    ["name"]=>
    string(13) "netzerk12.pdf"
    ["type"]=>
    string(15) "application/pdf"
    ["tmp_name"]=>
    string(22) "/tmp/uploads/phpWhm8M0"
    ["error"]=>
    int(0)
    ["size"]=>
    int(352361)
  }
}
4

4 回答 4

12

你可以检查$_SERVER['CONTENT_LENGTH']

// check that post_max_size has not been reached
// convert_to_bytes is the function turn `5M` to bytes because $_SERVER['CONTENT_LENGTH'] is in bytes.
if (isset($_SERVER['CONTENT_LENGTH']) 
    && (int) $_SERVER['CONTENT_LENGTH'] > convert_to_bytes(ini_get('post_max_size'))) 
{
  // ... with your logic
  throw new Exception('File too large!');
}
于 2013-09-02T07:50:32.007 回答
5

就像Rob提到的,你的post_max_size应该大于你的upload_max_filesize.

之后您可以检查$_FILES['fileupload']['error']它是否是UPLOAD_ERR_INI_SIZE上传的文件太大。

所以在你的php.ini集合中

; Maximum allowed size for uploaded files.
upload_max_filesize = 5M

; Must be greater than or equal to upload_max_filesize
post_max_size = 10M

在您的uploads.php支票上

if($_FILES['fileupload']['error'] === UPLOAD_ERR_INI_SIZE) {
    // Handle the error
    echo 'Your file is too large.';
    die();
}
// check for the other possible errors 
// http://php.net/manual/features.file-upload.errors.php
于 2013-09-02T08:05:31.627 回答
2

我有同样的问题,$_FILES如果上传的文件太大,哪里会是空的。基于xdazzFlorian的解决方案,我得出结论:

  • 如果文件大小大于post_max_size$_FILES则为空,$_FILES['fileupload']['error']因此未定义:使用 xdazz 的解决方案。Warning: POST Content-Length of xxx bytes exceeds the limit of yyy bytes in Unknown on line 0但是,您会收到来自 PHP ( )的警告消息。
  • 如果文件大小介于post_max_size和之间upload_max_filesize,那么您可以使用$_FILES['fileupload']['error'],而不必担心 PHP 警告消息。

简而言之,使用以下代码:

    if (isset($_SERVER['CONTENT_LENGTH']) &&
        (int) $_SERVER['CONTENT_LENGTH'] > (1024*1024*(int) ini_get('post_max_size'))) 
    {
        // Code to be executed if the uploaded file has size > post_max_size
        // Will issue a PHP warning message 
    }

    if ($_FILES[$this->name]['error'] === UPLOAD_ERR_INI_SIZE) {
        // Code to be executed if the uploaded file has size between upload_max_filesize and post_max_size
        // Will not issue any PHP warning message
    }
于 2016-06-05T17:37:10.297 回答
-1

您应该将允许的最大文件大小设置为超过 5M,然后使用 PHP 检查文件大小是否超过 5M。确保您的网络服务器帖子正文大小也更新为新大小。

基于 php ini 限制文件大小不是最好的解决方案,因为它会限制你。如果您想在另一个脚本中检查另一个不超过 3MB 的文件怎么办?

 if ($_FILES['fileupload']['size'] > 5242880) // 5242880 = 5MB
      echo 'your file is too large';
于 2013-09-02T07:44:09.410 回答