Search code examples
phpfilefilesize

Fastest way to calculate the size of an file opened inside the code (PHP)


I know there quite a bit of in-built functions available in PHP to get size of the file, some of them are: filesize, stat, ftell, etc.

My question lies around ftell which is quite interesting, it returns you the integer value of the file-pointer from the file.

Is it possible to get the size of the file using ftell function? If yes, then tell me how?

Scenario:

  1. System (code) opens a existing file with mode "a" to append the contents.
  2. File pointer points to the end of line.
  3. System updates the content into the file.
  4. System uses ftell to calculate the size of the file.

Solution

  • fstat determines the file size without any acrobatics:

    $f = fopen('file', 'r+');
    $stat = fstat($f);
    $size = $stat['size'];
    

    ftell can not be used when the file has been opened with the append("a") flag. Also, you have to seek to the end of the file with fseek($f, 0, SEEK_END) first.