PHP實(shí)現(xiàn)自定義文件緩存的方法
文件緩存:可以將PHP腳本的執(zhí)行結(jié)果緩存到文件中。當(dāng)一個PHP腳本被請求時,先查看是否存在緩存文件,如果存在且未過期,則直接讀取緩存文件內(nèi)容返回給客戶端,而無需執(zhí)行腳本
1、文件緩存寫法一,每個文件緩存一個數(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、文件緩存寫法二,一個文件緩存所有數(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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
PHP中isset與array_key_exists的區(qū)別實(shí)例分析
這篇文章主要介紹了PHP中isset與array_key_exists的區(qū)別,較為詳細(xì)的分析了isset與array_key_exists使用中的區(qū)別,并實(shí)例分析其具體用法,需要的朋友可以參考下2015-06-06
PHP如何實(shí)現(xiàn)Unicode和Utf-8編碼相互轉(zhuǎn)換
本文介紹了通過PHP實(shí)現(xiàn)一個函數(shù)可以對字符串進(jìn)行Unicode的編碼和解碼,需要的朋友可以參考下2015-07-07
PHP實(shí)現(xiàn)統(tǒng)計(jì)代碼行數(shù)小工具
這篇文章主要為大家詳細(xì)介紹了PHP實(shí)現(xiàn)統(tǒng)計(jì)代碼行數(shù)小工具,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-09-09
PHP關(guān)于foreach復(fù)制知識點(diǎn)總結(jié)
在本篇文章里小編給大家分享了關(guān)于PHP關(guān)于foreach復(fù)制知識點(diǎn)總結(jié),有興趣的朋友們學(xué)習(xí)下。2019-01-01
php運(yùn)行提示:Fatal error Allowed memory size內(nèi)存不足的解決方法
這篇文章主要介紹了php運(yùn)行提示:Fatal error Allowed memory size內(nèi)存不足的解決方法,分別針對有服務(wù)器管理權(quán)限和沒有服務(wù)器管理權(quán)限的情況分析解決方法,是非常實(shí)用的技巧,需要的朋友可以參考下2014-12-12

