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 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:

Note that the filesize function will also accept an absolute path to the 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).


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:

In the PHP above, we:

  1. Got the size of the file in bytes using PHP’s filesize function.
  2. Converted the bytes into MB by dividing the bytes by 1024 twice.
  3. 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):

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

This is because the underlying stat command does not support remote files. See: Get the size of a remote file using PHP.

Facebook Comments