With this function you can convert a number of bytes into using a larger unit that makes it easier to read. For example if you had 30,000,000 bytes it might be easier to read as 28.61 MB. This function will automatically convert the number of bytes into the most appropriate human readable format for that size. Alternatively, you can specify the unit type to force what it should be converted to. The precision option allows you to set how many decimal places should be utilized, by default it is 2.

Currently supported unit types are: bytes, KB (Kilobyte), MB (Megabyte), GB (Gigabyte), TB (Terabyte), PB (Petabyte), and EB (Exabyte). Instructions are included in the DocBlocks if you need support for ZB (Zettabyte), YB (Yottabyte), and BB (Brontobyte).

/**
 * Get Human Readable File Size
 *
 * Converts a size to use requested units, or if unit is not specified the easiest to read human representation.
 *
 * Supports: Bytes, Kilobytes (KB), Megabytes (MB), Gigabytes (GB), Terabytes (TB), Petabytes (PB), and Exabytes (EB).
 *
 * If you need support for larger units and the OS running this code can handle extremely large numbers, you can add
 * Zettabytes (ZB), Yottabytes (YB), and Brontobytes (BB) at the beginning of the $units array in the code below:
 *
 * $units = ['BB', 'YB', 'ZB', 'EB', 'PB', 'TB', 'GB', 'MB', 'KB'];
 *
 * @param $size
 * @param string $returnUnit Can be: KB, MB, GB, TB, PB, or EB
 * @param int $precision Number of places after decimal point to use
 *
 * @return string
 */
function humanFileSize($size, $returnUnit = "", $precision = 2): string
{
    $units = ['EB', 'PB', 'TB', 'GB', 'MB', 'KB'];

    for($i = count($units); $i > 0; $i--) {
        $unit = $units[count($units) - $i];
        $maxUnitSize = 1 << ($i * 10);
        if(! $returnUnit && $size >= $maxUnitSize || $returnUnit == $unit) {
            return number_format($size / $maxUnitSize, $precision) . " " . $unit;
        }
    }

    return number_format($size, $precision) . " bytes";
}

This code snippet was published on It was last edited on

0

0 Comments

  • Votes
  • Oldest
  • Latest