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
(PHP 4, PHP 5)
clearstatcache — Limpia la caché de estado de un archivo
Descripción
$clear_realpath_cache = false
[, string $filename
]] )Cuando usa stat(), lstat(), o cualquier otra función enumerada en la lista de funciones afectadas (abajo), PHP examina la información que devuelven esas funciones para proporcionar un rendimiento más rápido. Sin embargo, en ciertos casos, puede querer borrar la información almacenada en caché. Por ejemplo, si el mismo archivo está siendo verificado múltiples veces dentro de un sólo script, y ese archivo corre el peligro de ser borrado o modificado durante la operación de ese script, puede optar por limpiar la caché de estado. En estos casos, puede usar la función clearstatcache() para borrar la información que PHP examina del archivo.
Debería observar también que PHP no examina información sobre archivos no
existentes. Por lo que si llama a file_exists() con un archivo que
no existe, se devolverá FALSE a menos que cree el archivo. Si crea
el archivo, se devolverá TRUE incluso si después borra el archivo.
Sin embargo unlink() limpia la caché automáticamente.
Nota:
Esta función examina la información sobre nombres de archivos específicos, por lo que sólo necesita llamar a clearstatcache() si está llevando a cabo múltiples operaciones sobre un mismo nombre de archivo y necesita que la información sobre ese archivo en particular no sea examinada.
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().
Parámetros
-
clear_realpath_cache -
Si se limpia la caché de la ruta real o no.
-
filename -
Limpia la caché de la ruta real de un nombre de archivo específico, sólo se usa si
clear_realpath_cacheesTRUE.
Valores devueltos
No devuelve ningún valor.
Historial de cambios
| Versión | Descripción |
|---|---|
| 5.3.0 |
Se añadieron los parámetros opcionales clear_realpath_cache
y filename.
|
Ejemplos
Ejemplo #1 Ejemplo de clearstatcache()
<?php
$archivo = 'output_log.txt';
function obtener_propietario($archivo)
{
$estadísticas = stat($archivo);
$usuario = posix_getpwuid($estadísticas['uid']);
return $usuario['name'];
}
$formato = "UID @ %s: %s\n";
printf($formato, date('r'), obtener_propietario($archivo));
chown($archivo, 'ross');
printf($formato, date('r'), obtener_propietario($archivo));
clearstatcache();
printf($formato, date('r'), obtener_propietario($archivo));
?>
El resultado del ejemplo sería algo similar a:
UID @ Sun, 12 Oct 2008 20:48:28 +0100: root UID @ Sun, 12 Oct 2008 20:48:28 +0100: root UID @ Sun, 12 Oct 2008 20:48:28 +0100: ross
On Linux, a forked process inherits a copy of the parent's cache, but after forking the two caches do not impact each other. The snippet below demonstrates this by creating a child and confirming outdated (cached) information, then clearing the cache, and getting new information.
<?php
function report($directory, $prefix = '') { printf('%sDoes %s exist? PHP says "%s"'. PHP_EOL, $prefix, $directory, is_dir($directory) ? 'yes' : 'no'); }
$target = './delete-me-before-running-statcache';
if (is_dir($target)) {
die("Delete $target before running.\n");
}
echo "Creating $target.\n";
mkdir($target) || die("Unable to create $target.\n");
report($target); // is_dir($target) is now cached as true
echo "Unlinking $target.\n";
rmdir($target) || die("Unable to unlink $target.\n");
// This will say "yes", which is old (inaccurate) information.
report($target);
if (($pid = pcntl_fork()) === -1) { die("Failed to pcntl_fork.\n"); }
elseif ($pid === 0) {
// child
report($target, '<<child>> ');
echo "<<child>> Clearing stat cache.\n";
clearstatcache();
report($target, '<<child>> ');
} else {
// parent
sleep(2); // move this to the child block to reverse the test.
report($target, '<<<parent>> ');
clearstatcache();
report($target, '<<<parent>> ');
}
?>
