Home >Backend Development >PHP Problem >How to set cache time in php
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.
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('./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()); }
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!