Home >Backend Development >PHP Tutorial >PHP page setting cache time example code
This article mainly introduces you to php processing static pages: page setting cache time examples. The editor thinks it is quite good. Now I will share it with you and give you a reference. Let’s follow the editor to take a look, I hope it can help everyone.
Q: How to trigger the system to generate a purely static page?
1. Add cache time to the page
2. Manual triggering method
3.crontab scheduled scanner
Let’s implement option one: add cache time to the page
User request page => Whether the page has expired=> => No (get a static page) || = >Yes (the dynamic page generates a new static 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, when we access index.php, if the static file cache has not expired, the actual accessed content comes from the static file index.html.
Related recommendations:
How to set static content cache time in php, php setting static cache_PHP tutorial
The above is the detailed content of PHP page setting cache time example code. For more information, please follow other related articles on the PHP Chinese website!