phpday 2027 - Call for Papers

clearstatcache

(PHP 4, PHP 5, PHP 7, PHP 8)

clearstatcache — Svuota la cache dello stato dei file

Descrizione

function clearstatcache(bool $clear_realpath_cache = false, string $filename = ""): void

Quando si usano stat(), lstat() o una qualsiasi delle altre funzioni elencate nella lista delle funzioni interessate (sotto), PHP memorizza in cache le informazioni restituite da tali funzioni per fornire prestazioni migliori. Tuttavia, in alcuni casi, può essere necessario cancellare le informazioni memorizzate in cache. Ad esempio, se lo stesso file viene controllato più volte all'interno di un singolo script, e quel file rischia di essere rimosso o modificato durante l'esecuzione dello script, si può scegliere di svuotare la cache dello stato. In questi casi, è possibile usare la funzione clearstatcache() per cancellare le informazioni che PHP memorizza in cache su un file.

Si noti inoltre che PHP non memorizza in cache informazioni sui file inesistenti. Quindi, se si chiama is_file() su un file che non esiste, questa restituirà false finché il file non viene creato. Se si crea il file, restituirà true anche se poi il file viene eliminato. Tuttavia unlink() svuota la cache automaticamente.

Nota:

Questa funzione memorizza in cache informazioni su specifici nomi di file, quindi è necessario chiamare clearstatcache() solo se si eseguono più operazioni sullo stesso nome di file e occorre che le informazioni su quel particolare file non vengano memorizzate in cache.

Le funzioni interessate includono stat(), lstat(), file_exists(), is_writable(), is_readable(), is_executable(), is_file(), is_dir(), is_link(), filectime(), fileatime(), filemtime(), fileinode(), filegroup(), fileowner(), filesize(), filetype() e fileperms().

file_exists(), is_writable(), is_readable() e is_executable() usano la cache solo per i percorsi che usano un wrapper diverso dal filesystem locale. I file locali vengono controllati direttamente ogni volta.

Elenco dei parametri

clear_realpath_cache

Indica se svuotare anche la cache di realpath.

filename

Svuota la cache di realpath solo per uno specifico nome di file; usato solo se clear_realpath_cache è true.

Valori restituiti

Nessun valore viene restituito.

Esempi

Example #1 Esempio di clearstatcache()

<?php

$file = tempnam(sys_get_temp_dir(), 'stat-demo-');
file_put_contents($file, 'Ciao');

echo "Eseguire questo comando in un'altra shell:\n";
echo "\techo \" Mondo!\" >> $file\n";

$before = filesize($file); // memorizza in cache i metadati

sleep(20); // Eseguire il comando echo in un'altra shell

$cached = filesize($file); // vengono restituiti dati non aggiornati

clearstatcache();

$fresh = filesize($file);  // restituisce i dati corretti

printf("Prima: %d\nIn cache: %d\nAggiornato: %d\n", $before, $cached, $fresh);

unlink($file);

Il precedente esempio visualizzerà qualcosa di simile a:

Eseguire questo comando in un'altra shell:
    echo " Mondo!" >> /tmp/stat-demo-6fjvs4vir9ll2haCl4W
Prima: 4
In cache: 4
Aggiornato: 12

User Contributed Notes 6 notes

up
39
matt_m at me dot com
15 years ago
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.
up
12
msaladna at apisnetworks dot com
6 years ago
clearstatcache() does not canonicalize the path. clearstatcache(true, "/a/b/c") is different from clearstatcache(true, "/a/b//c").
up
13
vechenjivot at gmail dot com
6 years ago
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
up
9
David Spector
7 years ago
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.
up
11
bj at wjblack dot com
11 years ago
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 :-( ).
up
4
Gabriel
7 years ago
Definition of $filename parameter let's you think that it expects the filename only but it works if you give the path + filename also.

It should be more clear about this.
Adding new notes is disabled. Please see the links in the Found A Problem? section.
To Top