我在 PHP 页面中有以下代码。有时,当我删除cache2.html文件时,我希望php重新创建它,并且下一个人将获得cache2.html而不是执行php代码。我有时会在页面上收到以下警告,但没有内容。是因为多个用户同时访问php吗?如果是这样,我该如何解决?谢谢。
Warning: include(dir1/cache2.html) [function.include]: failed to open stream: No such file or directory in /home/content/54/site/index.php on line 8
<?php
if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start();
$cachefile = "dir1/cache2.html";
if (file_exists($cachefile)) {
include($cachefile); // output the contents of the cache file
} else {
/* HTML (BUILT USING PHP/MYSQL) */
$cachefile = "dir1/cache2.html";
$fp = fopen($cachefile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
ob_flush(); // Send the output to the browser
}
?>
最佳答案
对 file_exists() 的调用本身会被缓存,因此即使文件被删除后,您也可能会得到 true 的返回值。请参阅:
http://us.php.net/manual/en/function.clearstatcache.php
所以,你可以这样做:
clearstatcache();
if (file_exists($cache)) {
include($cache);
} else {
// generate page
}
或者,你可以这样做:
if (file_exists($cache) && @include($cache)) {
exit;
} else {
// generate page
}
或者更好的是,如果您要从 PHP 进程中删除缓存文件,则只需在删除文件后调用clearstatcache() 即可。
关于PHP 文件包含错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10887218/