Skip to content

Instantly share code, notes, and snippets.

@beporter
Created March 27, 2014 22:50
Show Gist options
  • Save beporter/9820829 to your computer and use it in GitHub Desktop.
Save beporter/9820829 to your computer and use it in GitHub Desktop.
Convert an integer byte value into a human-readable file size.
<?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;
}
@beporter
Copy link
Author

Output:

5 --> 5 B
5814.272 --> 5.68 K
7864320 --> 7.5 M
10737418240 --> 10 G
16497072463151 --> 15 T
7.0053492203748E+15 --> 6.22 P

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