note 98477 deleted from function.filesize by aharvey
| From: | aharvey@php.net | Date: | Tue, 22 Jan 2013 00:18:23 +0000 |
| Subject: | note 98477 deleted from function.filesize by aharvey | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-193317@lists.php.net to get a copy of this message | ||
Note Submitter: martinjohn dot sweeny at gmail dot com
----
Here is a quick function for getting a nicer filesize from a number:
<?php
function formatBytes($b,$p = null) {
/**
*
* @author Martin Sweeny
* @version 2010.0617
*
* returns formatted number of bytes.
* two parameters: the bytes and the precision (optional).
* if no precision is set, function will determine clean
* result automatically.
*
**/
$units =
array("B","kB","MB","GB","TB","PB","EB","ZB","YB");
$c=0;
if(!$p && $p !== 0) {
foreach($units as $k => $u) {
if(($b / pow(1024,$k)) >= 1) {
$r["bytes"] = $b / pow(1024,$k);
$r["units"] = $u;
$c++;
}
}
return number_format($r["bytes"],2) . " " . $r["units"];
} else {
return number_format($b / pow(1024,$p)) . " " . $units[$p];
}
}
echo formatBytes(81000000); //returns 77.25 MB
echo formatBytes(81000000,0); //returns 81,000,000 B
echo formatBytes(81000000,1); //returns 79,102 kB
?>
Feel free to email me if you can think of improvements!