get file size in PHP

Question

Answers ( 1 )

    0
    2024-01-11T18:05:21+00:00

    In PHP, you can get the size of a file using the filesize() function. This function returns the size of a file in bytes. Here's how you can use it:

    <?php
        $filename = 'path/to/your/file.txt';
        
        // Check if file exists
        if (file_exists($filename)) {
            $filesize = filesize($filename);
            echo "The size of the file is $filesize bytes.";
        } else {
            echo "File does not exist.";
        }
    ?>
    

    In this example, replace 'path/to/your/file.txt' with the actual path to the file you want to check. The file_exists() function is used to ensure that the file exists before trying to get its size to avoid errors.

    There are other methods to get file size in PHP, especially if you're dealing with large files or need to format the size:

    1. Large Files: For very large files, filesize() might return incorrect results due to integer overflow. In such cases, you can use the fseek() function with PHP_INT_MAX:

      $file = fopen($filename, "r");
      fseek($file, 0, SEEK_END);
      $size = ftell($file);
      fclose($file);
      
    2. Formatting File Size: To display the file size in a more readable format (like KB, MB), you can create a function to convert bytes:

      function formatSizeUnits($bytes) {
          if ($bytes >= 1073741824) {
              $bytes = number_format($bytes / 1073741824, 2) . ' GB';
          } elseif ($bytes >= 1048576) {
              $bytes = number_format($bytes / 1048576, 2) . ' MB';
          } elseif ($bytes >= 1024) {
              $bytes = number_format($bytes / 1024, 2) . ' KB';
          } elseif ($bytes > 1) {
              $bytes = $bytes . ' bytes';
          } elseif ($bytes == 1) {
              $bytes = $bytes . ' byte';
          } else {
              $bytes = '0 bytes';
          }
      
          return $bytes;
      }
      
      echo formatSizeUnits($filesize);
      

    Remember to handle potential errors and exceptions, especially when dealing with file operations in PHP.

Leave an answer