PHP静态文件生成类实现与缓存策略
本实例详细解析了PHP静态文件生成的具体实现方案,旨在为开发者提供可参考的代码范例。
核心实现逻辑如下所示: 复制代码 代码如下:defined('phpjb51') or die(header("http/1.1 403 not forbidden")); class include_createstatic { private $htmlpath = ''; private $path = ''; public $monthpath = ''; private $listpath = ''; private $content = ''; private $filename = ''; private $extname = '.html'; public function createhtml($type,$desname,$content) { $this->htmlpath = getappinf('htmlpath'); if (!file_exists($this->htmlpath)) { @mkdir($this->htmlpath); } $this->path = $this->htmlpath.$this->monthpath.'/'; if (!file_exists($this->path)) { @mkdir($this->path); } $this->listpath = $this->htmlpath.'list/'; if (!file_exists($this->listpath)) { @mkdir($this->listpath); } switch ($type) { case 'index': $this->filename = $desname; break; case 'list': $this->filename = $this->listpath.$desname; break; case 'view': $this->filename = $this->path.$desname; break; } $this->filename .= $this->extname; $this->content = $content; } public function write() { $fp=fopen($this->filename,'wb'); if (!is_writable($this->filename)) { return false; } if (!fwrite($fp,$this->content)) { return false; } fclose($fp); return $this->filename; } } //方法二 if(file_exists("./index.htm"))//检查静态index.htm文件是否存在 { $time=time(); //若文件修改时间与当前时间差值小于设定阈值,则直接指向htm文件,否则触发重新生成 if(time-filemtime("./index.htm")< 600) { header("location:classhtml/main.htm"); } } //在脚本起始处启用输出缓冲 ob_start(); //此处为动态页面内容主体 //在末尾获取缓冲内容并清空缓冲区 $temp=ob_get_contents(); ob_end_clean(); //将内容写入文件 $fp=fopen("./index.htm",'w'); fwrite($fp,$temp) or die('写文件错误'); //echo"生成html完成!";
上述代码示例希望能协助读者更好地掌握PHP程序中的静态化设计与文件操作技巧。