La llamada a la función stat() o lstat() es relativamente costosa en términos de tiempo de ejecución. Por ello, el resultado de la última llamada a una de las funciones de estado (ver la lista a continuación) se guarda para su reutilización. Si se desea forzar la verificación del estado de un fichero, en el caso de que el fichero hubiera podido ser modificado o hubiera desaparecido, se debe utilizar la función clearstatcache() para borrar de la memoria los resultados de la última llamada a la función.
Tenga en cuenta que PHP no guarda en caché información sobre
un fichero inexistente. Si se llama a file_exists()
sobre un fichero que no existe, la función devolverá false
hasta que se cree el fichero. Si se crea el fichero,
la función devolverá true incluso si se borra el fichero.
Nota:
Esta función guarda en caché información sobre ficheros. Por lo tanto, solo es necesario llamar a clearstatcache() si se realizan múltiples operaciones sobre el directorio, y se desea tener una versión actualizada de la información.
Las funciones afectadas incluyen : stat() , lstat() , file_exists() , is_writable() , is_readable() , is_executable() , is_file() , is_dir() , is_link() , filectime() , fileatime() , filemtime() , fileinode() , filegroup() , fileowner() , filesize() , filetype() , y fileperms() .
clear_realpath_cacheSi también debe vaciarse la caché de rutas reales.
filename
Limpia la caché de ruta real de un fichero específico.
Solo puede ser utilizado si el argumento
clear_realpath_cache vale true .
No se retorna ningún valor.
Ejemplo #1 Ejemplo con clearstatcache()
<?php
$file = 'output_log.txt';
function get_owner($file)
{
$stat = stat($file);
$user = posix_getpwuid($stat['uid']);
return $user['name'];
}
$format = "UID @ %s: %s\n";
printf($format, date('r'), get_owner($file));
chown($file, 'ross');
printf($format, date('r'), get_owner($file));
clearstatcache();
printf($format, date('r'), get_owner($file));
?>Resultado del ejemplo anterior es similar a:
UID @ 2008年10月12日 20:48:28 +0100: root UID @ 2008年10月12日 20:48:28 +0100: root UID @ 2008年10月12日 20:48:28 +0100: ross
unlink() does not clear the cache if you are performing file_exists() on a remote file like:
<?php
if (file_exists("ftp://ftp.example.com/somefile"))
?>
In this case, even after you unlink() successfully, you must call clearstatcache().
<?php
unlink("ftp://ftp.example.com/somefile");
clearstatcache();
?>
file_exists() then properly returns false.clearstatcache() does not canonicalize the path. clearstatcache(true, "/a/b/c") is different from clearstatcache(true, "/a/b//c").Not documented, but seems like clearstatcache() is clearing the cache only for the process it is being called from. I have 2 PHP scripts running simultaneously, and the first one does call clearstatcache(), but still the second one deadlocks, unless I call clearstatcache() in it too:
script1:
<?php
touch('system.lock');
...
unlink('system.lock');
clearstatcache(); // should be done by unlink?
?>
script2:
<?php
while (is_file('system.lock') {
sleep(1);
clearstatcache(); // without this, script 2 will deadlock forever!
}
?>
I also found this page, which leads to the same conclusion:
https://stackoverflow.com/questions/9251237/clearstatcache-include-path-sessions Note that this function affects only file metadata. However, all the PHP file system functions do their own caching of actual file contents as well. You can use the "realpath_cache_size = 0" directive in PHP.ini to disable the content caching if you like. The default content caching timeout is 120 seconds.
Content caching is not a good idea during development work and for certain kinds of applications, since your code may read in old data from a file whose contents you have just changed.
Note: This is separate from the caching typically done by browsers for all GET requests (the majority of Web accesses) unless the HTTP headers override it. It is also separate from optional Apache server caching.Just to make this more obvious (and so search engines find this easier):
If you do fileops of any kind outside of PHP (say via a system() call), you probably want to clear the stat cache before doing any further tests on the file/dir/whatever. For example:
<?php
// is_dir() forces a stat call, so the cache is populated
if( is_dir($foo) ) {
system("rm -rf " . escapeshellarg($foo));
if( is_dir($foo) ) {
// ...will still be true, even if the rm succeeded, because it's just
// reading from cache, not re-running the stat()
}
}
?>
Pop a clearstatcache() after the system call and all is good (modulo a bit of a performance hit from having a cleared stat cache :-( ).