Last active
July 11, 2024 09:59
-
-
Save liunian/9338301 to your computer and use it in GitHub Desktop.
Human Readable File Size with PHP
This file contains 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')); |
how to revert it?
i want to convert human file-size to int bytes
@Be1zebub that is for wget
progress format, but the concept is same
function transferedToBytes(string $transfered): int
{
$mods = ['B' => 1, 'K' => 1024, 'M' => 1024 ** 2, 'G' => 1024 ** 3];
$transfered = str_replace(',', '.', $transfered);
$mod = $transfered[strlen($transfered) - 1];
return isset($mods[$mod]) ? (int)round(((float)$transfered) * $mods[$mod]) : 0;
}
Even better
function MakeReadable($bytes) { $i = floor(log($bytes, 1024)); return round($bytes / pow(1024, $i), [0,0,2,2,3][$i]).['B','kB','MB','GB','TB'][$i]; }
I modified @MrCaspan's method to address a few issues.
- It returns
0B
instead ofNANB
when attempting to format 0 bytes, which was caused by a value of-INF
calculated for the factor. - I added petabytes, as I think this is the most reasonable max unit to display in most cases. If someone wanted a lower or higher ceiling, the units can easily be modified.
- When the factor was higher than the highest defined units, the function would just return an integer with no unit indication. This modified version just uses the highest defined unit when the factor exceeds the defined bounds.
It's a longer version for sure, but it's more readable and I think addressing the issues above warrants a lengthier function.
function readableBytes(int $bytes): string
{
$unitDecimalsByFactor = [
['B', 0],
['kB', 0],
['MB', 2],
['GB', 2],
['TB', 3],
['PB', 3]
];
$factor = $bytes ? floor(log($bytes, 1024)) : 0;
$factor = min($factor, count($unitDecimalsByFactor) - 1);
$value = round($bytes / pow(1024, $factor), $unitDecimalsByFactor[$factor][1]);
$units = $unitDecimalsByFactor[$factor][0];
return $value.$units;
}
If this function were to be adapted for use with larger factors, a type other than int
would be required for the $bytes
parameter due to its maximum value.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Enterprise-grade OOP version 😁 (requires PHP 7.4)
Full usage example: