note 39143 deleted from function.filesize by tomsommer
| From: | tomsommer@php.net | Date: | Wed, 01 Sep 2004 17:31:27 +0000 |
| Subject: | note 39143 deleted from function.filesize by tomsommer | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-75872@lists.php.net to get a copy of this message | ||
Note Submitter: jsheets at shadonet dot com
----
This function converts bytes to a human readable format, by default it scales from bytes to
terabytes but you can also supply your own names to localize it to other languages or extend it
beyond terabytes.
/**
* Converts bytes to a human readable string
* @param int $bytes Number of bytes
* @param int $precision Number of decimal places to include in return string
* @param array $names Custom usage strings
* @return string formatted string rounded to $precision
*/
function bytesToHumanReadableUsage($bytes, $precision = 2, $names = '')
{
if (!is_numeric($bytes) || $bytes < 0) {
return false;
}
for ($level = 0; $bytes >= 1024; $level++) {
$bytes /= 1024;
}
switch ($level)
{
case 0:
$suffix = (isset($names[0])) ? $names[0] : 'Bytes';
break;
case 1:
$suffix = (isset($names[1])) ? $names[1] : 'KB';
break;
case 2:
$suffix = (isset($names[2])) ? $names[2] : 'MB';
break;
case 3:
$suffix = (isset($names[3])) ? $names[3] : 'GB';
break;
case 4:
$suffix = (isset($names[4])) ? $names[4] : 'TB';
break;
default:
$suffix = (isset($names[$level])) ? $names[$level] : '';
break;
}
if (empty($suffix)) {
trigger_error('Unable to find suffix for case ' . $level);
return false;
}
return round($bytes, $precision) . ' ' . $suffix;
}
// example with an existing integer
print bytesToHumanReadableUsage('1024');
// example with a local filesystem file
print bytesToHumanReadableUsage(filesize('picture.jpg'));