Skip to content

Instantly share code, notes, and snippets.

@gladx
Last active April 8, 2021 12:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gladx/62fa307eb65586b6dbaaad75273c653d to your computer and use it in GitHub Desktop.
Save gladx/62fa307eb65586b6dbaaad75273c653d to your computer and use it in GitHub Desktop.
Human readable file size in php
<?php
// http://jeffreysambells.com/2012/10/25/human-readable-filesize-php + some edit
// https://gist.github.com/liunian/9338301
function human_filesize($bytes, $decimals = 2)
{
if ($bytes < 1024) {
return $bytes . ' B';
}
$factor = floor(log($bytes, 1024));
return sprintf("%.{$decimals}f ", $bytes / pow(1024, $factor)) . ['B', 'KB', 'MB', 'GB', 'TB', 'PB'][$factor];
}
# Tests
for ($num = 1022; $num < 1032; $num++) {
echo $num, ': ', human_filesize($num), "\n";
}
echo $num, ': ', human_filesize(0), "\n";
echo $num, ': ', human_filesize(1048576), "\n";
echo $num, ': ', human_filesize(125890578), "\n";
echo $num, ': ', human_filesize(102400000000), "\n";
# Result
/*
1022: 1022 B
1023: 1023 B
1024: 1.00 KB
1025: 1.00 KB
1026: 1.00 KB
1027: 1.00 KB
1028: 1.00 KB
1029: 1.00 KB
1030: 1.01 KB
1031: 1.01 KB
1032: 0 B
1032: 1.00 MB
1032: 120.06 MB
1032: 95.37 GB
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment