PHP

Human-Readable File Size

admin by @admin ADMIN
Jun 13, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Format a byte count as a human-friendly string (KB / MB / GB / TB). Defaults to base-1024 sizes; pass base 1000 for SI units.
PHP
Raw
<?php
function humanBytes(int $bytes, int $precision = 1, int $base = 1024): string {
    $units = $base === 1000
        ? ['B','kB','MB','GB','TB','PB']
        : ['B','KiB','MiB','GiB','TiB','PiB'];
    if ($bytes <= 0) return '0 B';
    $i = (int)floor(log($bytes, $base));
    $i = min($i, count($units) - 1);
    return round($bytes / ($base ** $i), $precision) . ' ' . $units[$i];
}

echo humanBytes(1536);                  // 1.5 KiB
echo humanBytes(1_500_000, 2, 1000);    // 1.50 MB
echo humanBytes(filesize('big.zip'));   // e.g. 4.2 GiB
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.