Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

file

php

filesize

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.
like image 286
Rakesh Sankar Avatar asked Jul 13 '11 05:07

Rakesh Sankar


1 Answers

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.

like image 56
phihag Avatar answered Sep 21 '22 20:09

phihag