How to get the size of a file
Short answer
filesize() returns the size in bytes:
<?php
$file = sys_get_temp_dir() . '/recipe-size.txt';
file_put_contents($file, str_repeat('a', 3000));
echo filesize($file);Output:
3000In a readable form
Divide by 1024 until the number gets small:
<?php
function readableSize(int $bytes): string
{
$units = ['B', 'KB', 'MB', 'GB'];
$index = 0;
$size = $bytes;
while ($size >= 1024 && $index < count($units) - 1) {
$size /= 1024;
$index++;
}
return round($size, 1) . ' ' . $units[$index];
}
echo readableSize(3000), ', ', readableSize(5 * 1024 * 1024);Output:
2.9 KB, 5 MBFunctions used in this recipe
- filesize — Returns the size of a file in bytes.
- round — Rounds a number to a given number of digits.
- number_format — Formats a number for display: decimals and a thousands separator.