liunian / gist:9338301
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
# 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’ )); |
function human_filesize($size, $precision = 2) < $units = array('B','kB','MB','GB','TB','PB','EB','ZB','YB'); $step = 1024; $i = 0; while (($size / $step) > 0.9) < $size = $size / $step; $i++; > return round($size, $precision).$units[$i]; >
Same function as redecs with some minor golfing
function human_filesize($size, $precision = 2) < for($i = 0; ($size / 1024) > 0.9; $i++, $size /= 1024) <> return round($size, $precision).['B','kB','MB','GB','TB','PB','EB','ZB','YB'][$i]; >
static should save a tiny bit more time.
function human_filesize($size, $precision = 2) < static $units = array('B','kB','MB','GB','TB','PB','EB','ZB','YB'); $step = 1024; $i = 0; while (($size / $step) > 0.9) < $size = $size / $step; $i++; > return round($size, $precision).$units[$i]; >
Same as above but precision is chosen based on the result. No on likes seeing 123.34 kB precision maters on larger files but on smaller files its not as important. This accounts for this issue
function human_filesize($size) <
for($i = 0; ($size / 1024) > 0.9; $i++, $size /= 1024) <>
return round($size, [0,0,1,2,2,3,3,4,4][$i]).[‘B’,’kB’,’MB’,’GB’,’TB’,’PB’,’EB’,’ZB’,’YB’][$i];
>
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]; >
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]; >
The below code is not my code, (I want to know which is better, Which is faster and reliable) ? can you please someone suggest me a Good code?
function bytesToHuman($bytes) < $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']; for ($i = 0; $bytes >1024; $i++) $bytes /= 1024; return round($bytes, 2) . ' ' . $units[$i]; >
I took what I consider to be the best ideas in this thread and made what I consider the most appealing implementation of this problem. Feel free to use as you wish.
I took what I consider to be the best ideas in this thread and made what I consider the most appealing implementation of this problem. Feel free to use as you wish.
You have to add this line for typecasting $bytes or else you will get tons of PHP NOTICEs about malformed numbers
$bytes = (int) $bytes; //typecast to int to suppress PHP NOTICE
Anyway I edited it to use the MiB suffixes.
const BYTE_UNITS = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']; const BYTE_PRECISION = [0, 0, 1, 2, 2, 3, 3, 4, 4]; const BYTE_NEXT = 1024; public function fileSizeInfo($bytes, $precision = null) < $bytes = (int) $bytes; //typecast to int to suppress PHP NOTICE for ($i = 0; ($bytes / self::BYTE_NEXT) >= 0.9 && $i < count(self::BYTE_UNITS); $i++) $bytes /= self::BYTE_NEXT; return round($bytes, is_null($precision) ? self::BYTE_PRECISION[$i] : (int)$precision) . self::BYTE_UNITS[$i]; >
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]; >
Can cause error Division by zero. if bytes enter is 0.
Enterprise-grade OOP version 😁 (requires PHP 7.4)
class BytesForHumans < public const FAMILIAR_UNIT_SCALE = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; public const PEDANTIC_UNIT_SCALE = ['B', 'kiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']; public string $formatString pl-s">%g%s"; public int $logBase = 1024; public int $maxDecimalPlaces = 2; public array $unitScale = self::PEDANTIC_UNIT_SCALE; /** Create a BytesForHumans from a number of bytes. Fractional bytes are not allowed. */ public static function fromBytes(int $bytes) < if ($bytes < 0) < throw new \DomainException("cannot have negative bytes"); > return new static($bytes); > /** Display for humans by converting to string. */ public function __toString() < [$number, $power] = $this->scaledValueAndPower(); $units = $this->getUnits($power); return sprintf($this->formatString, round($number, $this->maxDecimalPlaces), $units); > /** You can also get the "raw" scaled value and its log-base-1024 power. */ public function scaledValueAndPower(): array < if ($this->bytes == 0) < return [0, 0]; > $power = floor(log($this->bytes, $this->logBase)); $value = $this->bytes / pow($this->logBase, $power); return [$value, $power]; > /** For fluent setting of public properties. */ public function tap(\Closure $callback): self < $callback($this); return $this; > protected int $bytes; protected function __construct(int $bytes) < $this->bytes = $bytes; > protected function getUnits($power): string < if ($power >= count($this->unitScale)) < throw new \DomainException("cannot format bytes, too many bytes!"); > return $this->unitScale[$power]; > >
$binaryPrefixBytes = BytesForHumans::fromBytes(5945766364) ->tap(function($b) < $b->formatString = BytesForHumans::SPACED_FORMAT; $b->maxDecimalPlaces = 1; >); PHPUnit\Framework\Assert::assertEquals('5.5 GiB', (string)$binaryPrefixBytes); $decimalPrefixBytes = BytesForHumans::fromBytes(5945766364) ->tap(function($b) < $b->unitScale = BytesForHumans::FAMILIAR_UNIT_SCALE; $b->logBase = 1000; >); PHPUnit\Framework\Assert::assertEquals('5.95GB', (string)$decimalPrefixBytes);
PHP: Get file size.
This is a guide on how to get the size of a file using PHP. In this tutorial, we will get the size of a file in bytes using PHP’s filesize function before converting those bytes into KB, MB and GB, which are far more human-friendly.
PHP’s filesize function.
PHP’s filesize function takes in one parameter: A string parameter called $filename, which should contain the path to the file.
Take a look at the following example:
//The path to our file. $file = 'photograph.jpg'; //Get the file size in bytes using PHP's filesize function. $fileSizeBytes = filesize($file); //In my case, the file was 269,708 bytes in size. var_dump($fileSizeBytes);
The code snippet above assumes that the file “photograph.jpg” is located in the same directory as our PHP script.
If our file was located in another directory called images, we could use the following relative path:
//A relative path. $file = '../images/photograph.jpg'; //Get the file size in bytes. $fileSizeBytes = filesize($file);
Note that the filesize function will also accept an absolute path to the file:
//Using an absolute path. $file = 'C:\wamp\www\photograph.jpg'; //Get the file size in bytes. $fileSizeBytes = filesize($file);
If the filesize function is given an incorrect file path, it will throw the following warning:
“Warning: filesize(): stat failed for /path/to/photograph.jpg”
PHP’s filesize function uses the system’s underlying stat command to get the size of the file in question.
Getting the file size in KB.
If you are primarily dealing with images or other small files, you might want to convert the bytes into KB (kilobytes).
//Relative path to our file. $file = 'photograph.jpg'; //Get the file size in bytes. $fileSizeBytes = filesize($file); //Convert the bytes into KB. $fileSizeKB = round($fileSizeBytes / 1024); //269,708 bytes divided by 1024 results in 263 KB var_dump($fileSizeKB);
In the code snippet above, we got the size of the file in bytes and then divided the result by 1024. This is because there are roughly 1024 bytes in every kilobyte.
Getting the file size in MB.
The MB (megabyte) is a useful metric if you are dealing with MP3 files, Zip Files, PDFs or other relatively-large files.
An example of getting a file’s size in MB:
//Path to our file. $file = 'photograph.jpg'; //Get the file size in bytes. $fileSizeBytes = filesize($file); //Convert the bytes into MB. $fileSizeMB = ($fileSizeBytes / 1024 / 1024); //269,708 bytes is 0.2572135925293 MB var_dump($fileSizeMB); //Format it so that only 2 decimal points are displayed. $fileSizeMB = number_format($fileSizeMB, 2); //It now becomes 0.26 MB. var_dump($fileSizeMB);
- Got the size of the file in bytes using PHP’s filesize function.
- Converted the bytes into MB by dividing the bytes by 1024 twice.
- Because the result contains far two many decimal places, we used PHP’s number_format function to limit the number of decimal places to 2.
In my case, the “photograph.jpg” file was 269,708 bytes in size, which became 0.26 MB.
Using PHP to get the file size in GB.
If you are dealing with large files such as videos, you might want to use GB (gigabytes):
//The path to our file. $file = 'large-file.mp4'; //Get the file size in bytes. $fileSizeBytes = filesize($file); //Convert the bytes into GB. $fileSizeGB = ($fileSizeBytes / 1024 / 1024 / 1024); var_dump($fileSizeGB);
In the code sample above, we converted the bytes into GB by dividing the result of filesize by 1024 three times.
filesize won’t work with remote files.
The filesize function will not work with remote files. If you attempt to get the size of a remote file using the filesize function, it will spit out the following warning:
Warning: filesize(): stat failed for http://example.com/file.mp4
This is because the underlying stat command does not support remote files. See: Get the size of a remote file using PHP.