note 62656 deleted from function.filesize by aidan

From: Date: Sat, 02 May 2009 11:19:02 +0000
Subject: note 62656 deleted from function.filesize by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-154124@lists.php.net to get a copy of this message
Note Submitter: jiquera at yahoo dot com ---- here a piece of code to format a filesize: <?php function formatbytes($val, $digits = 3, $mode = "SI", $bB = "B"){ //$mode == "SI"|"IEC", $bB == "b"|"B" $si = array("", "k", "M", "G", "T", "P", "E", "Z", "Y"); $iec = array("", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi"); switch(strtoupper($mode)) { case "SI" : $factor = 1000; $symbols = $si; break; case "IEC" : $factor = 1024; $symbols = $iec; break; default : $factor = 1000; $symbols = $si; break; } switch($bB) { case "b" : $val *= 8; break; default : $bB = "B"; break; } for($i=0;$i<count($symbols)-1 && $val>=$factor;$i++) $val /= $factor; $p = strpos($val, "."); if($p !== false && $p > $digits) $val = round($val); elseif($p !== false) $val = round($val, $digits-$p); return round($val, $digits) . " " . $symbols[$i] . $bB; } //some test cases: function test($i, $digits = 3, $mode = "SI", $bB = "B"){ echo $i . " = " . formatbytes($i, $digits, $mode, $bB) . "<br>\n"; } test(1024); test(1024*1024); test(1024*1024, 4); test(1024*1024, 3, "IEC"); test(1024, 3, "SI", "b"); test(32423); test(323); test(128, "3", "IEC", "b"); test(324235236362453); test(32423535424236324362453, 3, "IEC"); //actual use: echo formatbytes(file_size("myfile.php")); ?> it formats to bit or bytes according to SI or IEC and rounded to a given number of digits.

« previous php.notes (#154124) next »