Convert File Size in Bytes into Human Readable String using PHP

Calculate by formula

<?php

function formatFileSize(float $size, int $decimals = 2, bool $binarySystem = true): string
{
    if ($binarySystem) {
        $units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB'];
        $largestUnit = 'YiB';
        $step = 1024;
    } else {
        $units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB'];
        $largestUnit = 'YB';
        $step = 1000;
    }

    foreach ($units as $unit) {
        if ($size < $step) {
            return sprintf('%.'.$decimals.'f %s', $size, $unit);
        }
        $size /= $step;
    }

    return sprintf('%.'.$decimals.'f %s', $size, $largestUnit);
}

echo formatFileSize(5000).PHP_EOL;           // 4.88 KiB
echo formatFileSize(5000, 8).PHP_EOL;        // 4.88281250 KiB
echo formatFileSize(5000, 2, false).PHP_EOL; // 5.00 kB

Leave a Comment

Cancel reply

Your email address will not be published.