Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP file size is unchanged after appending

I am facing a problem with PHP file I/O.

$file = fopen("/tmp/test.txt", "w");
fwrite($file,"hi there\n");
fclose($file);
echo filesize("/tmp/test.txt")."\n"; # displays 9

$file = fopen("/tmp/test.txt", "a");
fwrite($file,"hi there\n");
fclose($file);
echo filesize("/tmp/test.txt")."\n"; # also displays 9 !!!!!!!

As one can see, I am changing the file size after the initial write by appending to it. Why do I get 9 as file size in both the cases? I'm expecting 18 as the output in case 2.

like image 778
user1033837 Avatar asked Nov 07 '11 13:11

user1033837


1 Answers

You need to clear file status cache by calling the function clearstatcache before you call the filesize() again after modifying the file:

// write into file.
// call filesize()

clearstatcache();

// append to the fiile.
// call filesize()

In order to get better performance PHP caches the result of filesize() so you need to tell PHP to clear that cache before you call the filesize() again on a modified file.

like image 56
codaddict Avatar answered Sep 22 '22 09:09

codaddict