查看: 17275|回复: 0

PHP网站性能优化-页面静态缓存

[复制链接]
发表于 2019-1-12 10:02:39 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转南昌530论坛

您需要 登录 才可以下载或查看,没有账号?注册会员

×
  1.   ob_start()    //开启缓存
  2.         
  3.   ob_get_contents()  //获取缓存到的内容
复制代码
  1. <?php
  2.     //查找有没有缓存文件的存在
  3.     if(file_exists('./cache/index.html')){
  4.         //有缓存文件直接调用
  5.         include './cache/index.html';
  6.         //获取当前时间戳
  7.         $now_time = time();
  8.         //获取缓存文件时间戳
  9.         $last_time = filemtime('./cache/index.html');
  10.         //如果缓存文件生成超过指定的时间直接删除文件
  11.         if(($now_time - $last_time)/60>30){
  12.             unlink('./cache/index.html');
  13.         }
  14.         exit;
  15.     }
  16.     //开启缓存
  17.     ob_start();

  18. ?>
  19. <!doctype html>
  20. <html>
  21. <head>
  22. <meta charset="utf-8">
  23. <meta http-equiv="X-UA-Compatible" content="IE-Edge" />
  24. <title>南昌论坛</title>
  25. <meta name="copyrihgt" content="www.nc530.com"/>
  26. <link rel="shortcut icon" href="./favicon.jpg" type="image/x-icon"/>
  27. <link rel="stylesheet" href="./static/css/style.css" />
  28. </head>
  29. <body>

  30. ...省略html或php代码...

  31. </body>
  32. </html>
  33. <?php
  34.     //在文件代码末尾获取上面生成的缓存内容
  35.     $content = ob_get_contents();
  36.     //写入到缓存内容到指定的文件夹
  37.     $fp = fopen('./cache/index.html','w');
  38.     fwrite($fp,$content);
  39.     fclose($fp);
  40.     ob_flush(); //从PHP内存中释放出来缓存(取出数据)     
  41.     flush(); //把释放的数据发送到浏览器显示     
  42.     ob_end_clean(); //清空缓冲区的内容并关闭这个缓冲区
  43. ?>
复制代码


您需要登录后才可以回帖 登录 | 注册会员

本版积分规则

关注公众号
Archiver|手机版|南昌530论坛

相关侵权、举报、投诉及建议等,请发 E-mail:nc530@outlook.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖
关注公众号
返回顶部