static web page

public function index(){
        $index_module_file = "static/html/module/index.html";  //静态页面模板文件路径
        $index_file = "static/html/index.html";   //生成静态页面文件路径
        $express_time = 3600*24*10;   //设置静态文件10天过期

        if(file_exists($index_file)){   //已存在静态页面
            $file_ctime = filectime($index_file); //获取静态文件创建时间

            if($file_ctime + $express_time > time() ){   //没有过期
                echo file_get_contents($index_file);    //直接输出静态文件
                exit;
            }else{    //已经过期
                unlink($index_file);  //删除静态页面文件
                ob_start();    //打开缓冲区
                include ($index_module_file);    //在缓冲区引入静态页面模板文件
                $content = ob_get_contents();    //获取缓冲区内容(生成的静态文件页面内容)
                file_put_contents($index_file,$content);   //写入内容到对应的静态文件中
                ob_end_flush();    //关闭缓冲区并输出缓存内容
            }
        }else{    //不存在静态页面,重复已经过期操作(除了删除静态页面文件)
            ob_start();
            include ($index_module_file);
            $content = ob_get_contents();
            file_put_contents($index_file,$content);   
            ob_end_flush();  
        }

    }

Detailed steps: refer to the comments in the code, or the following instructions

Logical steps:

  1. First write a static page template file and store it in a static path (recommended) to generate a static page, that is, "static/html/module/index.html" in the example;
  2. The static page file path generated by default is used to determine whether the cached static page exists and whether the creation time has expired and needs to be updated;
  3. Judge whether there is a static page, if it exists, do the next step (determination of expiration), if it does not exist, regenerate and output;
  4. Determine whether the static page has expired and needs to be updated. If it expires, it will be regenerated and output. If it is not expired, it will be output directly.

Buffer generation file steps:

  1. First open the buffer ob_start();
  2. After opening the buffer, import the template file "static/html/module/index.html" in the buffer;
  3. Obtain the buffer content ob_get_contens();
  4. Generate static files file_put_contents();
  5. Close the buffer and output the cache content ob_end_flush();

Guess you like

Origin blog.csdn.net/weixin_43452467/article/details/112553267