Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php cache expiration time for file_exists() or similiar functions

Tags:

php

as per php documentation for file_exists()

The results of this function are cached. See clearstatcache() for more details.

But it doesn't provide information for how long php will hold this information in cache. I've checked documentation for clearstatcache() but no such information is there. Googling also not helped this time.

I'm building an application where file_exists is called to generate some output, and since the file being checked can be removed by any time by any user, i need to be sure if it really exists before generating output.

Calling clearcache() before file_exists() will solve the purpose, but just for curiosity I'd like to know for how long PHP will cache files information (default time) and by which variable i can this change cache expiration time?

EDIT 1: In real, checking again with file_exists() after deleting file returns false, but if it is so, what is the meaning of cache as written in documentation ?

EDIT 2:

<? 
var_dump(file_exists('/home/user/filecheck.php')); 
sleep(20);
// after running script, sleep for 20 seconds just to quickly delete this file manually before file_exists is called again.
// unlink is not used since as per documentation it'll clear php cache.
var_dump(file_exists('/home/user/filecheck.php')); 
?>

and the response of script is

boolean true

boolean false

That means php is not caching file_exists information if file exists even for same execution, then why it is written in documentation that "the results of this function are cached"?

like image 203
Dr. DS Avatar asked Oct 25 '25 06:10

Dr. DS


2 Answers

How long the stat cache will cache the information is configurable in your php.ini file using the realpath_cache_ttl variable. Default seems to be 120 seconds.

like image 66
Yorick Avatar answered Oct 26 '25 22:10

Yorick


Since this question was only ever accurately answered as a comment...

PHP caches that information for the duration of the request

- Mark Baker, 2016-04-30

Since there is currently no way to disable the stat cache, that means if you have a long running script or executing code from in the CLI, the cache will never expire and you will need to manually clear it for any call to functions which use it. Which is inefficient.

And here is a PR with a feature request to disable the cache (I approve!):

https://github.com/php/php-src/pull/5894

like image 39
Eaten by a Grue Avatar answered Oct 26 '25 22:10

Eaten by a Grue