note 73411 deleted from function.ini-get by nlopess

From: Date: Sat, 29 Dec 2007 11:41:09 +0000
Subject: note 73411 deleted from function.ini-get by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-134105@lists.php.net to get a copy of this message
Note Submitter: ben at qolc dot net ---- Re Webmaster at Grimchild's code As petrov says, grimchild's code doesn't "parse" the value, it just throws away the most significant part of it. Out of there you'll get a number but won't know whether it's bytes, kilobytes, megabytes or gigabytes! To parse the value you have to split off the character (if present) and multiply the number appropriately. Trivially: <?php $pms = ini_get('post_max_size'); if (preg_match('/^([\d\.]+)([gmk])?$/i', $pms, $m)) { $value = $m[1]; if (isset($m[2])) { switch(strtolower($m[2])) { case 'g': $value *= 1024; # fallthrough case 'm': $value *= 1024; # fallthrough case 'k': $value *= 1024; break; default: die("Can't parse value '$pms' "); } } print "$value bytes\n"; } else { die("Can't parse value '$pms' "); } ?> Note the cunning or horrible (depending on your viewpoint) use of fallthrough between cases in the switch statement, so that for example 'g' gets multiplied by 1024 three times. If you ever write code which intentionally uses switch fallthrough like the above, be a good boy/girl and comment it, else someday it will come and bite you or your unfortunate cow-orkers. It wouldn't surprise me if there's a PHP function to parse human-format sizes like this already (given that PHP itself has to do it).

« previous php.notes (#134105) next »