php中文件缓存实现程序代码
文件缓存就是指把缓存生成一个文件,这个文件可以是php,txt等等文件,当我下载访问时就来判断访问上次生成时间,如果超过了我们指定的时间再重新生成一次,否则就直接调用缓存文件,这样就可以减少了对mysql数据库的查询了。
文件缓存原理
1.把需要缓存的数据通过serialize函数序列化后直接保存到文件。在需要使用缓存数据的时候,通过反序列化读入文件内容并复制给需要的变量,然后使用。不经常改动的数据可以写入缓存文件。
文件缓存实例
index.php
<?php
define('CACHE_ROOT', './');
include_once ('./cache.func.php');
$file = 'qzp';
$cacheFile = getCacheFileByID($file, 'info/');
print_R(readCache($cacheFile));
$info = array(
'username' => 'qzp',
'area_name' => 'admin',
'mp_name' => '1234',
'gh_name' => '5678'
);
writeCache($cacheFile, $info);
?>cache.func.php文件
<?php
function arrayeval($array, $level = 0) {
$space = '';
for ($i = 0; $i <= $level; $i++) {
$space.= "t";
}
$evaluate = "Arrayn$space(n";
$comma = $space;
foreach ($array as $key => $val) {
$key = is_string($key) ? '''.addcslashes($key, ''') . ''' : $key;
$val = !is_array($val) && (!preg_match("/^-?[1-9]d*$/", $val) || strlen($val) > 12) ? ''' . addcslashes($val, ''').''' : $val;
if (is_array($val)) {
$evaluate.= "$comma$key => " . arrayeval($val, $level + 1);
} else {
$evaluate.= "$comma$key => $val";
}
$comma = ",n$space";
}
$evaluate.= "n$space)";
return $evaluate;
}
function getCacheFileByID($id, $pre = 'info/', $md5 = true) {
if ($md5) {
$md5id = md5($id);
return CACHE_ROOT . '/' . $pre . substr($md5id, 0, 2) . '/' . substr($md5id, 2, 2) . '/' . $id;
} else {
return CACHE_ROOT . '/' . $pre . $id;
}
}
function readCache($filename, $time = 0) {
if ($datas = @file_get_contents($filename)) {
$datas = unserialize($datas);
if ($time < 1 || (time() - $datas['time'] < $time)) {
return $datas['data'];
}
}
return false;
}
function writeCache($filename, $data) {
makeDir(dirname($filename));
if ($handle = fopen($filename, 'w+')) {
$datas = array(
'data' => $data,
'time' => time()
);
flock($handle, LOCK_EX);
$rs = fputs($handle, serialize($datas));
flock($handle, LOCK_UN);
fclose($handle);
if ($rs !== false) {
return true;
}
}
return false;
}
function makeDir($path) {
if (!file_exists($path)) {
makeDir(dirname($path));
if (!mkdir($path, 0777)) die('无法创建文件夹' . $path);
}
}
?>把要缓存的文件序列化下存放起来,当使用的时候反序列化回来使用。
使用对PHP模板数据进行缓存的工具smarty。smarty将HTML文件缓存成一个静态的HTML页,需要缓存的模板文件可以使用smarty。
例:
<?php
//包含Smarty类库
require ('libs/Smarty.class.php');
//创建Smarty类的对象
$smarty = new Smarty;
//启用缓存
$smarty->caching = true;
//指定缓存文件保存的目录
$smarty->cache_dir = "./cache/";
//也会把输出保存
$smarty->display('index.tpl')
?>教程链接:http://www.phprm.com/frame/php1005336.html
随意转载~但请保留教程地址★