Home > Backend Development > PHP Tutorial > PHP page setting cache time example code

PHP page setting cache time example code

小云云
Release: 2023-03-20 09:28:01
Original
3285 people have browsed it

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{
  // 重新生成一份静态页面
}
Copy after login

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());
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template