php 缓存工具类 实现网页缓存

php程序在抵抗大流量访问的时候动态网站往往都是难以招架,所以要引入缓存机制,一般情况下有两种类型缓存

一、文件缓存

二、数据查询结果缓存,使用内存来实现高速缓存

本例主要使用文件缓存。

主要原理使用缓存函数来存储网页显示结果,如果在规定时间里再次调用则可以加载缓存文件。

工具类代码:

// 文件缓存类
class Cache {
/**
* $dir : 缓存文件存放目录
* $lifetime : 缓存文件有效期,单位为秒
* $cacheid : 缓存文件路径,包含文件名
* $ext : 缓存文件扩展名(可以不用),这里使用是为了查看文件方便
*/
private $dir;
private $lifetime;
private $cacheid;
private $ext;
/**
* 析构函数,检查缓存目录是否有效,默认赋值
*/
function __construct($dir = '', $lifetime = 1800) {
if ($this->dir_isvalid ( $dir )) {
$this->dir = $dir;
$this->lifetime = $lifetime;
$this->ext = '.Php';
$this->cacheid = $this->getcacheid ();
}
}
/**
* 检查缓存是否有效
*/
private function isvalid() {
if (! file_exists ( $this->cacheid ))
return false;
if (! (@$mtime = filemtime ( $this->cacheid )))
return false;
if (mktime () - $mtime > $this->lifetime)
return false;
return true;
}
/**
* 写入缓存
* $mode == 0 , 以浏览器缓存的方式取得页面内容
* $mode == 1 , 以直接赋值(通过$content参数接收)的方式取得页面内容
* $mode == 2 , 以本地读取(fopen ile_get_contents)的方式取得页面内容(似乎这种方式没什么必要)
*/
public function write($mode = 0, $content = '') {
switch ($mode) {
case 0 :
$content = ob_get_contents ();
break;
default :
break;
}
ob_end_flush ();
try {
file_put_contents ( $this->cacheid, $content );
} catch ( Exception $e ) {
$this->error ( '写入缓存失败!请检查目录权限!' );
}
}
/**
* 加载缓存
* exit() 载入缓存后终止原页面程序的执行,缓存无效则运行原页面程序生成缓存
* ob_start() 开启浏览器缓存用于在页面结尾处取得页面内容
*/
public function load() {
if ($this->isvalid ()) {
// 以下两种方式,哪种方式好?????
require_once ($this->cacheid);
echo "<!--缓存-->";
// echo file_get_contents($this->cacheid);
exit ();
} else {
ob_start ();
}
}
/**
* 清除缓存
*/
public function clean() {
try {
unlink ( $this->cacheid );
} catch ( Exception $e ) {
$this->error ( '清除缓存文件失败!请检查目录权限!' );
}
}
/**
* 取得缓存文件路径
*/
private function getcacheid() {
return $this->dir . md5 ( $this->geturl () ) . $this->ext;
}
/**
* 检查目录是否存在或是否可创建
*/
private function dir_isvalid($dir) {
if (is_dir ( $dir ))
return true;
try {
mkdir ( $dir, 0777 );
} catch ( Exception $e ) {
$this->error ( '所设定缓存目录不存在并且创建失败!请检查目录权限!' );
return false;
}
return true;
}
/**
* 取得当前页面完整url
*/
private function geturl() {
$url = '';
if (isset ( $_SERVER ['REQUEST_URI'] )) {
$url = $_SERVER ['REQUEST_URI'];
} else {
$url = $_SERVER ['Php_SELF'];
$url .= empty ( $_SERVER ['QUERY_STRING'] ) ? '' : '?' . $_SERVER ['QUERY_STRING'];
}
return $url;
}
/**
* 输出错误信息
*/
private function error($str) {
echo '<div style="color:red;">' . $str . '</div>';
}
}

  

使用方法:

使用方法如下:

一部分代码放在要被缓存逻辑代码前面:

$cachedir = './Cache/'; // 设定缓存目录
$cache = new Cache ( $cachedir, 33 ); // 省略参数即采用缺省设置, $cache = new Cache($cachedir);
if (@$_GET ['cacheact'] != 'rewrite' || @$_GET ['clearCache'] == 'ok') // 此处为一技巧,通过xx.Php?cacheact=rewrite更新缓存,以此类推,还可以设定一些其它操作
$cache->load (); // 装载缓存,缓存有效则不执行以下页面代码
// 页面代码开始

  

一部分放在被缓存逻辑代码后面:

