PHP自定义文件缓存实现-CSDN博客

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

文件缓存可以将PHP脚本的执行结果缓存到文件中。当一个PHP脚本被请求时先查看是否存在缓存文件如果存在且未过期则直接读取缓存文件内容返回给客户端而无需执行脚本

1、文件缓存写法一每个文件缓存一个数据缺点文件可能太多 

function getFileCache($key, $value = null, $expiry = 3600) {
    $cacheDir = "D:\\phpstudy_pro\\WWW\\cache\\";
    $cacheFile = $cacheDir . md5($key) . '.txt';

    if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < $expiry)) {
        return file_get_contents($cacheFile);
    }

    if ($value !== null) {
        // 将$value参数的值保存到缓存文件中
        file_put_contents($cacheFile, $value);
        return $value;
    }

    // 保存数据到缓存文件中
    file_put_contents($cacheFile, $value);

    return $value;
}

// 缓存具体的值
$cacheValue = 'example_value';
 getFileCache('example_key', $cacheValue);

// 使用示例
$data = getFileCache('example_key');
echo $data;

 2、文件缓存写法二一个文件缓存所有数据缺点可能文件太大读写变慢

function getFileCache($key, $value = null, $expiry = 3600) {
    $cacheDir = "D:\\phpstudy_pro\\WWW\\cache\\";
    $cacheFile = $cacheDir .  'cache.txt';
    $file=false;
    if(file_exists($cacheFile)){
        $file= file_get_contents($cacheFile);
    }
    if($file){
         $data=unserialize($file);
    }else{
        $data=[];
    }
    if($value){
        $data[$key]=["data"=>$value,'expiry'=>time()+$expiry];

        file_put_contents($cacheFile, serialize($data));
        return true;
    }else{
        if(isset($data[$key])&&$data[$key]['expiry']>time()){

             return  $data[$key]['data'];
        }
        return null;
    }
}
// 缓存具体的值
$cacheValue = 'example_value';
getFileCache('example_key', $cacheValue);
$cacheValue = 'example_value2';
getFileCache('example_key2', $cacheValue);
// 使用示例
$data = getFileCache('example_key');
var_dump($data);
$data2 = getFileCache('example_key2');
var_dump($data2);

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: php

“PHP自定义文件缓存实现-CSDN博客” 的相关文章