在查看實例之前請先了解 PHP session_set_save_handler#函數的用法
定義個SessionManager 類別
class SessionManager { private $redis; public function construct(){ $this->redis = new Redis(); $this->redis->connect('192.168.0.102', 6379); $retval =session_set_save_handler( array($this,"open"), array($this,"close"), array($this,"read"), array($this,"write"), array($this,"destroy"), array($this,"gc") ); session_start(); } public function open($path,$name){ return true; } public function close(){ return true; } public function read($id){ $session_value = $this->redis->get($id); if($session_value){ return $session_value; }else{ return ""; } } public function write($id,$data){ if($this->redis->set($id,$data)){ return true; }else{ return false; } } public function destroy($id){ if($this->redis->delete($id)){ return true; }else{ return false; } } public function gc($maxlifetime){ return true; } public function destruct(){ session_write_close(); } }
建立一個session_set.php 程式碼如下
include("SessionManager.php"); new SessionManager(); $_SESSION['user_name']="xxdcsnd@sina.com";
建立一個session_set.php 程式碼如下
include("SessionManager.php"); new SessionManager(); echo $_SESSION['user_name'];
測試輸出結果 xxdcsnd@sina.com
注意:php.ini session.save-hadler 設定為user ,否則session_set_save_handler 不會生效
以上是redis如何取代php實作檔案儲存session的實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!