/**
|
+----------------------------------------------------------
|
* PHP文件缓存函数
|
* @author LiuYuanjun <http://www.liuyuanjun.com>
|
+----------------------------------------------------------
|
* @param string $key 缓存KEY 设为null则清空所有缓存
|
* @param mixed $data 缓存内容 设为null则删除KEY为$key的缓存
|
* @param int $time 缓存时间 秒数,如果大于当前时间戳则按照时间戳来处理,为0则永不过期
|
+----------------------------------------------------------
|
* @return mixed
|
+----------------------------------------------------------
|
*/
|
function file_cache($key, $data='', $time=0) {
|
$cacheDir = ROOTPATH . 'Cache' . DS; //这里设置缓存目录
|
$timestamp = time();
|
if ($key === null) { //clear all
|
$dirFiles = scandir($cacheDir);
|
foreach ($dirFiles as $dirFile) {
|
if ($dirFile != '.' && $dirFile != '..')
|
@unlink($cacheDir . $dirFile);
|
}
|
}
|
$cachePath = $cacheDir . '~' . $key . '.php';
|
if ($data === '') { //get cache
|
if (!is_file($cachePath))
|
return false;
|
$cacheData = @require $cachePath;
|
if ($cacheData[0] > 0 && $cacheData[0] < $timestamp) {
|
@unlink($cachePath);
|
return false;
|
} else {
|
return @unserialize($cacheData[1]);
|
}
|
}
|
if ($data === null)
|
@unlink($cachePath); //delete cache
|
$time = intval($time);
|
$deadline = $time == 0 ? 0 : ($time>$timestamp?$time:($timestamp+$time));
|
$storeData = '<?php return array(' . $deadline . ',\'' . serialize($data) . '\'); ?>';
|
@file_put_contents($cachePath, $storeData);
|
} |