PHP缓存小作
版权声明:原创作品,谢绝转载!否则将追究法律责任。 |
<!--cache.php-->
<?php
class cache { var $_file; var $cache_time; var $CacheRoot=CACHE_PATH; function cache($cache_time=1,$CacheUrl=false) {//初始化
//$this -> _file = $CacheUrl ? ($this->CacheRoot.$CacheUrl) : ($this -> CacheRoot.$this -> get_url()); $this -> _file = $CacheUrl ? $CacheUrl : ($this -> CacheRoot.$this -> get_url()); $this -> cache_time = $cache_time; } function start() {
if($this->cache_is_active()) { include($this->_file); exit; } ob_start(); } function _end() {
$this->make_cache(); ob_end_flush(); } function cache_is_active() {//判断文件是否存在以及过期
if ($this->cache_is_exist()) { if (time() - $this->lastModified() < $this->cache_time){ Return true; } else{ Return false; } } else{ Return false; } } function make_cache() {//生成缓存
$content = $this->get_cache_content(); if($this->write_file($content)) { Return true; } else { Return false; } } function cache_is_exist() {//检测问是否存在
if(file_exists($this->_file)){Return true;} else{Return false;} } function lastModified() {//取得文件最后修改时间
Return @filemtime($this->_file); } function get_cache_content() {//取得文件内容
$contents = ob_get_contents(); return $contents; //return '<!--'.date('Y-m-d H:i:s').'-->'.$contents;//缓存时间 } function write_file($content){//建立缓存文件
$this->mk_dir($this->_file); if(!$fp=fopen($this->_file,'w')){ $this->report_Error('无法打开缓存文件.');//trigger_error return false; } if(!flock($fp,LOCK_EX)){ $this->report_Error('无法锁定缓存文件.'); return false; } if(!fwrite($fp,$content)){ $this->report_Error('无法写入缓存文件.'); return false; } flock($fp,LOCK_UN);//释放锁定 fclose($fp);//关闭 return true; } function mk_dir(){//建立目录
$dir = @explode("/", $this->_file); $num = @count($dir)-1; $tmp = './'; for($i=0; $i<$num; $i++){ $tmp .= $dir[$i]; if(!file_exists($tmp)){ @mkdir($tmp); @chmod($tmp, 0777); } $tmp .= '/'; } } function clear_cache() {//清除缓存文件,后台使用
if (_file">!@unlink($this->_file)) { $this->report_Error('Unable to remove cache'); Return false; } else { Return true; } } function get_url() {//取得当前文件URL并使用base64_encode进行编码
if (isset($_SERVER['REQUEST_URI'])) { $url = $_SERVER['REQUEST_URI']; }else{ $url = $_SERVER['script_NAME']; $url .= (!empty($_SERVER['QUERY_STRING'])) ? '?' . $_SERVER['QUERY_STRING'] : ''; } return base64_encode($url); } function report_Error($message=NULL) {//发送错误
if($message!=NULL) { trigger_error($message); } } } ?> <!--index.php--> <?php
require_once('cache.php'); $cache = new cache(20,"./cache/index.cache");//参数:时间(秒),缓存路径 $cache->start(); echo date("Y-m-d h:i:s"); $cache->_end(); ?> 本文出自 “逍遥郭” 博客,谢绝转载! 本文出自 51CTO.COM技术博客 |


fei20082008
博客统计信息
热门文章
最新评论
友情链接