Skip to content

Instantly share code, notes, and snippets.

@liunian
Last active October 6, 2023 20:48
Show Gist options
  • Star 50 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save liunian/9338301 to your computer and use it in GitHub Desktop.
Save liunian/9338301 to your computer and use it in GitHub Desktop.
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'));
@buldezir
Copy link

buldezir commented Jun 12, 2022

@Be1zebub that is for wget progress format, but the concept is same

function transferedToBytes(string $transfered): int
{
    $mods = ['B' => 1, 'K' => 1024, 'M' => 1024 ** 2, 'G' => 1024 ** 3];
    $transfered = str_replace(',', '.', $transfered);
    $mod = $transfered[strlen($transfered) - 1];
    return isset($mods[$mod]) ? (int)round(((float)$transfered) * $mods[$mod]) : 0;
}

@jdevinemt
Copy link

Even better

function MakeReadable($bytes) {
    $i = floor(log($bytes, 1024));
    return round($bytes / pow(1024, $i), [0,0,2,2,3][$i]).['B','kB','MB','GB','TB'][$i];
}

I modified @MrCaspan's method to address a few issues.

  • It returns 0B instead of NANB when attempting to format 0 bytes, which was caused by a value of -INF calculated for the factor.
  • I added petabytes, as I think this is the most reasonable max unit to display in most cases. If someone wanted a lower or higher ceiling, the units can easily be modified.
  • When the factor was higher than the highest defined units, the function would just return an integer with no unit indication. This modified version just uses the highest defined unit when the factor exceeds the defined bounds.

It's a longer version for sure, but it's more readable and I think addressing the issues above warrants a lengthier function.

function readableBytes(int $bytes): string
{
    $unitDecimalsByFactor = [
        ['B', 0],
        ['kB', 0],
        ['MB', 2],
        ['GB', 2],
        ['TB', 3],
        ['PB', 3]
    ];

    $factor = $bytes ? floor(log($bytes, 1024)) : 0;
    $factor = min($factor, count($unitDecimalsByFactor) - 1);

    $value = round($bytes / pow(1024, $factor), $unitDecimalsByFactor[$factor][1]);
    $units = $unitDecimalsByFactor[$factor][0];

    return $value.$units;
}

If this function were to be adapted for use with larger factors, a type other than int would be required for the $bytes parameter due to its maximum value.

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