PHP文件式缓存代码 2024-06-09 暂无评论 ```php dir_isvalid($dir . $day)) { $this->dir = $dir . $day; $this->olddir = $dir . $day1; $this->cachename = $cachename; $this->lifetime = $lifetime; $this->ext = '.php'; $this->cacheid = $this->getcacheid(); } } /** * 检查缓存是否有效 */ private function isvalid() { return file_exists($this->cacheid) && (time() - filemtime($this->cacheid) <= $this->lifetime); } /** * 写入缓存 */ public function write($mode = 0, $content = '') { switch ($mode) { case 0: $content = ob_get_contents(); break; } ob_end_flush(); try { file_put_contents($this->cacheid, $content); } catch (Exception $e) { $this->error('写入缓存失败!请检查目录权限!'); } } /** * 加载缓存 */ public function load() { if ($this->isvalid()) { require_once($this->cacheid); exit(); } else { ob_start(); if (date("H", time()) == "04") { $this->del(); } } } /** * 删除旧缓存 */ private function del() { try { $path = $this->olddir; if (is_dir($path)) { $this->removeDirectory($path); } } catch (Exception $e) { $this->error('清除缓存文件失败!请检查目录权限!'); } } /** * 递归删除目录及文件 */ private function removeDirectory($path) { $items = array_diff(scandir($path), ['.', '..']); foreach ($items as $item) { $itemPath = $path . $item; if (is_dir($itemPath)) { $this->removeDirectory($itemPath . '/'); @rmdir($itemPath); } else { unlink($itemPath); } } @rmdir($path); } /** * 清除缓存 */ public function clean() { try { unlink($this->cacheid); } catch (Exception $e) { $this->error('清除缓存文件失败!请检查目录权限!'); } } /** * 取得缓存文件路径 */ private function getcacheid() { return $this->dir . md5($_SERVER['HTTP_HOST'] . '/' . $this->cachename) . $this->ext; } /** * 检查目录是否存在或是否可创建 */ private function dir_isvalid($dir) { if (is_dir($dir)) return true; try { return mkdir($dir, 0777, true); } catch (Exception $e) { $this->error('所设定缓存目录不存在并且创建失败!请检查目录权限!'); return false; } } /** * 输出错误信息 */ private function error($str) { echo '' . $str . ''; } } ?> ``` # 使用示例: ```php clean(); echo "缓存已清理。"; } // 加载缓存(如果有效则输出缓存内容并退出) $cache->load(); // 如果缓存无效,生成新内容 echo ""; echo "当前时间:" . date("Y-m-d H:i:s") . ""; echo "这是一个动态生成的页面内容。"; echo ""; // 写入缓存 $cache->write(); ?> ``` PHP文件式缓存代码 https://www.byue.cc/index.php/archives/5/ 本文作者 八月 发布时间 2024-06-09 许可协议 CC BY-NC-SA 4.0 取消回复 发表新评论 提交评论