<?php
define('CACHE_ROOT', dirname(__FILE__).'/cache'); // Cache store directory
define('CACHE_TIME', 1800);// Cache time Unit s
define('CACHE_FIX','.html');
$CacheName=md5($_SERVER['REQUEST_URI']).CACHE_FIX; // Cache file name
$CacheDir=CACHE_ROOT.'/'.substr($CacheName,0,1);// Cache files are stored in directories
$CacheUrl=$CacheDir.'/'.$CacheName;// The full path to the cache file
//GET Mode request to cache, POST after 1 I hope to see the latest results
if($_SERVER['REQUEST_METHOD']=='GET'){
// If the cache file exists and is not expired, read it out.
if(file_exists($CacheName) && time()-filemtime($CacheName)<CACHE_TIME){
$fp=fopen($CacheName,'rb');
fpassthru($fp);
fclose($fp);
exit;
}
// Determines if the folder exists, and creates it if it does not
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, which is automatically called when the program ends
function AutoCache($contents){
global $CacheUrl;
$fp=fopen($CacheUrl,'wb');
fwrite($fp,$contents);
fclose($fp);
chmod($CacheUrl,0777);
// When a new cache is generated, all old caches are automatically deleted , To save space , 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);
}
}
// The callback function auto_cache
ob_start('AutoCache');
}else{
// not GET To delete the cache file.
if(file_exists($CacheUrl))unlink($CacheUrl);
}
?>