The fastest way to calculate file size open inside code (PHP)

I know that in the PHP file there are several built-in functions available to get the file size, some of them: 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 file size using ftell function? If so, tell me how?

Scenario:

  • The system (code) opens an existing file with "a" mode to add content.
  • A file pointer points to the end of a line.
  • The system updates the contents in the file.
  • The system uses ftell to calculate the file size.
+6
source share
3 answers

fstat determines the file size without acrobatics:

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

ftell cannot be used when the file was opened with the append ( "a" ) flag. In addition, you must first search at the end of the fseek($f, 0, SEEK_END) file fseek($f, 0, SEEK_END) .

+12
source

ftell() can tell you how many bytes should be in the file, but not how many actually. Sparse files take up less disk space than a value that tends to end, and the message returns.

+2
source

Thanks @Phihag, with your information on fseek along with ftell I can calculate the size much better. See code here: http://pastebin.com/7XCqu0WR

 <?php $fp = fopen("/tmp/temp.rock", "a+"); fwrite($fp, "This is the contents"); echo "Time taken to calculate the size by filesize function: "; $t = microtime(true); $ts1 = filesize("/tmp/temp.rock") . "\n"; echo microtime(true) - $t . "\n"; echo "Time taken to calculate the size by fstat function:"; $t = microtime(true); $ts1 = fstat($fp) . "\n"; $size = $ts1["size"]; echo microtime(true) - $t . "\n"; echo "Time taken to calculate the size by fseek and ftell function: "; $t = microtime(true); fseek($fp, 0, SEEK_END); $ts2 = ftell($fp) . "\n"; echo microtime(true) - $t . "\n"; fclose($fp); /** OUTPUT: Time taken to calculate the size by filesize function:2.4080276489258E-5 Time taken to calculate the size by fstat function:2.9802322387695E-5 Time taken to calculate the size by fseek and ftell function:1.2874603271484E-5 */ ?> 
0
source

Source: https://habr.com/ru/post/892644/


All Articles