How to check the size of a file in PHP

- by

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.";


If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

1 thought on “How to check the size of a file in PHP”

  1. You are the boss – i found the same script but 10 times longer! Super easy and compact thanks a lot!

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.