Skip to content

Instantly share code, notes, and snippets.

@breadthe
Created November 25, 2021 18:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save breadthe/a116c58036936447d9951a743bebb0b6 to your computer and use it in GitHub Desktop.
Save breadthe/a116c58036936447d9951a743bebb0b6 to your computer and use it in GitHub Desktop.
Format bytes to human readable (KB/MB/GB)
<?php
/**
* Put this in bootstrap/helpers.php
* Add "files" key in composer.json > autoload: "files": ["bootstrap/helpers.php"]
* @see https://stackoverflow.com/questions/2510434/format-bytes-to-kilobytes-megabytes-gigabytes
*/
function formatBytes(int $bytes, $precision = 2)
{
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
// Uncomment one of the following alternatives
// $bytes /= pow(1024, $pow);
$bytes /= (1 << (10 * $pow));
return round($bytes, $precision) . ' ' . $units[$pow];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment