- define('CACHE_ROOT', dirname(__FILE__).'/cache'); //Cache storage directory
- define('CACHE_TIME', 1800); //Cache time unit seconds
- define( 'CACHE_FIX','.html');
- $CacheName=md5($_SERVER['REQUEST_URI']).CACHE_FIX; //Cache file name
- $CacheDir=CACHE_ROOT.'/'.substr($CacheName,0,1 );//Cache file storage directory
- $CacheUrl=$CacheDir.'/'.$CacheName;//The complete path of the cache file
- //The cache is only cached after GET request. After POST, you generally want 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) $fp=fopen($CacheName,'rb');
- fpassthru($fp);
- fclose($fp) ;
- exit;
- }
- //Check 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);
- }
- ?>
Copy code
|