首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP数据缓存功能

PHP数据缓存功能
EN

Stack Overflow用户
提问于 2019-04-16 10:08:47
回答 2查看 333关注 0票数 0

希望在PHP中缓存数据集。我想知道PHP中是否已经有了缓存函数,没有任何扩展/模块?我无法作为管理员访问我的服务器:-(

一些简单的事情,如:

代码语言:javascript
复制
 saveString('Foo,Bar','Keyname',60);
 getString('Keyname')
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-04-16 11:26:29

好的,我找到了一个字符串缓存函数的解决方案。

代码语言:javascript
复制
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));


}
票数 0
EN

Stack Overflow用户

发布于 2019-04-16 11:15:22

示例(简化)。

代码语言:javascript
复制
// 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脚本具有写访问权限。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55705660

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档