PHP文件缓存

本文介绍了一个PHP实现的文件缓存类,详细阐述了如何使用该类进行数据的存储和读取。缓存数据经过序列化、压缩和base64编码,提供了存入时和取出时的处理方式。同时,类中包含了设置缓存路径、检查缓存存在、清除所有缓存和删除特定缓存等方法,适用于简单的文件缓存需求。
摘要由CSDN通过智能技术生成

文件缓存

使用:

先引入缓存类
存:FileCache::save('cache');
取:FileCache::load('cache');

注:
缓存文件数据被 序列化,压缩和进行base64编码,如不需要 将
(转base64编码 是为了入库需要)

base64_encode(gzcompress(serialize($data), 3))   改为  $data   (存入时处理)
$data = unserialize(gzuncompress(base64_decode($data)))    直接去掉   (取出时处理)

缓存类

注意设定自己的缓存文件地址:cache_dir
<?php
class FileCache
{
    const FILE_LIFE_KEY = 'FILE_LIFE_KEY';
    const CLEAR_ALL_KEY = 'CLEAR_ALL';
    public static $_instance = null;
    protected $_options = array(
        'cache_dir' => __DIR__.'/../../runtime/filecache/',
        'file_locking' => true,
        'file_name_prefix' => 'cache',
        'cache_file_umask' => 0777,
        'file_life' => 60*60*24
    );
   
    public static function &getInstance($options = array())
    {
        if (self::$_instance === null) {
            self::$_instance = new self($options);
        }
        return self::$_instance;
    }

    /**
     * 设置参数
     * @param array $options 缓存参数
     * @return void
     */
    public static function &setOptions($options = array())
    {
        return self::getInstance($options);
    }
   
    /**
     * 构造函数
     * @param array $options 缓存参数
     * @return void
     */
    private function __construct($options = array())
    {
        if ($this->_options['cache_dir'] !== null) {
            $dir = rtrim($this->_options['cache_dir'], '/') . '/';
            $this->_options['cache_dir'] = $dir;
     
            if (!is_dir($this->_options['cache_dir'])) {
                mkdir($this->_options['cache_dir'], 0777, true);
            }
            if (!is_writable($this->_options['cache_dir'])) {
                exit('file_cache: 路径 "'. $this->_options['cache_dir'] .'" 不可写');
            }
        } else {
            exit('file_cache: "options" cache_dir 不能为空 ');
        }
    }
  
    /**
     * 设置缓存路径
     * @param string $value
     * @return void
     */
    public static function setCacheDir($value)
    {
        $self = & self::getInstance();
        if (!is_dir($value)) {
            exit('file_cache: ' . $value.' 不是一个有效路径 ');
        }
        if (!is_writable($value)) {
            exit('file_cache: 路径 "'.$value.'" 不可写');
        }
        $value = rtrim($this->_options['cache_dir'], '/') . '/';
        $self->_options['cache_dir'] = $value;
    }
   
    /**
     * 存入缓存数据
     * @param array $data   放入缓存的数据
     * @param string $id   缓存id(又名缓存识别码)
     * @param cache_life   缓存时间
     * @return boolean True if no problem
     */
    public static function save($data, $id = null, $cache_life = null)
    {
        $self = & self::getInstance();
        if (!$id) {
            if ($self->_id) {
                $id = $self->_id;
            } else {
                exit('file_cache:save() id 不能为空!');
            }
        }
        $time = time();
        if ($cache_life) {
            $data[self::FILE_LIFE_KEY] = $time + $cache_life;
        } elseif ($cache_life != 0) {
            $data[self::FILE_LIFE_KEY] = $time + $self->_options['file_life'];
        }
        $file = $self->_file($id);
        $data = "<?php\n".
    " // mktime: ". $time. "\n".
    " return ".
    var_export(base64_encode(gzcompress(serialize($data), 3)), true).
    "\n?>"
    ;
        $res = $self->_filePutContents($file, $data);
        return $res;
    }
   
   
    /**
     * 得到缓存信息
     *
     * @param string $id 缓存id
     * @return string|array 缓存数据
     */
    public static function load($id)
    {
        $self = & self::getInstance();
        $time = time();
        //检测缓存是否存在
        if (!$self->test($id)) {
            // The cache is not hit !
            return false;
        }
    
        //全部清空识别文件
        $clearFile = $self->_file(self::CLEAR_ALL_KEY);
        $file = $self->_file($id);
        //判断缓存是否已被全部清除
        if (is_file($clearFile) && filemtime($clearFile) > filemtime($file)) {
            return false;
        }
        $data = $self->_fileGetContents($file);
        $data = unserialize(gzuncompress(base64_decode($data)));
        if (empty($data[self::FILE_LIFE_KEY]) || $time < $data[self::FILE_LIFE_KEY]) {
            unset($data[self::FILE_LIFE_KEY]);
            return $data;
        }
        return false;
    }
   
