How to check the size of a file in PHP

PHP-IconPHP has a handy function called filesize() which can help us display how big a file is.

It does this in bytes by default, but with a bit of tinkering we can easily convert this into kilobytes or megabytes.

Let’s first see how this works in bytes:

$file = '/path/to/your/file';
$filesize = filesize($file);

echo "The size of your file is $filesize bytes.";

Converting bytes into kilobytes works by dividing the value by 1024. PHP is very accurate and will give you 12 decimal digits – perhaps a little overkill. To avoid this we can make use of the round() function and specify how many digits of accuracy we’d like to display:

$file = '/path/to/your/file';
$filesize = filesize($file); // bytes
$filesize = round($filesize / 1024, 2); // kilobytes with two digits

echo "The size of your file is $filesize KB.";

To display the value in megabytes we’ll simply divide by 1024 twice:

$file = '/path/to/your/file';
$filesize = filesize($file); // bytes
$filesize = round($filesize / 1024 / 1024, 1); // megabytes with 1 digit

echo "The size of your file is $filesize MB.";

You can leave a comment on my original post.