php文件缓存类用法实例分析

yipeiwu_com6年前PHP代码库

本文实例讲述了php文件缓存类用法。分享给大家供大家参考。具体如下:

<?php
/**
 * 简单的文件缓存类
 *
 */
class XZCache{
 // default cache time one hour
 var $cache_time = 3600;
 // default cache dir
 var $cache_dir = './cache';
 public function __construct($cache_dir=null, $cache_time=null){
  $this->cache_dir = isset($cache_dir) ? $cache_dir : $this->cache_dir;
  $this->cache_time = isset($cache_time) ? $cache_time : $this->cache_time;
 }
 public function saveCache ($key, $value){
  if (is_dir($this->cache_dir)){
   $cache_file = $this->cache_dir . '/xzcache_' . md5($key);
   $timedif = @(time() - filemtime($cache_file));
   if ($timedif >= $this->cache_time) {
    // cached file is too old, create new
    $serialized = serialize($value);
    if ($f = @fopen($cache_file, 'w')) {
     fwrite ($f, $serialized, strlen($serialized));
     fclose($f);
    }
   }
   $result = 1;
  }else{
   echo "Error:dir is not exist.";
   $result = 0;
  }
  return $result;
 }
 /**
  * @return array 
  *   0 no cache
  *    1 cached
  *    2 overdue
  */
 public function getCache ($key) {
  $cache_file = $this->cache_dir . '/xzcache_' . md5($key);
  if (is_dir($this->cache_dir) && is_file($cache_file)) {
   $timedif = @(time() - filemtime($cache_file));
   if ($timedif >= $this->cache_time) {
    $result['cached'] = 2;
   }else{
    // cached file is fresh enough, return cached array
    $result['value'] = unserialize(file_get_contents($cache_file));
    $result['cached'] = 1;
   }
  }else {
   echo "Error:no cache";
   $result['cached'] = 0;
  }
  return $result;
 }
} //end of class

用法示例如下:

$cache = new XZCache();
$key = 'global';
$value = $GLOBALS;
$cache->saveCache($key, $value);
$result = $cache->getCache($key);
var_dump($result);

希望本文所述对大家的php程序设计有所帮助。

相关文章

PHP实现UTF-8文件BOM自动检测与移除实例

本文实例讲述了PHP实现UTF-8文件BOM自动检测与移除的方法。分享给大家供大家参考。具体实现方法如下: BOM信息是文件开头的一串隐藏的字符,用于让某些编辑器识别这是个UTF-8编码...

神盾加密解密教程(一)PHP变量可用字符

先来说说php变量的命名规则,百度下一抓一大把:(1) PHP的变量名区分大小写;(2) 变量名必须以美元符号$开始;(3) 变量名开头可以以下划线开始;(4) 变量名不能以数字字符开头...

漂亮的thinkphp 跳转页封装示例

漂亮的thinkphp 跳转页封装示例

项目是要一点点按优先级进行优化的,现在到优化thinkphp的跳转页了。<?php  if(C('LAYOUT_ON')) {  &...

PHP无敌近乎加密方式!

因为本人对sql注入比较喜欢 前前后后 检测过不少网站 aspphpjsp 发现基本都是用md5加密算法 都说 MD5 不可逆 无法破 对 MD5是无法逆 可是可以暴力破 只需要把常用的...

php session的锁和并发

本文分享PHP的session在使用过程中的锁和并发的问题,与之相关的现象有请求阻塞、session数据丢失、session数据读不到。 我登录不了了 某天,我准备登录我们一个后台系统,...