php缓存机制封装【序列化机制】

<?php
/**
 * 缓存写操作
 *  @param  string $file 文件名称【包含文件后缀】
 *  @param  array $array 待缓存的数据
 *  @param  string $path 缓存保存的地址,默认为空
 *  @return  int 返回写入数据的长度
 */
function  cacheWrite($file, $array, $path =  ''  )
{
     if (! is_array($array))  return false ;
    $array = serialize($array);  //序列化
    $cachefile = ($path ? $path : CACHE_PATH) . $file;
    $strlen = file_put_contents($cachefile, $array);
    @chmod($cachefile, 0777);  //设置权限
     return  $strlen;
}

/**
 * 缓存读操作
 *  @param  string $file 文件名称【包含文件后缀】
 *  @param  string $path 缓存保存的地址,默认为空
 *  @return  返回读取的数据
 */
function  cacheRead($file, $path =  ''  )
{
     if (! $path) $path = CACHE_PATH;
    $cachefile = $path . $file;
     return  unserialize(file_get_contents($cachefile));
}

/**
 * 缓存删除操作
 *  @param  string $file 文件名称【包含文件后缀】
 *  @param  string $path 缓存保存的地址,默认为空
 */
function  cacheDelete($file, $path =  ''  )
{
    $cachefile = ($path ? $path : CACHE_PATH) . $file;
     return  @unlink($cachefile);
}

/**
 * 测试操作
 * 采用序列化缓存数据,serialize,unserialize
 * 优势:速度快
 * 缺点:一点路径暴露,内容容易泄漏
 * 应用领域:缓存一些不安全的数据
 */
define( 'CACHE_PATH' ,  'd:/test/' );
cacheWrite( 'test.txt' ,  array ( '123123'  ,  'asdfasdf'  ));  //写入缓存
var_dump(cacheRead( 'test.txt' ));  //读取缓存
cacheDelete( 'test.txt' );  //删除缓存
?>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值