Thursday, July 12, 2007

PHP function to make a file size human-readable

Problem: You're working in PHP and you have a file size in bytes. You'd like to make it easier to read.

Answer: This quick function I created. It accepts the byte count and returns a human-readable file size string:
// make file size human-readable
function byte_size($bytes)
{
switch(1)
{
case ($bytes < pow(2, 10)): // bytes
$size = number_format($bytes) . ' B';
break;
case ($bytes < pow(2, 20)):
$size = number_format($bytes / pow(2, 10)) . ' kB'; // kilobytes
break;
case ($bytes < pow(2, 30)):
$size = number_format($bytes / pow(2, 20)) . ' MB'; // megabytes
break;
case ($bytes < pow(2,40)):
$size = number_format($bytes / pow(2,30)) . ' GB'; // gigabytes
break;
case ($bytes < pow(2,50)):
$size = number_format($bytes / pow(2,40)) . ' TB'; // terabytes
break;
case ($bytes < pow(2,60)):
$size = number_format($byes / pow(2,50)) . ' PB'; // pedabytes
break;
default: // a famous man once said, "a PC will never need more than 640 kB of RAM"
$size = number_format($bytes) . ' B';
}

return $size;
}

No comments: