以文件形式缓存php变量的方法


Posted in PHP onJune 26, 2015

本文实例讲述了以文件形式缓存php变量的方法。分享给大家供大家参考。具体实现方法如下:

<?php
/*
$cache_set = array(
//缓存路径 , 最后要加"/"
'cacheRoot'=>'./cache/',
//缓存时间
'cacheTime'=>20,
//cache type
'cacheType'=>1,
//扩展名
'cacheExe'=>'.php'
);
$cache = new Cache($cache_set);
$a=array('1','2');
$a="aaa";
$b='';
if($cache->cache_is("d")){
 $c=$cache->cache_read("d");
 echo "c";
 print_r($c);
}else {
$b=$cache->cache_data('d',$a);
}
print_r($b);
//$cache->clear("a");
//echo $cache->cache_read("./cache/d.php");
//echo $d;
*/
/**
 * 数据缓存类 v1.0
 * @author shooke
 * 2009-11-13 16:02:26
 * 用于缓存数据,如变量,但不能缓存页面
 */
class Cache{
 //配置
 public $config = array(
 //缓存路径
 'cacheRoot'=>'./cache/',
 //缓存时间
 'cacheTime'=>1,
 //cache 类型 1串化数据 2变量
 'cacheType'=>2,
 //扩展名
 'cacheExe'=>'.php'
 //转换中间变量
 );
 public $return_name=array();
 function __construct($cache_set = array())
 {
  if(!empty($cache_set)) $this->config=array_merge($this->config,$cache_set);
  $this->config['ClassName'] = __CLASS__;
 }
 public function clear($filename=''){
  if (file_exists($this->cache_file($filename))) {
   @unlink($this->cache_file($filename));
  }elseif (empty($filename)){
   $this->clear_dir($this->config['cacheRoot']);
  }else{
   $this->clear_dir($this->config['cacheRoot'].$filename);
   echo $this->config['cacheRoot'].$filename;
  }
 }
 //循环删除路径
 private function clear_dir($dir,$to = false)
 {
  if ($list = glob($dir.'/*'))
  {
   foreach ($list as $file)
   {
    is_dir($file) ? $this->clear_dir($file) : unlink($file);
   }
  }
  if ($to === false) rmdir($dir);
 }
 //写入缓存
 private function cache_write($filename, $writetext, $openmod='w'){
  if (!file_exists($filename)) {
   @$this->makeDir( dirname($filename ));
  }
  if(@$fp = fopen($filename, $openmod)) {
   flock($fp, 2);
   fwrite($fp, $writetext);
   fclose($fp);
   return true;
  } else {
   echo "File: $filename write error.";
   return false;
  }
 }
 //缓存有效期 有效返回 true
 public function cache_is($fileName){
  $fileName=$this->cache_file($fileName);
  if( file_exists( $fileName ) ) {
   //如果缓存时间为负数则永不过期
   if ($this->config['cacheTime'] < 0) {
    return true;
   }
   //如果缓存时间为0则一直过期
   if ($this->config['cacheTime'] == 0) {
    return false;
   }
   //获取缓存文件的建立时间
   $ctime = intval(filemtime( $fileName ));
   //比较是否大于缓存时间,是则过期 否则不过期
   if (time() - $ctime > $this->config['cacheTime']) {
    return false;
   }else {
    return true;
   }
   //文件不存在视为过期失效
  }else {
   return false;
  }
 }
 public function cache_data($name,$data){
  $varname=$name;
  $name = $this->cache_file($name);
  //config['cacheTime']==0也就是不启用缓存是直接返回数据
  if ($this->config['cacheTime'] <> 0) {
   if($this->config['cacheType']==1){
    $write_data = "<?php exit;?>".serialize($data);
    //return $data;
   }else {
    $write_data = "<?php\\r\\n\\$var= ";
    $write_data .= var_export($data,true);
    $write_data .=";\\r\\n?>";
   }
   $this->cache_write($name,$write_data);
  }
  return $data;
 }
 //缓存文件名
 private function cache_file($filename){
  return $this->config['cacheRoot'].$filename.$this->config['cacheExe'];
 }
 //读取文件
 public function cache_read($file){
  $file=$this->cache_file($file);
  if (!file_exists($file)) {
   return '';
  }
  if($this->config['cacheType']==1){
   if (function_exists('file_get_contents')){
    $cache_Content= file_get_contents($file);
   }else{
    $fopen = fopen($file,'r');
    $cache_Content = '';
    do {
     $data = fread($fopen,filesize($file));
     if (strlen($data)===0) break;
     $cache_Content .= $data;
    }while(1);
    fclose($fopen);
   }
   $cache_Content = substr($cache_Content,13);/* 去除<?php exit;?> */
   $cache_Content = unserialize($cache_Content);
   return $cache_Content;
  }else{
   include_once($file);
   return $var;
  }
 }
 //循环创建目录
 private function makeDir( $dir, $mode = 0777 ) {
  if( ! $dir ) return 0;
  $dir = str_replace( "\\\\", "/", $dir );
  $mdir = "";
  foreach( explode( "/", $dir ) as $val ) {
   $mdir .= $val."/";
   if( $val == ".." || $val == "." || trim( $val ) == "" ) continue;
   if( ! file_exists( $mdir ) ) {
    if(!@mkdir( $mdir, $mode )){
     return false;
    }
   }
  }
  return true;
 }
}
?>

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

PHP 相关文章推荐
随机头像PHP版
Oct 09 PHP
用PHP制作静态网站的模板框架(一)
Oct 09 PHP
php面向对象全攻略 (四)构造方法与析构方法
Sep 30 PHP
解析数组非数字键名引号的必要性
Aug 09 PHP
php构造函数实例讲解
Nov 13 PHP
检查用户名是否已在mysql中存在的php写法
Jan 20 PHP
php导出csv格式数据并将数字转换成文本的思路以及代码分享
Jun 05 PHP
php中异常处理方法小结
Jan 09 PHP
微信公众号支付之坑:调用支付jsapi缺少参数 timeStamp等错误解决方法
Jan 12 PHP
PHP递归实现层级树状展开
Apr 01 PHP
PHP getDocNamespaces()函数讲解
Feb 03 PHP
PHP使用ajax的post方式下载excel文件简单示例
Aug 06 PHP
PHP批量去除BOM头代码分享
Jun 26 #PHP
PHP多态代码实例
Jun 26 #PHP
PHP微信开发之二维码生成类
Jun 26 #PHP
Thinkphp关闭缓存的方法
Jun 26 #PHP
php获取、检查类名、函数名、方法名的函数方法
Jun 25 #PHP
php header函数的常用http头设置
Jun 25 #PHP
PHP里的单例类写法实例
Jun 25 #PHP
You might like
PHP实现微信公众平台音乐点播
2014/03/20 PHP
Yii2 GridView实现列表页直接修改数据的方法
2016/05/16 PHP
详解PHP防止直接访问.php 文件的实现方法
2017/07/28 PHP
Javascript里使用Dom操作Xml
2007/01/22 Javascript
PNG背景在不同浏览器下的应用
2009/06/22 Javascript
javascript操作JSON的要领总结
2012/12/09 Javascript
js父窗口关闭时子窗口随之关闭完美解决方案
2014/04/29 Javascript
jQuery.Callbacks()回调函数队列用法详解
2016/06/14 Javascript
jQuery实现div横向拖拽排序的简单实例
2016/07/13 Javascript
浅谈MVC+EF easyui dataGrid 动态加载分页表格
2016/11/10 Javascript
vue component组件使用方法详解
2017/07/14 Javascript
AngularJS基于MVC的复杂操作实例讲解
2017/12/31 Javascript
vue发送ajax请求详解
2018/10/09 Javascript
vue移动端使用canvas签名的实现
2020/01/15 Javascript
JavaScript直接调用函数与call调用的区别实例分析
2020/05/22 Javascript
从Node.js事件触发器到Vue自定义事件的深入讲解
2020/06/26 Javascript
Antd表格滚动 宽度自适应 不换行的实例
2020/10/27 Javascript
微信小程序实现下拉加载更多商品
2020/12/29 Javascript
[01:01:52]DOTA2-DPC中国联赛正赛 iG vs LBZS BO3 第一场 3月4日
2021/03/11 DOTA
Python使用Socket(Https)Post登录百度的实现代码
2012/05/18 Python
浅析Python中的多进程与多线程的使用
2015/04/07 Python
Python发送以整个文件夹的内容为附件的邮件的教程
2015/05/06 Python
pytorch + visdom CNN处理自建图片数据集的方法
2018/06/04 Python
有关Python的22个编程技巧
2018/08/29 Python
Python 窗体(tkinter)按钮 位置实例
2019/06/13 Python
python实现一个函数版的名片管理系统过程解析
2019/08/27 Python
基于python实现百度语音识别和图灵对话
2020/11/02 Python
Django集成MongoDB实现过程解析
2020/12/01 Python
使用 css3 transform 属性来变换背景图的方法
2019/05/07 HTML / CSS
css3 盒模型以及box-sizing属性全面了解
2016/09/20 HTML / CSS
法国滑雪假期的专家:Ski Planet
2019/11/02 全球购物
美国在线艺术商店:HandmadePiece
2020/11/06 全球购物
市场开发与营销专业求职信
2013/12/31 职场文书
《学会合作》教学反思
2014/04/12 职场文书
教师节活动总结
2014/08/29 职场文书
边城读书笔记
2015/06/29 职场文书