How to show a file size in a readable form
Short answer
Divide the size by 1024 until it is below 1024, keeping track of the unit:
<?php
function formatSize(int $bytes): string
{
$units = ['B', 'KB', 'MB', 'GB'];
$index = 0;
while ($bytes >= 1024 && $index < count($units) - 1) {
$bytes /= 1024;
$index++;
}
return round($bytes, 1) . ' ' . $units[$index];
}
echo formatSize(532), ' | ', formatSize(1536), ' | ', formatSize(5242880);Output:
532 B | 1.5 KB | 5 MBThe size of a real file
filesize() returns the number of bytes:
<?php
$file = sys_get_temp_dir() . '/recipe-size.txt';
file_put_contents($file, str_repeat('a', 2048));
echo filesize($file) / 1024, ' KB';Output:
2 KB