php怎么设置缓存时间
2022-12-02 09:01:16
184
{{single.collect_count}}

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

php入门到就业线上直播课:进入学习
Apipost = Postman + Swagger + Mock + Jmeter 超好用的API调试工具:点击使用

推荐:《PHP视频教程

本教程操作环境:

  • Windows7系统、PHP5.6版

  • 适用于所有品牌电脑

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

1.页面添加缓存时间

2.手动触发的方式

3.crontab定时扫描程序

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

用户请求页面 => 页面是否过期 =>=> 否(获取静态页面) || =>是(动态页面生成一份新的静态页面)if( 如果存在这个静态文件 && 没有过期){// 获取页面}else{// 重新生成一份静态页面}
登录后复制

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

<?phpif(is_file('./index.html') && (time()-filemtime('./index.html')) < 60){ // 假设缓存时间是60秒// 获取页面require_once('./index.html');}else{// 重新生成一份静态页面// 准备要展示到网页的数据$data = array( array('id'=>1,'msg'=>'hello java'),array('id'=>2,'msg'=>'hello php'),array('id'=>3,'msg'=>'hello python'),);// 渲染到模板// 实际项目一般是在html里渲染// 这里演示 希望能看懂ob_start(); // 开始输入缓冲控制foreach($data as $item){echo $item['id'].'===>'.$item['msg'].'<br/>';}// 开始生成静态页面文件file_put_contents('index.html',ob_get_contents());}
登录后复制

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

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

回帖
全部回帖({{commentCount}})
{{item.user.nickname}} {{item.user.group_title}} {{item.friend_time}}
{{item.content}}
{{item.comment_content_show ? '取消' : '回复'}} 删除
回帖
{{reply.user.nickname}} {{reply.user.group_title}} {{reply.friend_time}}
{{reply.content}}
{{reply.comment_content_show ? '取消' : '回复'}} 删除
回帖
收起
没有更多啦~
{{commentLoading ? '加载中...' : '查看更多评论'}}