web页面静态化

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

    }

详细步骤:可参考代码中的注释,或以下说明

逻辑步骤:

  1. 先写一个静态页面模板文件,并存放在静态路径下(建议),用于生成静态页面,即例子中的"static/html/module/index.html";
  2. 预设生成的静态页面文件路径,用于判断缓存静态页面是否存在,创建时间是否过期需要更新;
  3. 判断是否存在静态页面,存在则做下一步判断(过期判断),不存在则重新生成然后输出;
  4. 判断静态页面是否已经过期需要更新,过期则重新生成然后输出,没过期则直接输出

缓冲区生成文件步骤:

  1. 先打开缓冲区 ob_start() ;
  2. 打开缓冲区后,在缓冲区引入模板文件"static/html/module/index.html";
  3. 获取缓冲区内容 ob_get_contens() ;
  4. 生成静态文件 file_put_contents() ;
  5. 关闭缓冲区并输出缓存内容 ob_end_flush() ;

猜你喜欢

转载自blog.csdn.net/weixin_43452467/article/details/112553267