Created
November 25, 2021 18:14
-
-
Save breadthe/a116c58036936447d9951a743bebb0b6 to your computer and use it in GitHub Desktop.
Format bytes to human readable (KB/MB/GB)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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