2、PHP文件緩存的簡單案例
_cache_path = $config['cache_path']; } else { $this->_cache_path = realpath(dirname(__FILE__)."/")."/cache/"; } } //判斷key值對應的文件是否存在,如果存在,讀取value值,value以序列化存儲 public function get($id) { if ( ! file_exists($this->_cache_path.$id)) { return FALSE; } $data = @file_get_contents($this->_cache_path.$id); $data = unserialize($data); if(!is_array($data) || !isset($data['time']) || !isset($data['ttl'])) { return FALSE; } if ($data['ttl'] > 0 && time() > $data['time'] + $data['ttl']) { @unlink($this->_cache_path.$id); return FALSE; } return $data['data']; } //設置緩存信息,根據key值,生成相應的緩存文件 public function set($id, $data, $ttl = 60) { $contents = array( 'time' => time(), 'ttl' => $ttl, 'data' => $data ); if (@file_put_contents($this->_cache_path.$id, serialize($contents))) { @chmod($this->_cache_path.$id, 0777); return TRUE; } return FALSE; } //根據key值,刪除緩存文件 public function delete($id) { return @unlink($this->_cache_path.$id); } public function clean() { $dh = @opendir($this->_cache_path); if(!$dh) return FALSE; while ($file = @readdir($dh)) { if($file == "." || $file == "..") continue; $path = $this->_cache_path."/".$file; if(is_file($path)) @unlink($path); } @closedir($dh); return TRUE; } }