PHP页面实现缓存方法总结

前端之家收集整理的这篇文章主要介绍了PHP页面实现缓存方法总结前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

PHP页面缓存主要用到的是ob系列函数,如ob_start(),ob_end_flush(),ob_get_contents()

但是更高级的缓存是不用这些的。本文章最后有介绍。

funcs

ob_start(): 页面缓存开始的标志,此函数一下的内容直至ob_end_flush()或者ob_end_clean()都保存在页面缓存中

ob_get_contents(): 用来获取页面缓存中的内容获取到以后呢,我们就可以想怎么处理这些内容都行了,过滤字段啦,匹配内容啦,都可以

ob_end_flush(): 表示页面缓存结束。并且经我验证,缓存的内容输出当前页面上,也就是可以显示缓存内容

如果数据库查询量较大,可以用cache来解决这个问题。

编码部分

  1. 初始化函数包括:设置页面缓存路径,缓存文件命名格式等。

这里用到的识别ID是经加密的$_SERVER[REQUEST_URI]参数。这个函数中最后还有一个if判断:若未过缓存期,则加载缓存文件,否则加载源文件

// 目录命名方式,如exp_index
$dir = str_replace('/','_',substr($_SERVER['SCRIPT_NAME'],1,-4));
if(!file_exists($pd = PAGE_PATH.$dir.'/')){ 
    @mkdir($pd,777) or die('mkdir failed');
}

// eg: cache/page/exp_index
define('PAGE_FILE',$pd . $pageId . '.html');
$contents = file_get_contents(PAGE_FILE);

if($contents &amp;&amp; substr($contents,13,10) > time()){ // 对应page_cache()<a href="/tag/hanshu/" target="_blank" class="keywords">函数</a>中<a href="/tag/jiashang/" target="_blank" class="keywords">加上</a>的<a href="/tag/zidingyi/" target="_blank" class="keywords">自定义</a>头部
    echo substr($contents,27);
    exit;
}
return true;

}

  1. 页面缓存函数

tips: 在缓存文件内容加上一个头部信息--过期时间,所以每次只需要对头部中的过期时间和当前时间进行比较(在page_init()函数中进行)就能判断缓存是否过期了。

PHP">    function page_cache($ttl = 0){
    $ttl = $ttl ? $ttl : PAGE_TTL; // cache time,default is 3600s
    $contents = ob_get_contents();
    $contents = "n" . $contents;
file_put_contents(PAGE_FILE,$contents);
ob_end_flush(); // release cache
}</code></pre>
  1. 函数使用,注意这两个函数有先后执行顺序,还有别忘了ob_start()

PHP">    page_init();
    ob_start();
// code

page_cache(60); // always the last line of code</code></pre>

Example

PHP">
    $_time = 10;
    $dir = "D:PHP";
function cache_start($_time,$dir){
    $cachefile = $dir . '/' . sha1($_SERVER['REQUEST_URI']) . '.html';
    $cachetime = $_time;
    ob_start();
    if(file_exists($cachefile) &amp;&amp; (time() - filemtime($cachefile) < $cachetime)){
        include($cachefile);
        ob_end_flush();
        exit;
    }
}

function cache_end($dir){
    $cachefile = $dir . '/' . sha1($_SERVER['REQUEST_URI']) . '.html';
    $fp = fopen($cachefile,'w');
    fwrite($fp,ob_get_contents());
    fclose($fp);
    ob_end_flush();
}

cache_start($_time,$dir);
//以下是<a href="/tag/shuchu/" target="_blank" class="keywords">输出</a>的<a href="/tag/neirong/" target="_blank" class="keywords">内容</a>,放在cache_start和cache_end之间
for($i=0;$i<5;$i++){
    echo $i;
    sleep(1);
}
cache_end($dir);</code></pre>

利用生成文件做缓存

class Cache{
private $cache_folder = null;
private $wroot_dir = null; // 站点目录
private $cacher_create_time = null; // cacher文件的建立时间

public function __construct($cache_foldername,$cacher_time = 100){
    ob_start();
    $this->wroot_dir = $_SERVER['DOCUMENT_ROOT'];
    $this->cache_folder = $cache_foldername;
    $this->cacher_create_time = $cacher_time;
}

public function read_cache(){
    try{
        if(self::create_folder($this->cache_folder)){
            self::get_cache();
        }else{
            echo 'create cache dir fail';
            return false;
        }
    }catch (Exception $e){
        echo $e;
        return false;
    }
}

private function exist_folder($folder){
    if(file_exists($this->wroot_dir . '/' . $folder)){
        return true;
    }else{
        return false;
    }
}

private function create_folder($folder){
    if(!self::exist_folder($folder)){
        try{
            mkdir($this->wroot_dir . '/' . $folder,0777);
            chmod($this->wroot_dir . '/' . $folder,0777);
            return true;
        }catch (Exception $e){
            self::get_cache(); // echo cache
            return false;
        }
        return false;
    }else{
        return true;
    }
}

private function get_cache(){
    $file_name = self::get_filename();
    if(file_exists($file_name) &amp;&amp; ((filemtime($file_name) + $this->cacher_create_time) > time())){
        $content = file_get_contents($file_name);
        if($content){
            echo $content;
            ob_end_flush();
            exit;
        }else{
            echo 'read file fail';
            exit;
        }
    }
}
private function get_filename(){
    $filename = $file_name = $this->wroot_dir . '/' . $this->cache_folder . '/' . md5($_SERVER['QUERY_STRING']). '.html';
    return $filename;
}

public function create_cache(){
    $filename = self::get_filename();
    if($filename != ''){
        try{
            file_put_contents($filename,ob_get_contents());
            return true;
        }catch (Exception $e){
            echo $e;
            exit;
        }
        return true;
    }
    return  false;
}

// get all file in cache
public function list_file(){
    $path = $this->cache_folder;
    if($handle = opendir($path)){
        while(false !== ($file = readdir($handle))){
            if($file != '.' &amp;&amp; $file != ".."){
                $path1 = $path . '/' . $file;
                if(file_exists($path1)){
                    $result[] = $file;
                }
            }
        }
        closedir($handle);
    }
    return $result;
}

public function del_file(){
    $path = $this->cache_folder;
    if($handle = opendir($path)){
        while(false !== ($file = readdir($handle))){
            if($file != '.' &amp;&amp; $file != '..'){
                $path1 = $path . '/' . $file;
                if(file_exists($path1)){
                    unlink($path1);
                }
            }
        }
        closedir($handle);
    }
    return true;
}
}</code></pre>

PHP100.com/html/PHP/lei/2013/0905/5309.html">source

猜你在找的程序笔记相关文章