If, like me, you have to create software that deals with files, it will probably come in handy to show your users how big the files are, so that they know what they’re getting into when they click the download button. And since not everybody has a computer background, looking at how many bytes a file has is not the best solution. That’s why we have units of measurement for files that are more human readable. A kilobyte has 1024 bytes, a megabyte has 1024 kilobytes and so on.
Unix systems do that when listing files by using the -h flag option:
But other than that, we have to rely on the system functions that only return the size in bytes and work with that. This small but very useful function in PHP gets the size in bytes and by using a simple loop.
First, we define what the extensions for each measurement unit are, in a simple PHP array:
1 |
$prefixes = array('B', 'kB', 'MB', 'GB'); |
1 |
$limit = count($prefixes) - 1; |
1 2 |
if ($sizeInBytes < 1024 || $i >= $limit) return round($sizeInBytes, 2) . $prefixes[$i]; |
1 2 |
$i++; $sizeInBytes = $sizeInBytes / 1024; |
Full code below:
1 2 3 4 5 6 7 8 9 10 11 12 |
function filesize2String($sizeInBytes) { $prefixes = array('B', 'kB', 'MB', 'GB'); $limit = count($prefixes) - 1; $i = 0; while (true) { if ($sizeInBytes < 1024 || $i >= $limit) return round($sizeInBytes, 2) . $prefixes[$i]; $i++; $sizeInBytes = $sizeInBytes / 1024; } return $sizeInBytes . $prefixes[$i]; } |