Php 网页缓存
我正在寻找缓存网页的最佳解决方案示例http:/www.website.com/test.php?d=2011-11-01,其url重写规则为http:/www.website.com/testd-2011-11-01.html 下面的脚本不适用于动态网页,无论查询如何,它都会提供相同的页面Php 网页缓存,php,Php,我正在寻找缓存网页的最佳解决方案示例http:/www.website.com/test.php?d=2011-11-01,其url重写规则为http:/www.website.com/testd-2011-11-01.html 下面的脚本不适用于动态网页,无论查询如何,它都会提供相同的页面 <?php $cachefile = "cache/".$reqfilename.".html"; $cachetime = 240 * 60; // 5 minutes //
<?php
$cachefile = "cache/".$reqfilename.".html";
$cachetime = 240 * 60; // 5 minutes
// Serve from the cache if it is younger than $cachetime
if (file_exists($cachefile) && (time() - $cachetime
< filemtime($cachefile)))
{
include($cachefile);
echo "<!-- Cached ".date('jS F Y H:i', filemtime($cachefile))."
-->";
exit;
}
ob_start(); // start the output buffer?>
my website content here
<?php
// open the cache file for writing
$fp = fopen($cachefile, 'w');
// save the contents of output buffer to the file
fwrite($fp, ob_get_contents());
// close the file
fclose($fp);
// Send the output to the browser
ob_end_flush(); ?>
我的网站内容在这里
如果您的URL看起来像testd-2011-11-01.html
,您有两种可能的解决方案:
- 使用一些,以便URL被重写为
;然后,您的test.php?d=2011-11-01
脚本可以处理缓存生成/失效test.php
- 或者使用,它将每隔X分钟重新生成
静态文件testd-2011-11-01.html
第二种解决方案在性能方面可能会更好一些(除了cronjob运行时,不会执行任何PHP代码);但区别可能并不那么重要,除非你有一个拥有大量用户的大型网站。类似的方法可能会奏效:
class SimpleCache {
private $_cacheDir = '/path/to/cache';
private $_cacheTime = 240*60;
public function isCached( $id ) {
$cacheFilename = $this->_cache . "/" . $id . "_*";
$files = glob($cacheFilename, GLOB_NOSORT);
if( $files && !empty($files) ) {
// There should always be one file in the array
$filename = $files[0];
$params = explode("_", $filename);
$cacheTime = strtok($params[1], '.');
// Check if the cached file is too old
if( time() - $params[1] > $this->_cacheTime ) {
@unlink($filename);
}
else {
return $filename;
}
}
return false;
}
public function cache( $id, $data ) {
$filename = $this->_cache . "/" . $id. "_" . time() . ".cache";
if( !($fp = @fopen($filename, "w")) ) {
return false;
}
if( !@fwrite($fp, $data) ) {
@fclose($fp);
return false;
}
@fclose($fp);
return true;
}
}
$cache = new SimpleCache();
if( !($buffer = $cache->isCached($reqfilename)) ) {
// Produce the contects of the file and save them in the $buffer variable
$cache->cache($reqfilename, $buffer);
}
echo $buffer;
但是,如果您能胜任,您可以使用memcached、APC和更高级的缓存技术您可以使用HTTP缓存。您可以发送标题,告诉客户端(浏览器)将整个页面缓存一段时间
// 5 minutes
header('Cache-Control: max-age=300');
如果您可以控制托管环境,还可以在Web服务器前面添加varnish或nginx等反向代理。然后,该代理将为您缓存这些请求,使缓存的版本在您站点的所有访问者之间共享
另请参见。通过对这个答案进行投票,我刚刚把你推到了10万人的高度:)祝贺你@不幸的是,在过去的几个月里,我真的没有太多的时间,但我看到我的声誉计数器每天都在增长(多亏了我提供的大量不太糟糕的答案),越来越接近10万;如果是你把我推到10万,谢谢;-)