希望在PHP中缓存数据集。我想知道PHP中是否已经有了缓存函数,没有任何扩展/模块?我无法作为管理员访问我的服务器:-(
一些简单的事情,如:
saveString('Foo,Bar','Keyname',60);
getString('Keyname')发布于 2019-04-16 11:26:29
好的,我找到了一个字符串缓存函数的解决方案。
define('cachepath','cache/');
$q=('StringKeyExists');
if(isString($q,30)){
getString($q);
}else{
$c=('Content to save');
saveString($q,$c);
}
function isString($key,$time=60){
$exp = 60 * $time; // 3600s = 1 hour
$key=uniq($key);
$file=@cachepath.$key;
if(file_exists($file) &&( filectime($file) > time() - $exp)){
return 1;
} else{
return false;
}
}
function getString($key){
$key=uniq($key);
$file=@cachepath.$key;
return json_decode(file_get_contents($file),1);
}
function uniq($str='',$nr=6){
return substr(md5($str),0,$nr);
}
function saveString($key,$str=''){
$key=uniq($key);
$file=@cachepath.$key;
return file_put_contents($file, json_encode($str));
}发布于 2019-04-16 11:15:22
示例(简化)。
// write to cache file
$data = [
'foo' => 'bar',
];
file_put_contents('cache.json', json_encode($data));
// read from cache file
$data = json_decode(file_get_contents('cache.json'), true);备注:确保缓存文件存在,并且php脚本具有写访问权限。
https://stackoverflow.com/questions/55705660
复制相似问题