PHP實(shí)現(xiàn)自定義文件緩存的方法
文件緩存:可以將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)文章
PHP實(shí)現(xiàn)手機(jī)號(hào)碼中間四位用星號(hào)(*)隱藏的自定義函數(shù)分享
這篇文章主要介紹了PHP實(shí)現(xiàn)手機(jī)號(hào)碼中間四位用星號(hào)(*)隱藏的自定義函數(shù)分享,這是一個(gè)比較常用的功能,需要的朋友可以參考下2014-09-09PHP取得一個(gè)類的屬性和方法的實(shí)現(xiàn)代碼
PHP取得一個(gè)類的屬性和方法的實(shí)現(xiàn)代碼,需要的朋友可以參考下。2011-05-05thinkphp jquery實(shí)現(xiàn)圖片上傳和預(yù)覽效果
這篇文章主要為大家詳細(xì)介紹了thinkphp上傳圖片功能,和jquery預(yù)覽圖片效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-12-12