Heim >Backend-Entwicklung >PHP-Tutorial >php页面缓存ob系列函数的相关介绍

php页面缓存ob系列函数的相关介绍

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-25 09:08:08904Durchsuche
  1. function page_init()

  2. {
  3. $url = $_SERVER['REQUEST_URI'];//子url,该参数一般是唯一的
  4. $pageid = md5($url);
  5. $dir = str_replace('/','_',substr($_SERVER['SCRIPT_NAME'],1,-4));
  6. //目录命名方式,如exp_index
  7. if(!file_exists($pd = PAGE_PATH.$dir.'/'))@mkdir($pd,0777) or die("$pd目录创建失败");
  8. //如cache/page/exp_index/
  9. define('PAGE_FILE',$pd.$pageid.'.html');
  10.   //如cache/page/exp_index/cc8ef22b405566745ed21305dd248f0e.html
  11. $contents = file_get_contents(PAGE_FILE);//读出
  12. if($contents && substr($contents, 13, 10) > time() )//对应page_cache()函数中加上的自定义头部

  13. {
  14. echo substr($contents, 27);
  15. exit(0);
  16. }
  17. return true;
  18. }
  19. ?>
复制代码

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

  1. function page_cache($ttl = 0)
  2. {
  3. $ttl = $ttl ? $ttl : PAGE_TTL;//缓存时间,默认3600s
  4. $contents = ob_get_contents();//从缓存中获取内容
  5. $contents = "\n".$contents;
  6.   //加上自定义头部:过期时间=生成时间+缓存时间
  7. file_put_contents(PAGE_FILE, $contents);//写入缓存文件中
  8. ob_end_flush();//释放缓存
  9. }
  10. ?>
复制代码

三、函数使用,注意这两个函数有先后执行顺序,还有别忘了ob_start()。

  1. page_init();//页面缓存初始化

  2. ob_start();//开启缓存
  3. ...//代码段

  4. page_cache(60);//一般是最后一行

  5. ?>
复制代码


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:获取域名 Nächster Artikel:在羊驼中整合友言评论、留言板