當咱們所作的系統相對來講比較大的時候,可能會用到session的共享機制!如呵實現session的共享,有不少的方法,可是,在php中,我的認爲首先要實現對session的重寫,才能進一步往下談session的共享!php
若是實現session的重寫機制呢?php爲咱們提供了重寫的函數,session_set_save_handle()咱們只須要應用便可!mysql
<?php session_set_save_handler(); class Session { /* 操做數據庫的db對象 */ private $_db = null; /** * 構造函數,鏈接數據庫使用 * * @access public */ public function __construct() { require '../Db/Db.class.php'; require '../Config/Config.php'; $this->_db = new Core_DB($config); } /** * 開始session機制時自動調用,即調用session_start()後立刻回調該函數 * * @param string $sessionSavePath session文件的存儲路徑 * @param string $sessionName 默認爲PHPSESSID * @return boolan * @access public */ public function open($sessionSavePath, $sessionName) { /* 咱們也能夠在這裏鏈接數據庫 */ return true; } /** * 在腳本執行完畢後,在write回調以後,進行調用 * * @access public * @return boolean */ public function close() { mysql_close($this->_db->_connectid); return true; } /** * 開啓session機制後自動調用,在open回調以後立刻調用 * * @param string $sessionID * @return String * @access public */ public function read($sessionID) { $returnData = ''; $sessionID = trim($sessionID); $sql = " select * from session where session_id='$sessionID' "; $sessionRecord = $this->_db->getToArray($sql); if(is_array($sessionRecord)) { $returnData = $sessionRecord['sessiondata']; } return $returnData; } /** * 當腳本執行完畢後,回調該函數 * * @param $sessionID string * @param string $sessionData 要保存的session數據 * @return mixed * @access public */ public function write($sessionID, $sessionData) { $result = false; $sessionID = trim($sessionID); $sessionData = trim($sessionData); if(!empty($sessionData)) { $addTime = date('Y-m-d H:i:s'); $sql = " select * from session where session_id = '$sessionID' "; $sessionRecord = $this->_db->query($sql);//boolean if(count($sessionRecord)) {//存在更新 $sql = " update session set sessionData = '$sessionData', addtime = '$addTime' where session_id = '$sessionID' "; } else {//不存在,插入 $sql = " inset into session values ('$sessionID', '$sessionData', '$addTime') "; } $this->_db->query($sql); } return $result; } /** * 當調用session_destory()函數的時候,對該函數進行回調 * * @param string $sessioinID * @return boolean * @access public */ public function destory($sessionID) { $result = false; $sql = " delete from session where session_id = '$sessionID' "; $result = $this->_db->query($sql); return $result; } /** * session的垃圾回收機制,當session數據超過了靜默時間,按照機率刪除 默認機率:1/1000 * * @param $maxliefttime 靜默時間,默認爲1440秒 * @access public * @return boolean */ public function gc($maxlifetime) { $result = false; $expireTime = time()-$maxlifetime; $sql = " delete from session where addtime < $expireTime "; $result = $this->_db->query($sql); return $result; } } $session = new Session(); session_set_save_handler( array($session, 'open'), array($session, 'close'), array($session, 'read'), array($session, 'write'), array($session, 'destory'), array($session, 'gc') ); session_start(); ?