    /**
     * 写入缓存文件
     *
     * @param string $file 缓存路径
     * @param string $string 缓存信息
     * @return boolean true 成功
     */
    protected function _filePutContents($file, $string)
    {
        $self = & self::getInstance();
        $result = false;
        $f = @fopen($file, 'ab+');
        if ($f) {
            if ($self->_options['file_locking']) {
                @flock($f, LOCK_EX);
            }
            fseek($f, 0);
            ftruncate($f, 0);
            $tmp = @fwrite($f, $string);
            if (!($tmp === false)) {
                $result = true;
            }
            @fclose($f);
        }
        @chmod($file, $self->_options['cache_file_umask']);
        return $result;
    }
   
    /**
     * 格式化后的缓存文件路径
     *
     * @param string $id 缓存id
     * @return string 缓存文件名(包括路径)
     */
    protected function _file($id)
    {
        $self = & self::getInstance();
        $fileName = $self->_idToFileName($id);
        return $self->_options['cache_dir'] . $fileName;
    }
   
    /**
     * 格式化后的缓存文件名字
     *
     * @param string $id 缓存id
     * @return string 缓存文件名
     */
    protected function _idToFileName($id)
    {
        $self = & self::getInstance();
        $self->_id = $id;
        $prefix = $self->_options['file_name_prefix'];
        $result = $prefix . '---' . $id;
        return $result;
    }
   
    /**
     * 判断缓存是否存在
     *
     * @param string $id Cache id
     * @return boolean True 缓存存在 False 缓存不存在
     */
    public static function test($id)
    {
        $self = & self::getInstance();
        $file = $self->_file($id);
        if (!is_file($file)) {
            return false;
        }
        return true;
    }
   
    /**
     * 得到缓存信息
     *
     * @param string $file 缓存路径
     * @return string 缓存内容
     */
    protected function _fileGetContents($file)
    {
        if (!is_file($file)) {
            return false;
        }
        return include $file;
    }
   
    /**
     * 清除所有缓存
     *
     * @return void
     */
    public static function clear()
    {
        $self = & self::getInstance();
        $cachedir = $self->_options['cache_dir'];
        $dirfile = scandir($cachedir);
        foreach ($dirfile as $k) {
            if ($k!='.' && $k!='..') {
                unlink($cachedir. $k);
            }
        }
    }
    /**
     * 清除一条缓存
     *
     * @param string cache id
     * @return void
     */
    public static function del($id)
    {
        $self = & self::getInstance();
        if (!$self->test($id)) {
            // 该缓存不存在
            return false;
        }
        $file = $self->_file($id);
        return unlink($file);
    }

计算字节大小

function getFilesize($num){
   $p = 0;
   $format='bytes';
   if($num>0 && $num<1024){
     $p = 0;
     return number_format($num).' '.$format;
   }
   if($num>=1024 && $num<pow(1024, 2)){
     $p = 1;
     $format = 'KB';
  }
  if ($num>=pow(1024, 2) && $num<pow(1024, 3)) {
    $p = 2;
    $format = 'MB';
  }
  if ($num>=pow(1024, 3) && $num<pow(1024, 4)) {
    $p = 3;
    $format = 'GB';
  }
  if ($num>=pow(1024, 4) && $num<pow(1024, 5)) {
    $p = 3;
    $format = 'TB';
  }
  $num /= pow(1024, $p);
  return number_format($num, 3).' '.$format;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值