Covert PHP config size values to bytes

Convert PHP config value (2M, 8M, 200K…) to bytes. Use full when converting values received, for an example, through ini_get(‘memory_limit’).

function php_config_value_to_bytes($val) {
    $val = trim($val);
    $last = strtolower($val{strlen($val)-1});
    switch($last) {
      // The 'G' modifier is available since PHP 5.1.0
      case 'g':
        $val *= 1024;
      case 'm':
        $val *= 1024;
      case 'k':
        $val *= 1024;
    } // if

    return (integer) $val;
  } // php_config_value_to_bytes

One thought on “Covert PHP config size values to bytes

  1. If you typecast the returned value as a float instead of an integer your function will return larger numbers that are required to covert strings larger than 1G. For an example, check what your function returns when you try to convert 8G. It returns 0. Then typecast the returned value as a float and you will see the true value in bytes.

Leave a Reply

Your email address will not be published. Required fields are marked *