I need to test the value returned by ini_get(\'memory_limit\')
and increase the memory limit if it is below a certain threshold, however this ini_get(\'me
I think you're out of luck. The PHP manual for ini_get() actually addresses this specific problem in a warning about how ini_get() returns the ini values.
They provide a function in one of the examples to do exactly this, so I'm guessing it's the way to go:
function return_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;
}
return $val;
}
They have this to say about the above function: "The example above shows one way to convert shorthand notation into bytes, much like how the PHP source does it."
Since you will get an error with newer versions of PHP if the value has a CHAR at the end of it, you might need some extra testing:
private function toBytes($str){
$val = trim($str);
$last = strtolower($str[strlen($str)-1]);
if (!is_numeric($last)) {
$val = substr($val,0,strlen($val)-1);
switch($last) {
case 'g': $val *= 1024;
case 'm': $val *= 1024;
case 'k': $val *= 1024;
}
}
return $val;
}
This works with no warnings
even if the solutions above are correct, the switch
statement without a break
is not very intuitive and for an improved readability, to express what is really going on, I would rather do it this way:
/**
* @return int maximum memory limit in [byte]
*/
private static function takeMaximumFootprint()
{
$memory = ini_get('memory_limit');
$byte = intval($memory);
$unit = strtolower($memory[strlen($memory) - 1]);
switch ($unit) {
case 'g':
$byte *= 1024 * 1024 * 1024; break;
case 'm':
$byte *= 1024 * 1024; break;
case 'k':
$byte *= 1024; break;
}
return $byte;
}
Or some shorter version, if you please
function toInteger ($string)
{
sscanf ($string, '%u%c', $number, $suffix);
if (isset ($suffix))
{
$number = $number * pow (1024, strpos (' KMG', strtoupper($suffix)));
}
return $number;
}
From the PHP website for ini_get():
function return_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;
}
return $val;
}
I can only think of a slight variation on what you're doing:
function int_from_bytestring($byteString) {
$ret = 0;
if (preg_match('!^\s*(\d+(?:\.\d+))\s*([KMNGTPE])B?\s*$!', $byteString, $matches)) {
$suffix = " KMGTPE";
$index = strpos($suffix, $matches[2]);
if ($index !== false) {
$ret = $matches[1];
while ($index--) {
$matches *= 1024;
}
}
}
return intval($ret);
}