PHP file size is unchanged after appending
Asked Answered
F

1

8

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.

Fine answered 7/11, 2011 at 13:39 Comment(2)
What is the file's content after execution of this script ?Sanatory
Dear hsz it has expected contents. It has 18 characters.Fine
M
15

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.

Maurits answered 7/11, 2011 at 13:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.