A PHP caching class code (with detailed description)_PHP tutorial

WBOY
Release: 2016-07-21 15:28:27
Original
751 people have browsed it

Copy code The code is as follows:

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 full path of the cached file
//The cache is only cached when requested in GET mode. 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/323583.htmlTechArticleCopy the code as follows: ?php define('CACHE_ROOT', dirname(__FILE__).'/cache'); //Cache storage directory define('CACHE_TIME', 1800); //Cache time unit seconds define('CACHE_FIX','.html...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template