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, 25 May 2012

view this page in

clearstatcache

(PHP 4, PHP 5)

clearstatcacheОчищает кэш состояния файлов

Описание

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

Для обеспечения большей производительности при использовании функций stat(), lstat() или любой другой функции, перечисленных в приведенном ниже списке, PHP кеширует результаты их выполнения. Однако, в некоторых случаях вам может потребоваться очистка этого кэша. Например, когда ваш скрипт несколько раз проверяет состояние одного и того же файла, который может быть изменен или удален во время выполнения скрипта, вы можете захотеть очистить кэш состояния. В этом случае необходимо использовать функцию clearstatcache() для очистки в PHP кэшированной информации об указанном файле.

Обратите внимание, что PHP не кэширует информацию о несуществующих файлах. Так что если вы вызовите file_exists() на несуществующем файле, она будет возвращать FALSE до тех пор, пока вы не создадите этот файл. Если же вы создадите файл, она будет возвращать TRUE даже если затем вы его удалите. Однако, функция unlink() очистит данный кэш автоматически.

Замечание:

Данная фукнция кэширует информацию об определенных файлах, поэтому имеет смысл вызывать clearstatcache() только в том случае, если вы совершаете несколько операций с одним и тем же файлом и не хотите получать кэшированную информацию об этом файле.

Список функций, результаты выполнения которых кешируются: stat(), 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 или нет.

filename

Очистить кэш realpath для определенного файла, используется только если параметр clear_realpath_cache установлен в TRUE.

Возвращаемые значения

Эта функция не возвращает значения после выполнения.

Список изменений

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

Примеры

Пример #1 Пример использования 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($formatdate('r'), get_owner($file));

chown($file'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 23-Sep-2011 03: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 11: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