Home > Article > Backend Development > Caching static page classes
/** * 缓存静态页面类 */ class HtmlCache{ /** * 开启缓存 * $filename缓存完整路径 * $time缓存时间单位是秒,默认7200秒 */ public function cache_start($filename,$time=7200) { $cachefile = $filename; $cachetime = $time; ob_start(); if(file_exists($cachefile) && (time()-$cachetime < filemtime($cachefile)))//判断文件是否存在或者是否在缓存时间内 { include($cachefile); ob_end_flush(); exit; } } /** * 结束缓存 * $filename缓存完整路径 */ public function cache_end($filename){ $cachefile = $filename; $fp = fopen($cachefile, 'w'); fwrite($fp, ob_get_contents()); fclose($fp); ob_end_flush(); } } 用法: $HtmlCache = new HtmlCache(); $filename = "./cache.html"; $HtmlCache->cache_start($filename); //以下是输出的内容,放在cache_start和cache_end两个方法之间 echo "cache"; $HtmlCache->cache_end($filename);
The above introduces the caching static page class, including caching content. I hope it will be helpful to friends who are interested in PHP tutorials.