我使用以下代码来缓存访问的 URL,希望能节省一些 CPU。在 php 文件的开头:
$url = $_SERVER['DOCUMENT_ROOT'].$_SERVER["REQUEST_URI"];
$break = Explode('/', $url);
$file = $break[count($break) - 1];
$cachefile = 'cache/cached-'.$file.'.html';
$cachetime = 900;
// Serve from the cache if it is younger than $cachetime
if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) {
// echo "<!-- Cached copy, generated ".date('H:i', filemtime($cachefile))." -->\n";
readfile($cachefile);
exit;
}
ob_start();
php 文件末尾:
// Cache the contents to a cache file
$cached = fopen($cachefile, 'w');
fwrite($cached, ob_get_contents());
fclose($cached);
ob_end_flush(); // Send the output to the browser
这工作正常,但它使用完整的 URI 创建文件(即包括查询、# 等)。我正在尝试将缓存文件写入一次,而不需要任何其他内容。
换句话说,当有人访问 mysite.com/index.php 时,我希望创建一个文件index.php.html。如果其他人访问 mysite.com/index.php?sdgd=3534&#whatever&other&stuff 我希望缓存文件仍然是index.php.html,因此覆盖以前创建的index.php.html。我不想要名为index.php?sdgd=3534&#whatever&other&stuff.html的缓存文件 - 这似乎现在发生了。
我知道这可能与:
$cachefile = 'cache/cached-'.$file.'.html';
但我自己却无法弄清楚。
如何实现这一点?
谢谢大家的建议。事实并非如此,所以我要回答我自己的问题。显然答案就像改变一样简单
$url = $_SERVER['DOCUMENT_ROOT'].$_SERVER["REQUEST_URI"];
进入
$url = strtok($_SERVER['DOCUMENT_ROOT'].$_SERVER["REQUEST_URI"], '?');
这似乎缓存了一个名称不包括查询的文件。