Copy the code The code is as follows:
define('CACHE_ROOT', dirname(__FILE__).'/cache'); //Cache storage directory
define('CACHE_TIME', 1800); //Cache time in seconds
define('CACHE_FIX','.html');
$CacheName=md5($_SERVER['REQUEST_URI']).CACHE_FIX; //Cache file name
$CacheDir=CACHE_ROOT.'/' .substr($CacheName,0,1);//The cache file storage directory
$CacheUrl=$CacheDir.'/'.$CacheName;//The complete path of the cache file
//The cache is only cached after GET request, generally after POST Everyone wants to see the latest results
if($_SERVER['REQUEST_METHOD']=='GET'){
//If the cache file exists and has not expired, read it out.
if(file_exists($CacheName) && time()-filemtime($CacheName)
fpassthru($fp);
fclose($fp) ;
exit;
}
//Determine whether the folder exists, create it if it does not exist
elseif(!file_exists($CacheDir)){
if(!file_exists(CACHE_ROOT)){
mkdir(CACHE_ROOT,0777);
chmod (CACHE_ROOT,0777);
}
mkdir($CacheDir,0777);
chmod($CacheDir,0777);
}
//Callback function, this function is automatically called when the program ends
function AutoCache($contents){
global $CacheUrl;
$fp=fopen($CacheUrl,'wb');
fwrite($fp,$contents);
fclose($fp);
chmod($CacheUrl,0777);
//Generate new While caching, all old caches are automatically deleted to save space and can be ignored.
//DelOldCache();
return $contents;
}
function DelOldCache(){
chdir(CACHE_ROOT);
foreach (glob("*/*".CACHE_FIX) as $file){
if(time() -filemtime($file)>CACHE_TIME)unlink($file);
}
}
//Callback function auto_cache
ob_start('AutoCache');
}else{
//Delete the cache file if it is not a GET request.
if(file_exists($CacheUrl))unlink($CacheUrl);
}
?>
The above has introduced the instructions. A PHP caching class code is attached with detailed instructions, including instructions. I hope it will be helpful to friends who are interested in PHP tutorials.