// 页面代码结束
$cache->write (); // 首次运行或缓存过期,生成缓存

  

原文地址:http://sijienet.com/bbs/?leibie=showinfo&id=50

php 缓存工具类 实现网页缓存的更多相关文章

  1. Cache【硬盘缓存工具类(包含内存缓存LruCache和磁盘缓存DiskLruCache)】

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 内存缓存LruCache和磁盘缓存DiskLruCache的封装类,主要用于图片缓存. 效果图 代码分析 内存缓存LruCache和 ...

  2. 分享基于MemoryCache(内存缓存)的缓存工具类,C# B/S 、C/S项目均可以使用!

    using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Caching; usi ...

  3. Go/Python/Erlang编程语言对比分析及示例 基于RabbitMQ.Client组件实现RabbitMQ可复用的 ConnectionPool(连接池) 封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil 分享基于MemoryCache(内存缓存)的缓存工具类,C# B/S 、C/S项目均可以使用!

    Go/Python/Erlang编程语言对比分析及示例   本文主要是介绍Go,从语言对比分析的角度切入.之所以选择与Python.Erlang对比,是因为做为高级语言,它们语言特性上有较大的相似性, ...

  4. redis缓存工具类

    import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis ...

  5. redis缓存工具类,提供序列化接口

    1.序列化工具类 package com.qicheshetuan.backend.util; import java.io.ByteArrayInputStream; import java.io. ...

  6. SpringBoot整合Redis、mybatis实战,封装RedisUtils工具类,redis缓存mybatis数据 附源码

    创建SpringBoot项目 在线创建方式 网址:https://start.spring.io/ 然后创建Controller.Mapper.Service包 SpringBoot整合Redis 引 ...

  7. CookieUtils-浏览器缓存工具类

    package cn.yonyong.myproject.commons.utils; import javax.servlet.http.Cookie; import javax.servlet.h ...

  8. 缓存工具类CacheHelper

    代码: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Syst ...

  9. 基于spring的redisTemplate的缓存工具类

    pom.xml文件添加 <!-- config redis data and client jar --><dependency> <groupId>org.spr ...

随机推荐

  1. Getting Started with xUnit.net (desktop)

    https://xunit.github.io/docs/getting-started-desktop.html In this article, we will demonstrate getti ...

  2. 网站建设中用JS判断时间并显示不同内容

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  3. mysql忘记root用户密码找回步骤

    修改或找回root密码步骤1.修改MySQL的登录设置: # vi /etc/my.cnf 在[mysqld]的段中加上一句:skip-grant-tables 保存并且退出vi. 2.重新启动mys ...

  4. 书写优雅的shell脚本(三) - shell中exec解析

    参考:<linux命令.编辑器与shell编程> <unix环境高级编程> exec和source都属于bash内部命令(builtins commands),在bash下输入 ...

  5. 书写优雅的shell脚本(插曲)- /proc

    1. /proc目录 Linux 内核提供了一种通过 /proc 文件系统,在运行时访问内核内部数据结构.改变内核设置的机制.proc文件系统是一个伪文件系统,它只存在内存当中,而不占用外存空间.它以 ...

  6. Java中gcRoot和引用类型

    看到一个老问题,Java是如何判定回收哪些对象的? 答:从gcRoot根搜索不可达,且标记清理一次之后仍没有被复活的对象,会被认定为垃圾对象进行清理.注意在Java中没有对象的作用域,只有对象的引用的 ...

  7. 【总结——HTTP协议】

    一.HTTP协议简介 什么是HTTP?全称是HyperText Transfer Protocal,即:超文本传输协议,从1990年开始就在WWW上广泛应用,是现今在WWW上应用最多的协议,目前版本是 ...

  8. poj1830开关问题——异或高斯消元

    题目:http://poj.org/problem?id=1830 根据题意,构造出n元方程组: a(1,1)x1 ^ a(1,2)x2 ^ a(1,3)x3 ... a(1,n)xn = st1 ^ ...

  9. Bootstrap-CL:下拉菜单

    ylbtech-Bootstrap-CL:下拉菜单 1.返回顶部 1. Bootstrap 下拉菜单(Dropdowns) 本章将重点介绍 Bootstrap 下拉菜单.下拉菜单是可切换的,是以列表格 ...

  10. ASP.NET Core:WebAppCoreAngular

    ylbtech-ASP.NET Core:WebAppCoreAngular 1.返回顶部 1. 2. 3. 4. 5. 6. 2.返回顶部   3.返回顶部   4.返回顶部   5.返回顶部   ...