Php 浏览器缓存还是磁盘缓存?
就在几天前,我开始使用浏览器缓存,缓存js和css文件并保持“未修改”,效果非常好 现在我想在系统的许多页面上应用相同的方法。例如,我有一个页面,其中列出了数据库中的“用户”,我希望缓存该页面,以避免在数据库中过度加载查询 我的问题是:这是一个好方法(缓存时页面是否仍执行db查询?),还是应该使用磁盘缓存或memcachedPhp 浏览器缓存还是磁盘缓存?,php,caching,memcached,Php,Caching,Memcached,就在几天前,我开始使用浏览器缓存,缓存js和css文件并保持“未修改”,效果非常好 现在我想在系统的许多页面上应用相同的方法。例如,我有一个页面,其中列出了数据库中的“用户”,我希望缓存该页面,以避免在数据库中过度加载查询 我的问题是:这是一个好方法(缓存时页面是否仍执行db查询?),还是应该使用磁盘缓存或memcached header("HTTP/1.1 304 Not Modified"); header("Expires: ".gmdate("D, d M Y H:i:s", time(
header("HTTP/1.1 304 Not Modified");
header("Expires: ".gmdate("D, d M Y H:i:s", time()+(60*86400))." GMT");
header("Cache-Control: must-revalidate");
mysql_query(" SELECT * FROM `users` ");
// list all users
这是一个简单的磁盘缓存示例,我在缓存动态内容时使用了这种方法,动态内容经常发生变化,如统计信息、菜单、rssfeeds、页面等
<?php
$cacheTime=3600; /*1hour*/
if(file_exists('./cache/'.sha1('users').'.php') && $_SESSION['user_status']!=true){
$FileCreationTime = filectime('./cache/'.sha1('users').'.php');
/* Calculate file age in seconds*/
$FileAge = time() - $FileCreationTime;
/*1h cache*/
if ($FileAge > ($cacheTime)){unlink('./cache/'.sha1('users').'.php');header('Location: '.$_SERVER['REQUEST_URI']);die();}
include("./cache/".sha1('users').".php");
/*Cache is there and not older then 1hour so echo the cache*/
echo base64_decode($cache);
}else{
/*************************************************************/
//Cache is NOT there or user logged in or older then 1hour so regenerate content
//Do Content and store in $return variable
$return='';
$result = mysql_query(" SELECT * FROM `users` ");
while($row=mysql_fetch_assoc($result)){
$return .='<ul>'.$row['user'].'</ul>';
...
}
...
...
$return .='bla bla';
/*************************************************************/
/*Check if not logged in else save*/
if($_SESSION['user_status']!=true){
$cache_file_encoded = base64_encode($return);
$cache_file = <<<CACHE
<?php
/**
* Cached for:Users Page [{$_SERVER["HTTP_HOST"]}{$_SERVER['REQUEST_URI']}] Base64
*/
\$cache ="$cache_file_encoded"; ?>
CACHE;
file_put_contents('./cache/'.sha1('users').'.php',$cache_file);
}
echo $return;
}
?>
隐藏物
文件内容('./cache/'.sha1('users')..php',$cache\u文件);
}
回音$return;
}
?>
不建议在动态页面上使用缓存(原因很明显)。在我正在使用的系统上,取消缓存并从数据库中调用结果取决于另一个因素。因此,我可以将其缓存起来,并在需要时取消它。