Home > Back-end >  PHP - Is fstat() cached?
PHP - Is fstat() cached?

Time:11-17

I'd like to know if fstat() is cached.

Documentation says nothing about it.

(PHP 8.1.12)

CodePudding user response:

I made a quick demo that appears to show that it is not cached. However, see the edit, too

$filename = __DIR__.'/test.txt';

@unlink($filename);
touch($filename);
echo 'STAT - Size before write: '.stat($filename)['size'], PHP_EOL;
file_put_contents($filename, 'test');
echo 'STAT - Size after write: '.stat($filename)['size'], PHP_EOL;
clearstatcache();
echo 'STAT - Size after cache clear: '.stat($filename)['size'], PHP_EOL;

@unlink($filename);
touch($filename);
$fp = fopen($filename, 'wb');
echo 'FSTAT - Size before write: '.fstat($fp)['size'], PHP_EOL;
fwrite($fp, 'test');
echo 'FSTAT - Size after write: '.fstat($fp)['size'], PHP_EOL;
clearstatcache();
echo 'FSTAT - Size after cache clear: '.fstat($fp)['size'], PHP_EOL;

Output:

STAT - Size before write: 0
STAT - Size after write: 0
STAT - Size after cache clear: 4
FSTAT - Size before write: 0
FSTAT - Size after write: 4
FSTAT - Size after cache clear: 4

Edit

Per @Barmar, I ran the test again, this time with just an fstat call followed by a sleep(10), then I quickly updated the file with vim manually, and then one final fstat call (all in the same request), and that one came back as cached.

I then ran that again, this time with clearstatcache() before the final fstat, and it did not change. I also tried the tests with both w and r modes for fopen, same results.

So there does appear to be a cache of some sort, but I don't think it is the stat cache.

CodePudding user response:

As a supplement:

I also did exactly such a test as Chris Haas describes in the comment.

/*
 * Open test.txt with a text editor
 * Run this script
 * Add some characters in the editor and save while the script is running
 */
$file = __DIR__.'/../test/test.txt';
$fp = fopen($file,'r');
$size[] = fstat($fp)['size'];
sleep(10);
$size[] = fstat($fp)['size'];
var_dump($size);
//array(2) { [0]=> int(3) [1]=> int(13) }

Same results for PHP on Win10 and a small Linux.

  • Related