get byte value from shorthand byte notation in php.ini

Viewed 6067

Is there any way to get the byte values from the strings returned from functions like ini_get('upload_max_filesize') and ini_get('post_max_size') when they are using shorthand byte notation? For example get 4194304 from 4M ? I could hack together a function that does this but I would be surprised if there wasn't some built in way of doing this.

6 Answers

This is my suggestion which should be future-proof (with regard to PHP Versions 7++)!

function return_bytes($val, $gotISO = false) {        
    // This is my ultimate "return_bytes" function!
    // Converts (not only) the PHP shorthand notation which is returned by e.g. "ini_get()"
    // Special features:
    // Doesn't need regular expression and switch-case conditionals.
    // Identifies beside "Kilo", "Mega" and "Giga" also "Tera", "Peta", "Exa", "Zetta", and "Yotta" too!
    // Ignores spaces and doesn't make no difference between e.g. "M" or "MB"!
    // By default possible commas (,) as thousand separator will be erased. Example: "1,000.00" will "be 1000.00".
    // If ($gotISO == true) it converts ISO formatted values like "1.000,00" into "1000.00".
    $pwr = 0;
    if(empty($val)) return 0;
    $val  = trim($val);
    if (is_numeric($val)) return $val;
    if ($gotISO) {
        $val = str_replace('.','',$val); // wipe possibe thousend separators (.)
        $val = str_replace(',','.',$val); // convert ISO comma to value point
    } else {
        $val = str_replace(',','',$val); // wipe possibe thousend separators (,)
    }
    $val = str_replace(' ','',$val);
    if (floatval($val) == 0) return 0;
    if (stripos($val, 'k') !== false) $pwr = 1;
        elseif (stripos($val, 'm') !== false) $pwr = 2;
        elseif (stripos($val, 'g') !== false) $pwr = 3;
        elseif (stripos($val, 't') !== false) $pwr = 4;
        elseif (stripos($val, 'p') !== false) $pwr = 5;
        elseif (stripos($val, 'e') !== false) $pwr = 6;
        elseif (stripos($val, 'z') !== false) $pwr = 7;
        elseif (stripos($val, 'y') !== false) $pwr = 8;
    $val *= pow(1024, $pwr);
    return $val;
}

... have fun with it!

Neither one of the Version shown above will work with PHP 7.2x anymore, as I found out.By use of this,with PHP 7.0 + 7.1, it works, but not with PHP 7.x Ernie

private function return_bytes ($val) {
        if(empty($val))return 0;
        $val = trim($val);
        preg_match('#([0-9]+)[\s]*([a-z]+)#i', $val, $matches);
        $last = '';
        if(isset($matches[2])){
            $last = $matches[2];
        }
        if(isset($matches[1])){
            $val = (int) $matches[1];
        }
        switch (strtolower($last)){
            case 'g':
            case 'gb':  
            $val *= 1024;
            case 'm':
            case 'mb':
            $val *= 1024;
            case 'k':
            case 'kb':
            $val *= 1024;
        }
        return (int) $val;
    }
Related