PHP 檔案快取

2021-08-20 20:08:18 字數 1990 閱讀 9308

/**

* 檔案快取類

* class cache

*/class filecache

self::$dir = $dir;

}/**

* 讀取快取檔案

* @param $file string 快取檔案

* @param boolean 讀取成功返回結果, 否則返回 false

*/public function read( $file )

// 讀取快取檔案

if (!( $handle = @fopen( $filename, 'rb' ) ) )

// 跳過寫入快取檔案保護**

fgets( $handle );

// 取出序列化的快取資料,並進行序列化恢復

$data = unserialize( fgets( $handle ) );

return $data;

}/**

* 寫入快取檔案

* @param $file string 寫入快取的檔名

* @param $data array, 需要進行快取資料

* @param boolean 讀取成功返回結果, 否則返回 false

*/public function write( $file, $data = array() )

return false;

}/**

* 清除快取檔案

* @param array $filearr 需要清除的快取檔案

* @param bool $filenamemode 完整檔名模式,為 true 時必須 $file 引數必須輸入完整的檔名,用於清除不在同一資料夾下的快取檔案!

** 案例:

* cache::clear(array('file1'));//清除單條資料

* cache::clear(array('file1', 'file2', 'file3'));//清除多條資料,注意:必須在同一資料夾下

* cache::clear(array('../cache/file1', '../new/cache/file1'), true);//完整檔名模式

*/public function clear( $filearr, $filenamemode = false )

foreach ( $filearr as $file ) else }}

}

###寫入快取

$data = array('aaa','bbb');

// 寫入 ./cache/a.php

cache::dir('./cache/');

cache::write('a.php', $data);

// 寫入 ./global_cache/b.php

cache::dir('./global_cache/');

cache::write('b.php', $data);

###讀取快取
// 讀取./cache/a.php

cache::dir('./cache/');

print_r(cache::read('a.php'));

// 讀取 ./cache/b.php

cache::dir('./global_cache/');

print_r(cache::read('b.php'));

###清除快取

// 清除方法1

cache::dir('./cache/');

cache::clear(array('a.php'));

cache::dir('./global_cache/');

cache::clear(array('b.php'));

// 方法2

cache::clear(array('./cache/a.php', './global_cache/b.php'), true);

php 檔案快取

class cache return self instance 得到快取資訊 param string id return boolean array public static function get id file instance file id data instance fileget...

PHP檔案快取

專案中要用到臨時儲存乙個陣列,於是想利用php的檔案操作來臨時儲存陣列。php 4,php 5,php 7 fopen 開啟檔案或者 url resource fopen string fi lena me,s trin g mode bool us einc lude path fal se re...

php檔案快取

快取做快取的目的是為了讓程式執行起來更加迅速。因為如果程式訪問資料庫時資料量較大,執行起來會比較慢。而且每一次重新整理頁面都會訪問依稀資料庫,然後再把資料顯示在頁面上。設定快取也有乙個缺點,那就是快取時間要設定好,如果快取時間較長,那麼資料庫資料變化時,不能及時的在頁面上顯示。例如快取不能用在秒殺商...