note 22946 added to function.filesize

From: Date: Thu, 04 Jul 2002 20:29:49 +0000
Subject: note 22946 added to function.filesize
Groups: php.notes 
Request: Send a blank email to php-notes+get-32601@lists.php.net to get a copy of this message
I've just implemented an easy&extensible function for calculating file size in an human readable format. It does'n check any file, it just formats any given number. Hope it helps anyone ;) /** * Format file size in a human-readable way * such as "xx Megabytes" or "xx Mo" * * @author Andrea Paleni <andreaSPAMLESS_AT_SPAMLESScriticalbit.com> * @version 1.0 * @param int bytes is the size * @param bool base10 enable base 10 representation, otherwise * default base 2 is used * @param int round number of fractional digits * @param array labels strings associated to each 2^10 or * 10^3(base10==true) multiple of base units */ function hbytes ($bytes, $base10=false, $round=0, $labels=array('bytes', 'Kb', 'Mb', 'Gb')) { if (($bytes <= 0) || (! is_array($labels)) || (count($labels) <= 0)) return null; $step = $base10 ? 3 : 10 ; $base = $base10 ? 10 : 2; $log = (int)(log10($bytes)/log10($base)); krsort($labels); foreach ($labels as $p=>$lab) { $pow = $p * $step; if ($log < $pow) continue; $text = round($bytes/pow($base,$pow),$round) . $lab; break; } return $text; } Notice that you can pass any number of labels: the function automatically uses the biggest one available. E.g. If you pass only "bytes" , then every file will have it's size printed in bytes. (almost useless...) If you add "Kb" , then any filesize bigger than 1Kb will use Kb instead. Works similarly for any bigger unit until Tera or even Peta bytes :) Maybe there's some bug I didn't notice (Murphy docet) , so please warn me if it occurs. -- http://www.php.net/manual/en/function.filesize.php http://master.php.net/manage/user-notes.php?action=edit+22946 http://master.php.net/manage/user-notes.php?action=delete+22946 http://master.php.net/manage/user-notes.php?action=reject+22946

« previous php.notes (#32601) next »