PHP文件缓存函数
转载
发一个自己写的PHP文件缓存函数
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 |
|
/**
| +----------------------------------------------------------
| * 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);
| } |
|
本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。