欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PHP實(shí)現(xiàn)自定義文件緩存的方法

 更新時(shí)間:2023年10月31日 10:15:48   作者:PHP隔壁老王鄰居  
這篇文章主要介紹了PHP是如何實(shí)現(xiàn)自定義文件緩存的方法的,文中通過代碼示例給大家介紹了兩個(gè)方法,具有一定的參考價(jià)值,需要的朋友可以參考下

文件緩存:可以將PHP腳本的執(zhí)行結(jié)果緩存到文件中。當(dāng)一個(gè)PHP腳本被請(qǐng)求時(shí),先查看是否存在緩存文件,如果存在且未過期,則直接讀取緩存文件內(nèi)容返回給客戶端,而無(wú)需執(zhí)行腳本

1、文件緩存寫法一,每個(gè)文件緩存一個(gè)數(shù)據(jù),缺點(diǎn)文件可能太多 

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參數(shù)的值保存到緩存文件中
        file_put_contents($cacheFile, $value);
        return $value;
    }
 
    // 保存數(shù)據(jù)到緩存文件中
    file_put_contents($cacheFile, $value);
 
    return $value;
}
 
// 緩存具體的值
$cacheValue = 'example_value';
 getFileCache('example_key', $cacheValue);
 
// 使用示例
$data = getFileCache('example_key');
echo $data;

 2、文件緩存寫法二,一個(gè)文件緩存所有數(shù)據(jù),缺點(diǎn)可能文件太大讀寫變慢

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);

到此這篇關(guān)于PHP實(shí)現(xiàn)自定義文件緩存的方法的文章就介紹到這了,更多相關(guān)PHP自定義文件緩存內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論