Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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 MB

The 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

Functions used in this recipe

  • round — Rounds a number to a given number of digits.
  • filesize — Returns the size of a file in bytes.
  • floor — Rounds a number down to the nearest integer.

Thanks for reading!

Donate to the site — we work hard for you.