php clearstatcache()

2020-01-15  本文已影响0人  金星show

clearstatcache — 清除文件状态缓存
clearstatcache ([ bool clear_realpath_cache = false [, stringfilename ]] ) : void

当使用 stat(),lstat() 或者任何列在受影响函数表(见下面)中的函数时,PHP 将缓存这些函数的返回信息以提供更快的性能。然而在某些情况下,你可能想清除被缓存的信息。例如如果在一个脚本中多次检查同一个文件,而该文件在此脚本执行期间有被删除或修改的危险时,你需要清除文件状态缓存。这种情况下,可以用 clearstatcache() 函数来清除被 PHP 缓存的该文件信息。

必须注意的是,对于不存在的文件,PHP 并不会缓存其信息。所以如果调用 file_exists()来检查不存在的文件,在该文件没有被创建之前,它都会返回 FALSE。如果该文件被创建了,就算以后被删除,它都会返回 TRUE
函数 unlink()会自动清除该缓存。

受影响的函数包括 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()

例子1:

<?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));
?>

以上例程的输出类似于:

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

例子2:
如果是对一个远程文件校验文件是否存在,unlink()这个文件,不会删除缓存,因此还需要执行一下clearstatcache()

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.

上一篇 下一篇

猜你喜欢

热点阅读