Skip to content

Instantly share code, notes, and snippets.

@liunian
Last active January 7, 2025 11:59
Human Readable File Size with PHP
<?php
# http://jeffreysambells.com/2012/10/25/human-readable-filesize-php
function human_filesize($bytes, $decimals = 2) {
$size = array('B','kB','MB','GB','TB','PB','EB','ZB','YB');
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$size[$factor];
}
echo human_filesize(filesize('example.zip'));
@jgarcianewemage
Copy link

jgarcianewemage commented Sep 9, 2024

Another version, eliminates needless count() units will always be 5, ** operator, optional unit output, reworked array for determining decimals by the factor

function human_bytes(int $bytes, $u = false): string {
    if ($bytes < 1) return 0;

    $units = ['B', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb'];
    $factor = min(floor(log($bytes, 1024)), 5);
    $value = round($bytes / (1024 ** $factor), $factor > 1 ? 2 : 0);

    return $u ? $value . $units[$factor] : $value;
}

@buldezir
Copy link

buldezir commented Sep 9, 2024

Another version, eliminates needless count()

just FYI: count is "free" operation in php, cause array always have its size in internal structure.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment