Home  >  Article  >  Backend Development  >  The principle of sending a PHP cache class_PHP tutorial

The principle of sending a PHP cache class_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:43:56837browse

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);//Cache file storage directory
$CacheUrl=$CacheDir./.$CacheName;//Full path of cache file
//The GET request is cached. 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;
}
// 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);
//While generating a new cache, automatically delete all old caches 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);
}
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478808.htmlTechArticle?php 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_U...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn