downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

copy> <chown
[edit] Last updated: Fri, 18 Sep 2009

view this page in

clearstatcache

(PHP 4, PHP 5)

clearstatcacheИзчиства кеша за статуса на файл

Описание

void clearstatcache ([ bool $clear_realpath_cache [, string $filename ]] )

Когато използвате функциите stat(), lstat() или някоя от другите функции изброени по-долу PHP кешира информацията, която тези функции връщат с цел да осигури по-добра производителност. В някой случаи обаче може да искате да изчистите този кеш. Да вземем следния пример: скрипт проверява статуса на даден файл на няколко пъти в процеса на изпълнение, но има вероятност в някой момент този файл да бъде изтрит или променен. В такъв случай можете да използвате функцията clearstatcache(), за да изчистите кеша за статуса.

Трябва също така да се отбележи, че PHP не кешира информация за несъществуващи файлове, т.е. ако извикате file_exists() за несъществуващ файл тя ще върне FALSE. Когато създадете файла file_exists() ще връща TRUE докато не изтриете файла (т.е. няма нужда да извиквате clearstatcache() между проверките за съществуване на файла). Както може да се предположи при изтриване unlink() изчиства кеша автоматично.

Забележка: Тази функция кешира информацията за специфични файлове, така че трябва да извикате clearstatcache() само ако изпълнявате множество операции върху един и същ файл и изисквате информацията за този файл да не се кешира.

Списък на функциите, които създават кеш за статуса на файлове и които се засягат от действието на clearstatcache(): lstat(), file_exists(), is_writable(), is_readable(), is_executable(), is_file(), is_dir(), is_link(), filectime(), fileatime(), filemtime(), fileinode(), filegroup(), fileowner(), filesize(), filetype(), и fileperms().

Параметри

clear_realpath_cache

Дали да изчити кеша на realpath или не (по подразбиране е FALSE)

filename

Изчиства кеша на realpath за дадено име на файл. Използва се само ако clear_realpath_cache е TRUE.

Връщани стойности

Няма връщана стойност.

Дневник на промените

Версия Описание
5.3.0 Добавени са допълнителни параметри clear_realpath_cache и filename .

Примери

Example #1 Пример за използване на clearstatcache()

<?php
$file 
'output_log.txt';

function 
get_owner($file)
{
    
$stat stat($file);
    
$user posix_getpwuid($s['uid']);
    return 
$user['name'];
}

$format "UID @ %s: %s\n";

printf($formatdate('r'), get_owner($file));

chown($path'ross');
printf($formatdate('r'), get_owner($file));

clearstatcache();
printf($formatdate('r'), get_owner($file));
?>

Примерът по-горе ще изведе нещо подобно на:

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



add a note add a note User Contributed Notes clearstatcache
matt_m at me dot com 22-Sep-2011 09:04
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.
markandrewslade at gmail dot com 08-Mar-2010 04:54
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>> ');
}

?>

 
show source | credits | stats | sitemap | contact | advertising | mirror sites