Home > Backend Development > PHP Tutorial > PHP cache class

PHP cache class

WBOY
Release: 2016-07-25 09:09:58
Original
1094 people have browsed it
  1. define('CACHE_ROOT', dirname(__FILE__).'/cache'); //Cache storage directory
  2. define('CACHE_TIME', 1800); //Cache time unit seconds
  3. define( 'CACHE_FIX','.html');
  4. $CacheName=md5($_SERVER['REQUEST_URI']).CACHE_FIX; //Cache file name
  5. $CacheDir=CACHE_ROOT.'/'.substr($CacheName,0,1 );//Cache file storage directory
  6. $CacheUrl=$CacheDir.'/'.$CacheName;//The complete path of the cache file
  7. //The cache is only cached after GET request. After POST, you generally want to see the latest results
  8. if ($_SERVER['REQUEST_METHOD']=='GET'){
  9. //If the cache file exists and has not expired, read it out.
  10. if(file_exists($CacheName) && time()-filemtime($CacheName) $fp=fopen($CacheName,'rb');
  11. fpassthru($fp);
  12. fclose($fp) ;
  13. exit;
  14. }
  15. //Check whether the folder exists, create it if it does not exist
  16. elseif(!file_exists($CacheDir)){
  17. if(!file_exists(CACHE_ROOT)){
  18. mkdir(CACHE_ROOT,0777);
  19. chmod (CACHE_ROOT,0777);
  20. }
  21. mkdir($CacheDir,0777);
  22. chmod($CacheDir,0777);
  23. }
  24. //Callback function, this function is automatically called when the program ends
  25. function AutoCache($contents){
  26. global $CacheUrl;
  27. $fp=fopen($CacheUrl,'wb');
  28. fwrite($fp,$contents);
  29. fclose($fp);
  30. chmod($CacheUrl,0777);
  31. //Generate new While caching, all old caches are automatically deleted to save space and can be ignored.
  32. //DelOldCache();
  33. return $contents;
  34. }
  35. function DelOldCache(){
  36. chdir(CACHE_ROOT);
  37. foreach (glob("*/*".CACHE_FIX) as $file){
  38. if(time() -filemtime($file)>CACHE_TIME)unlink($file);
  39. }
  40. }
  41. //Callback function auto_cache
  42. ob_start('AutoCache');
  43. }else{
  44. //Delete the cache file if it is not a GET request.
  45. if(file_exists($CacheUrl))unlink($CacheUrl);
  46. }
  47. ?>
Copy code


Related labels:
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