欢迎访问WDPHP素材源码!今天是2024年05月01日 星期三,熬夜对身体不好,早点休息吧!
您好,游客 [ 马上登录 | 注册帐号 | 微信登录 | QQ登录]
当前位置:首页 > 教程 > PHP教程 > 

PHP 缓存读写方法,支持数组
栏目分类:PHP教程    发布日期:2023-03-31    浏览次数:557次     收藏

以下是一个简单的 PHP 缓存读写方法,支持数组:

function cache($key, $value = null, $ttl = 60) {
    // 设置缓存文件路径和名称
    $cache_file = '/path/to/cache/' . md5($key) . '.cache';

    // 如果传入了 $value,则将 $value 写入缓存文件
    if (!is_null($value)) {
        $data = serialize($value);
        file_put_contents($cache_file, $data);
        return;
    }

    // 如果缓存文件不存在或已过期,则返回 null
    if (!file_exists($cache_file) || (filemtime($cache_file) + $ttl < time())) {
        return null;
    }

    // 从缓存文件中读取数据并反序列化为 PHP 数组
    $data = file_get_contents($cache_file);
    return unserialize($data);
}

使用方法如下:

// 将数据写入缓存,有效期为 3600 秒(1 小时)
$data = array('foo' => 'bar', 'baz' => 'qux');
cache('my_cache_key', $data, 3600);

// 从缓存中读取数据
$data = cache('my_cache_key');
if ($data === null) {
    // 缓存未命中,需要重新生成数据
    $data = generate_data();
    cache('my_cache_key', $data, 3600);
}

// 对缓存中的数据进行修改
$data['foo'] = 'hello';
cache('my_cache_key', $data, 3600);

声明:本文为原创文章,如需转载,请注明来源 WDPHP.COM 并保留原文链接:http://www.wdphp.com/detail/1998.html

相关热词:

源码 模板 特效 素材 资源 教程 站长