bytephp

get byte value from shorthand byte notation in php.ini


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.


Solution

  • The paragraph you linked to ends:

    You may not use these shorthand notations outside of php.ini, instead use an integer value of bytes. See the ini_get() documentation for an example on how to convert these values.

    This leads you to something like this (which I have slightly modified):

    function return_bytes($val)
    {
        $val  = trim($val);
    
        if (is_numeric($val))
            return $val;
    
        $last = strtolower($val[strlen($val)-1]);
        $val  = substr($val, 0, -1); // necessary since PHP 7.1; otherwise optional
    
        switch($last) {
            // The 'G' modifier is available since PHP 5.1.0
            case 'g':
                $val *= 1024;
            case 'm':
                $val *= 1024;
            case 'k':
                $val *= 1024;
        }
    
        return $val;
    }
    

    Use it like so:

    echo return_bytes("3M");
    // Output: 3145728
    

    There is no built-in function to perform this task; recall that, really, INI settings are designed for use internally within PHP. The PHP source uses a similar function to the above.