Steven
Steven

Reputation: 19425

Max file upload in bytes?

I'm using ini_get('upload_max_filesize') to get the max file upload size.
The result is 5M.

What is the easiest way to get this in bytes?

Upvotes: 8

Views: 10386

Answers (3)

FieryCat
FieryCat

Reputation: 1889

For PHP 7 the solution will return: 'A non well formed numeric value encountered'

It might be used:

function return_bytes($val)
{
    preg_match('/(?<value>\d+)(?<option>.?)/i', trim($string), $matches);
    $inc = array(
        'g' => 1073741824, // (1024 * 1024 * 1024)
        'm' => 1048576, // (1024 * 1024)
        'k' => 1024
    );
    
    $value = (int) $matches['value'];
    $key = strtolower(trim($matches['option']));
    if (isset($inc[$key])) {
        $value *= $inc[$key];
    }

    return $value;
}

return_bytes(ini_get('post_max_size'));

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038850

You could use the return_bytes from the documentation:

function return_bytes($val) {
    if (empty($val)) {
        $val = 0;
    }
    $val = trim($val);
    $last = strtolower($val[strlen($val)-1]);
    $val = floatval($val);
    switch($last) {
        // The 'G' modifier is available since PHP 5.1.0
        case 'g':
            $val *= (1024 * 1024 * 1024); //1073741824
            break;
        case 'm':
            $val *= (1024 * 1024); //1048576
            break;
        case 'k':
            $val *= 1024;
            break;
    }

    return $val;
}

return_bytes(ini_get('post_max_size'));

Upvotes: 23

Andrew Sharpe
Andrew Sharpe

Reputation: 78

Not enough rep to comment on the solution by @fierycat

Just need to change trim($string) to trim($val).

Upvotes: 2

Related Questions