This is my upload form:
Like Rob mentioned, your post_max_size
should be greater than your upload_max_filesize
.
After that you can check $_FILES['fileupload']['error']
if it is UPLOAD_ERR_INI_SIZE
the uploaded file is to large.
So in your php.ini
set
; Maximum allowed size for uploaded files.
upload_max_filesize = 5M
; Must be greater than or equal to upload_max_filesize
post_max_size = 10M
In your uploads.php
check
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
You could check the $_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!');
}
I had the same problem, where $_FILES
would be empty if the uploaded file is too large. Based on the solutions of xdazz and Florian, I concluded that:
post_max_size
, then $_FILES
is empty and $_FILES['fileupload']['error']
is therefore not defined: use the solution of xdazz. However, you get a warning message from PHP (Warning: POST Content-Length of xxx bytes exceeds the limit of yyy bytes in Unknown on line 0
).post_max_size
and upload_max_filesize
, in that case you can use $_FILES['fileupload']['error']
, without having to be bothered with PHP warning messages.In short use the following code:
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
}
You should set the max allowed file size more than 5M, then with PHP check if the file size exceed 5M. Make sure your webserver post body size is updated with the new size as well.
Limiting file size based on php ini is not the best solution, because it will limit you. What if you want to check another file not exceed 3MB in another script?
if ($_FILES['fileupload']['size'] > 5242880) // 5242880 = 5MB
echo 'your file is too large';