PHP processing static pages: Detailed graphic and text explanation of page setting cache time

墨辰丷
Release: 2023-03-27 07:44:01
Original
1190 people have browsed it

This article mainly introduces PHP to process static pages: page setting cache time detailed graphic and text explanation, interested friends can refer to it, I hope it will be helpful to 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 1: add cache time to the page

User request page => Whether the page has expired => => No (get 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:

Easy writing of PHP static pages_PHP tutorial

##php Use tag replacement to generate static pages, php static pages_PHP tutorial

Use PHP to generate HTML static pages, php static pages_PHP tutorial

The above is the detailed content of PHP processing static pages: Detailed graphic and text explanation of page setting cache time. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!