Home  >  Article  >  Backend Development  >  How to set cache time in php

How to set cache time in php

藏色散人
藏色散人Original
2020-11-27 09:05:582270browse

php method to set cache time: first create a PHP sample file; then pass "if(is_file('./index.html') && (time()-filemtime('./index.html') )) < 60){...}" method to set the cache time.

How to set cache time in php

Recommendation: "PHP Video Tutorial"

Operating environment for this tutorial:

  • Windows7 system, PHP5.6 version

  • Suitable for all brands of computers

php handles static pages: page settings Cache time

1. Page added cache time

2. Manual triggering method

3.crontab scheduled scanner

Let’s implement it Option 1: Add cache time to the page

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

ok, the basic logic is like this, let’s improve the code below:

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

In this way we access index.php, if the static file cache has not expired, its actual access The content comes from the static file index.html.

The above is the detailed content of How to set cache time in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn