Detect if uploaded file is too large

前端 未结 4 1271
悲哀的现实
悲哀的现实 2020-12-07 01:10

This is my upload form:

4条回答
  •  心在旅途
    2020-12-07 02:04

    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:

    • If the file size is greater than 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).
    • If the file size is between 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
        }
    

提交回复
热议问题