当前位置: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定时扫描程序

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

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

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

<?php
if(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怎么设置缓存时间的详细内容,更多请关注gxlcms其它相关文章!

人气教程排行