Formatting filesize with PHP
A common task you might face when creating a web application is devising a simple, elegant method for formatting filesize. If you are using a PHP framework you most likely already have access to a function or method similar to below.
Format Filesize Code
/**
* Formats bytes to a human readable representation.
*
* @param int $bytes
*
* @return string
*/
function format_filesize($bytes) {
$labels = array('B', 'KB', 'MB', 'GB', 'TB');
foreach($labels AS $label){
if ($bytes > 1024){
$bytes = $bytes / 1024;
}
else {
break;
}
}
return round($bytes, 2) . $label;
}
?>
Code Explained
$labels = array('B', 'KB', 'MB', 'GB', 'TB');
?>
You will see the simple $bytes array containing labels for each size quantifier. The order of this is important.
foreach($labels AS $label){
if ($bytes > 1024){
$bytes = $bytes / 1024;
}
else {
break;
}
}
?>
Next we have the foreach construct allowing you to iterate or loop array members. So basically we are saying, "loop every member in $labels, and populate $label with our quantifier label".
We then if $bytes can still be divided by 1024 (1024B = 1KB, 1024KB = 1MB, etc), if so then we continue to divide it, otherwise we are done working with the $bytes var and we should break; out of the loop.
return round($bytes, 2) . $label;
?>
The loop has now stopped executing, we can then round the remaining size with the round() function, rounding to 2 decimal places for readability. Then the proper $label was assigned during that iteration so we can simply concatenate it with the '.' character.
Results
echo format_filesize(2000);
?>
Will output 1.95KB
echo format_filesize(23423234234);
?>
Will output 21.81GB
That concludes our tiny article on how to elegantly handle filesize formatting.

Comments
Post new comment