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

来源:互联网 发布:哪些淘宝店衣服好看 编辑:程序博客网 时间:2024/05/18 03:02
<?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'); //删除缓存
?>
原创粉丝点击