How to Get the File Size in PHP

09/09/2021

Contents

In this article, you will learn how to get the file size in PHP.

PHP filesize() Function

You can use the filesize() function in PHP to get the size of a file in bytes.

You can use it as follows:

<?php
  $filename = "path/to/file.ext";

  if (file_exists($filename)) {
    $filesize = filesize($filename);
    echo "The size of $filename is $filesize bytes.";
  } else {
    echo "$filename does not exist.";
  }
?>

In this example, the file_exists() function is used to check if the file exists before calling filesize. This is to avoid an error in case the file does not exist.

The filesize() function takes the path to the file as its argument, and returns the size of the file in bytes. If the file does not exist or there is a problem accessing the file, the filesize() function returns FALSE.

It’s worth noting that the size of the file may be limited by your system’s PHP configuration, and the filesize() function may return FALSE if the file size exceeds this limit. To avoid this issue, you can increase the value of the memory_limit setting in your php.ini file.

Here’s an example of how you could use filesize to display a human-readable size instead of just the number of bytes:

<?php
  $filename = "path/to/file.ext";

  if (file_exists($filename)) {
    $filesize = filesize($filename);
    $units = array('B', 'KB', 'MB', 'GB', 'TB');
    for ($i = 0; $filesize >= 1024 && $i < count($units) - 1; $i++) {
        $filesize /= 1024;
    }
    echo "The size of $filename is " . round($filesize, 2) . " " . $units[$i] . ".";
  } else {
    echo "$filename does not exist.";
  }
?>

In this example, the size is divided by 1024 and the units array is used to determine the appropriate unit of measurement. The result is rounded to two decimal places, and the final size is displayed along with the appropriate unit of measurement.