Different websites require different caching functions. Some websites only need to cache the requested get information, but some websites need to cache the complete URL information. Here is a commonly used caching code that has been written.
cache code
<?php
//缓存存放目录
define('CACHE_ROOT', dirname(__FILE__) . DIRECTORY_SEPARATOR . 'empirecms');
//缓存时间 单位秒
define('CACHE_TIME', 86400*7);
//缓存文件后缀
define('CACHE_FIX','.php');
date_default_timezone_set("Asia/Shanghai");
$CacheName=md5($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']) . CACHE_FIX; //缓存文件名
$CacheDir=CACHE_ROOT . DIRECTORY_SEPARATOR . substr($CacheName,0,1);//缓存文件存放目录
$CacheUrl=$CacheDir . DIRECTORY_SEPARATOR . $CacheName;//缓存文件的完整路径
//GET方式请求才缓存,POST之后一般都希望看到最新的结果
if($_SERVER['REQUEST_METHOD']!='POST'){
//如果缓存文件存在,并且没有过期,就把它读出来。
if(file_exists($CacheUrl) && time()-filemtime($CacheUrl)<CACHE_TIME){
echo gzuncompress(file_get_contents($CacheUrl));
exit;
}
//判断文件夹是否存在,不存在则创建
elseif(!file_exists($CacheDir)){
if(!file_exists(CACHE_ROOT)){
mkdir(CACHE_ROOT,0777);
chmod(CACHE_ROOT,0777);
}
mkdir($CacheDir,0777);
chmod($CacheDir,0777);
}
//回调函数,当程序结束时自动调用此函数
function AutoCache($contents){
global $CacheUrl;
$fp=fopen($CacheUrl,'wb');
$contents = "<!--站长qq:1810216796 缓存更新时间: ".(date("Y-m-d H:i:s", time()))."-->\r\n".$contents;
fwrite($fp,gzcompress($contents));
fclose($fp);
chmod($CacheUrl,0777);
//生成新缓存的同时,自动删除所有的老缓存,以节约空间,可忽略。
DelOldCache();
return $contents;
}
function DelOldCache(){
chdir(CACHE_ROOT);
foreach (glob("*/*".CACHE_FIX) as $file){
if(time()-filemtime($file)>CACHE_TIME) unlink($file);
}
}
ob_start('AutoCache');//回调函数 auto_cache
clearstatcache();//清除文件缓存
}else{
//不是GET的请求就删除缓存文件。
if(file_exists($CacheUrl)) unlink($CacheUrl);
}
?>How to use
If you want to use it, just quote the code directly.
Code focus
The main reason is that the callback function of PHP is difficult to understand. After supplementing some basic knowledge, I can barely understand it. Among themob_startI checked the manual for this function and the details are as follows:
ob example
Example of user-defined callback function
<?php
function callback ( $buffer )
{
// replace all the apples with oranges
return ( str_replace ( "apples" , "oranges" , $buffer ));
}
ob_start ( "callback" );
?>
<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>
<?php
ob_end_flush ();
?>
The above routine will output:
<html>
<body>
<p>It's like comparing oranges to oranges.</p>
</body>
</html>
