Created
March 27, 2014 22:50
-
-
Save beporter/9820829 to your computer and use it in GitHub Desktop.
Convert an integer byte value into a human-readable file size.
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 | |
//---------- | |
// Only works with INTEGER values for $bytes. | |
function human_filesize($bytes, $decimals = 2) { | |
$sz = 'BKMGTP'; | |
$bytes = (int)$bytes; // This process only works with integer $byte values. | |
$factor = floor((strlen($bytes) - 1) / 3); // Determine the correct range. | |
$s = $bytes / pow(1024, $factor); // Knock out the right number of exponents. | |
$s = sprintf("%.{$decimals}f", $s) + 0; // Clean up decimals, `+0` removes trailing zeroes. | |
return sprintf('%s %s', $s, @$sz[$factor]); // Return the formatted number and unit. | |
} | |
// main() ----------------- | |
$tests = array( | |
5, // 5 bytes | |
1024 * 5.678, // 5.68 kb | |
1024 * 1024 * 7.5, // 7.5 mb | |
1024 * 1024 * 1024 * 10, // 10 gb | |
1024 * 1024 * 1024 * 1024 * 15.004, // 15.02 tb | |
1024 * 1024 * 1024 * 1024 * 1024 * 6.222, // 6.22 pb | |
); | |
foreach ($tests as $b) { | |
echo "$b --> " . human_filesize($b) . PHP_EOL; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: