当前位置:Gxlcms > PHP教程 > php怎么设置缓存时间

php怎么设置缓存时间

时间:2021-07-01 10:21:17 帮助过:78人阅读

php设置缓存时间的方法:首先创建一个PHP示例文件;然后通过“if(is_file('./index.html') && (time()-filemtime('./index.html')) < 60){...}”方法设置缓存时间即可。

推荐:《PHP视频教程》

本教程操作环境:

  • Windows7系统、PHP5.6版

  • 适用于所有品牌电脑

php处理静态页面:页面设置缓存时间

1.页面添加缓存时间

2.手动触发的方式

3.crontab定时扫描程序

我们来实现方案一:页面添加缓存时间

  1. 用户请求页面 => 页面是否过期 =>
  2. => 否(获取静态页面) || =>是(动态页面生成一份新的静态页面)
  3. if( 如果存在这个静态文件 && 没有过期){
  4. // 获取页面
  5. }else{
  6. // 重新生成一份静态页面
  7. }

ok,基本逻辑就是如此,下面我们完善代码:

  1. <?php
  2. if(is_file('./index.html') && (time()-filemtime('./index.html')) < 60){
  3. // 假设缓存时间是60秒
  4. // 获取页面
  5. require_once('./index.html');
  6. }else{
  7. // 重新生成一份静态页面
  8. // 准备要展示到网页的数据
  9. $data = array(
  10. array('id'=>1,'msg'=>'hello java'),
  11. array('id'=>2,'msg'=>'hello php'),
  12. array('id'=>3,'msg'=>'hello python'),
  13. );
  14. // 渲染到模板
  15. // 实际项目一般是在html里渲染
  16. // 这里演示 希望能看懂
  17. ob_start(); // 开始输入缓冲控制
  18. foreach($data as $item){
  19. echo $item['id'].'===>'.$item['msg'].'<br/>';
  20. }
  21. // 开始生成静态页面文件
  22. file_put_contents('index.html',ob_get_contents());
  23. }

这样我们访问index.php,如果静态文件缓存没有过期,其实质访问的内容来自index.html这个静态文件。

以上就是php怎么设置缓存时间的详细内容,更多请关注gxlcms其它相关文章!

人气教程排行