Last active
June 3, 2025 07:34
-
-
Save liunian/9338301 to your computer and use it in GitHub Desktop.
Human Readable File Size with PHP
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 | |
| # http://jeffreysambells.com/2012/10/25/human-readable-filesize-php | |
| function human_filesize($bytes, $decimals = 2) { | |
| $size = array('B','kB','MB','GB','TB','PB','EB','ZB','YB'); | |
| $factor = floor((strlen($bytes) - 1) / 3); | |
| return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$size[$factor]; | |
| } | |
| echo human_filesize(filesize('example.zip')); |
Another version, eliminates needless count() units will always be 5, ** operator, optional unit output, reworked array for determining decimals by the factor
function human_bytes(int $bytes, $u = false): string {
if ($bytes < 1) return 0;
$units = ['B', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb'];
$factor = min(floor(log($bytes, 1024)), 5);
$value = round($bytes / (1024 ** $factor), $factor > 1 ? 2 : 0);
return $u ? $value . $units[$factor] : $value;
}Another version, eliminates needless count()
just FYI: count is "free" operation in php, cause array always have its size in internal structure.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I modified @MrCaspan's method to address a few issues.
0Binstead ofNANBwhen attempting to format 0 bytes, which was caused by a value of-INFcalculated for the factor.It's a longer version for sure, but it's more readable and I think addressing the issues above warrants a lengthier function.
If this function were to be adapted for use with larger factors, a type other than
intwould be required for the$bytesparameter due to its maximum value.