PHP自定义文件缓存实现

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

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

php 复制代码
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、文件缓存写法二,一个文件缓存所有数据,缺点可能文件太大读写变慢

php 复制代码
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);
相关推荐
六点_dn2 小时前
RabbitMQ学习笔记-部署和使用
笔记·学习·rabbitmq
凌虚2 小时前
面向 MySQL 用户的 PostgreSQL 快速上手指南
数据库·后端·架构
名字还没想好☜2 小时前
Next.js ‘use client‘ 到底加在哪:Server/Client Components 边界与常见报错
开发语言·前端·javascript·react·next.js
2501_926978333 小时前
以说明书 DNA 为模板——完整 AGI 的结构图景
前端·人工智能·经验分享·笔记·ai写作
IT_陈寒3 小时前
Vite静态资源引用这个坑我踩得有点疼
前端·人工智能·后端
天天爱吃肉82183 小时前
商用车多体动力学实战笔记|第6篇:动力传动系统(发动机、变速箱、分动器、TCS、LSD限滑差速)
大数据·人工智能·笔记·python·嵌入式硬件·汽车
初级代码游戏3 小时前
iOS开发 Swift 速记1:变量和基本数据类型
开发语言·ios·swift
前端开发张小七3 小时前
Java 学习笔记 · 第一课:基础语法与核心概念
java·后端
海盗12344 小时前
微软技术周报 ——2026-08-03
后端·python·microsoft·c#·.netcore
沙湖遇雨4 小时前
6. Pipeline 的生命周期
后端