Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

php - Detect if uploaded file is too large

This is my upload form:

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

My max upload sizes are set like this:

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

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

If I upload a file that is larger then 5M var_dump($_FILES) is empty. I can do that:

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

$_FILES is not set if the file is larger then 5M. But this is a bit strange. How would you do that?

EDIT:

var_dump of file over 5M:

array(0) {
}

var_dump of file <= 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)
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!');
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...