检测上传的文件是否过大

tun*_*una 9 php file-upload

这是我的上传表格:

<form action="uploads.php" method="post" enctype="multipart/form-data">
    <input name="fileupload" type="file" multiple>
    <button>Upload</button>
</form>
Run Code Online (Sandbox Code Playgroud)

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

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

; Must be greater than or equal to upload_max_filesize
post_max_size = 5M
Run Code Online (Sandbox Code Playgroud)

如果我上传的文件大于5M var_dump($_FILES)则为空.我能做到:

if($_FILES){
    echo "Upload done!";
}
Run Code Online (Sandbox Code Playgroud)

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

编辑:

文件的var_dump超过5M:

array(0) {
}
Run Code Online (Sandbox Code Playgroud)

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)
  }
}
Run Code Online (Sandbox Code Playgroud)

xda*_*azz 10

你可以查看$_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!');
}
Run Code Online (Sandbox Code Playgroud)


Flo*_*ell 5

就像罗布提到的那样,您的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
Run Code Online (Sandbox Code Playgroud)

在您的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
Run Code Online (Sandbox Code Playgroud)