PHP Logo

PHP – Obtain the maximum allowed file upload size

Posted by

This was actually remarkably difficult to do, in terms of the volume of code required. It uses the fact that there are 3 things which affect the size of a file which can be uploaded: upload_max_filesize, post_max_size and memory_limit. The below code is useful for providing the user with the upload limit on a file upload form.

The code also uses the PHP quirk feature whereby casting a string, which starts with digits, to int will return the int value of the first digits – e.g. (int)’123abc321′ evaluates to 123.

This may, however, be a ridiculous way to do it  and an easier way may exist. Feel free to comment if you know one.

function max_upload_size() {
    // Multipliers to make byte values from php.ini shorthand
    $suffix_multipliers = array(
        'K'=>1024,
        'M'=>1024*1024,
        'G'=>1024*1024*1024
    );

    // Values to consider
    $vals = array(
        'upload' => ini_get('upload_max_filesize'),
        'post' => ini_get('post_max_size'),
        'mem' => ini_get('memory_limit')
    );

    // Convert above values to bytes based on their shorthand notation
    $byte_vals = array();

    foreach ($vals as $name=>$val) {
        if ($suffix = preg_match('/[a-z]+$/i', $val, $matches)) {
            // "10M" cast to int is 10
            if (isset($suffix_multipliers[$matches[0]])) {
                $byte_vals[$name] = (int)$val * $suffix_multipliers[$matches[0]];
            }
            else {
                $byte_vals[$name] = (int)$val;
            }
        }
    }

    // Get the key(s) of the smallest entries
    $smallest_keys = array_keys($byte_vals, min($byte_vals));
    // Get one of these
    $smallest_key = reset($smallest_keys);

    // Return the smallest
    return $vals[$smallest_key];
}

One comment

Leave a Reply

Your email address will not be published.