note 22946 deleted from function.filesize by tomsommer
| From: | tomsommer@php.net | Date: | Wed, 01 Sep 2004 17:33:54 +0000 |
| Subject: | note 22946 deleted from function.filesize by tomsommer | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-75885@lists.php.net to get a copy of this message | ||
Note Submitter: andreaSPAMLESS@SPAMLESScriticalbitDOTcom
----
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.