PHP get actual maximum upload size

前端 未结 6 476
Happy的楠姐
Happy的楠姐 2020-12-04 16:38

When using

ini_get(\"upload_max_filesize\");

it actually gives you the string specified in the php.ini file.

It is not good to use

6条回答
  •  庸人自扰
    2020-12-04 16:53

    Here is the full solution. It takes care of all traps like the shorthand byte notation and also considers post_max_size:

    /**
    * This function returns the maximum files size that can be uploaded 
    * in PHP
    * @returns int File size in bytes
    **/
    function getMaximumFileUploadSize()  
    {  
        return min(convertPHPSizeToBytes(ini_get('post_max_size')), convertPHPSizeToBytes(ini_get('upload_max_filesize')));  
    }  
    
    /**
    * This function transforms the php.ini notation for numbers (like '2M') to an integer (2*1024*1024 in this case)
    * 
    * @param string $sSize
    * @return integer The value in bytes
    */
    function convertPHPSizeToBytes($sSize)
    {
        //
        $sSuffix = strtoupper(substr($sSize, -1));
        if (!in_array($sSuffix,array('P','T','G','M','K'))){
            return (int)$sSize;  
        } 
        $iValue = substr($sSize, 0, -1);
        switch ($sSuffix) {
            case 'P':
                $iValue *= 1024;
                // Fallthrough intended
            case 'T':
                $iValue *= 1024;
                // Fallthrough intended
            case 'G':
                $iValue *= 1024;
                // Fallthrough intended
            case 'M':
                $iValue *= 1024;
                // Fallthrough intended
            case 'K':
                $iValue *= 1024;
                break;
        }
        return (int)$iValue;
    }      
    

    This is an error-free version of this source: http://www.smokycogs.com/blog/finding-the-maximum-file-upload-size-in-php/ .

提交回复
热议问题