这是我的上传表单:
<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
如果我上传的文件较大,那么5M var_dump($_FILES)
为空。我能做到:
if($_FILES){
echo "Upload done!";
}
如果文件大于5M,则不设置 $_FILES
。但这有点奇怪。你会怎么做?
修改
超过5M的文件的var_dump:
array(0) {
}
文件的var_dump&lt; = 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)
}
}
答案 0 :(得分:9)
您可以查看$_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!');
}
答案 1 :(得分:4)
与上述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
答案 2 :(得分:1)
我遇到了同样的问题,如果上传的文件太大,$_FILES
将为空。根据{{3}}和xdazz的解决方案,我得出结论:
post_max_size
,则$_FILES
为空,因此未定义$_FILES['fileupload']['error']
:使用xdazz的解决方案。但是,您会收到来自PHP(Warning: POST Content-Length of xxx bytes exceeds the limit of yyy bytes in Unknown on line 0
)的警告消息。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
}
答案 3 :(得分:-1)
您应该将允许的最大文件大小设置为大于5M,然后使用PHP检查文件大小是否超过5M。确保您的网络服务器帖子正文大小也使用新大小进行更新。
基于php ini限制文件大小不是最好的解决方案,因为它会限制你。如果要在另一个脚本中检查另一个不超过3MB的文件怎么办?
if ($_FILES['fileupload']['size'] > 5242880) // 5242880 = 5MB
echo 'your file is too large';