<?php // ini_set('session.save_handler', 'user'); // 注意 set_session_save_handler() 必定要在 session_start()前執行 // session.gc_probability =1 //session 回收機制的機率分子 // session.gc_divisor = 1000 // session 回收機制的機率分母 // session.gc_maxlifetime = 1440 // session 有效期 // 當開啓 session 時,如 session_start(), // 執行順序爲 sess_open() -> sess_read()->sess_write() -> sess_close() ->sess_destroy() -> sess_gc() ini_set("session.save_handler", "user"); // 自定義保存方式 function sess_open($sess_path, $sess_name) { echo "session 路徑:" . $sess_path . "<br />"; echo "session名稱:" . $sess_name . "<br />"; return true; } function sess_close() { echo "session 關閉<br />"; return true; } function sess_read($sess_id) { echo "讀取session id :" . $sess_id . "<br />"; return true; } function sess_write($sess_id, $data) { echo "寫入數據 session id " . $sess_id . "<br />"; echo "session 數據 " . $data . "<br />"; return true; } function sess_destroy($sess_id) { echo "銷燬 session id " . $sess_id . "<br />"; return true; } function sess_gc($sess_maxlifetime) { echo "session 回時機制,每隔時間爲 " . $sess_maxlifetime; return true; } session_set_save_handler("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc"); session_start(); $_SESSION['lin'] = 'lin3615'; echo 'hi, world '; $_SESSION['long'] = 'good luck for you'; // 開啓 cookie 時,默認時會以 session 名稱 PHPSESSID 爲了cookie 爲記錄 // 如 $_COOKIE['PHPSESSID'] = session_id; 值即爲session_id值。 // 默認時,它們之間的關係是:session_name() = PHPSESSID ; $_COOKIE[session_name()] = session_id(); print_r($_COOKIE); ?> ================ 如下適合 <?php /* 數據表 CREATE TABLE IF NOT EXISTS `sessions` ( `id` char(200) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', `data` text COLLATE utf8_unicode_ci, `timestamp` varchar(200) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; */ class Session { /** * a database connection resource * @var resource $maxTime 生存時間 */ private $_sess_db; private $maxTime; /** * Open the session * @return bool */ public function open() { $this->maxTime = get_cfg_var("session.gc_maxlifetime") > 0 ? get_cfg_var("session.gc_maxlifetime") : 3600; if ($this->_sess_db = mysql_connect('localhost', 'root', '123456')) { return mysql_select_db('test', $this->_sess_db); } return false; } /** * Close the session * @return bool */ public function close() { return mysql_close($this->_sess_db); } /** * Read the session * @param int session id * @return string string of the sessoin */ public function read($id) { $id = mysql_real_escape_string($id); $sql = "SELECT `data` FROM `sessions` " . "WHERE id = '" . $id . "'"; if ($result = mysql_query($sql, $this->_sess_db)) { if (mysql_num_rows($result)) { $record = mysql_fetch_assoc($result); return $record['data']; } } return ''; } /** * Write the session * @param int session id * @param string data of the session */ /* replace [into] 與 insert 功能相似,不一樣點在於:replace into 首先嚐試插入數據表中,若是發現表中已經有此行數據(根據主鍵或者惟一索引斷定)則先刪除此行,而後插入新的數據。不然直接插入數據。要注意是:插入數據的表必須有主鍵或者惟一索引。不然就成了 insert 了 */ public function write($id, $data) { $sql = sprintf("REPLACE INTO `sessions` VALUES('%s', '%s', '%s')", mysql_real_escape_string($id), mysql_real_escape_string($data), mysql_real_escape_string(time() + $this->maxTime)); return mysql_query($sql, $this->_sess_db); } /** * Destoroy the session * @param int session id * @return bool */ public function destroy($id) { $sql = sprintf("DELETE FROM `sessions` WHERE `id` = '%s'", $id); return mysql_query($sql, $this->_sess_db); } /** * Garbage Collector * @param int life time (sec.) * @return bool * @see session.gc_divisor 100 * @see session.gc_maxlifetime 1440 * @see session.gc_probability 1 * @usage execution rate 1/100 * (session.gc_probability/session.gc_divisor) */ public function gc($max) { $sql = sprintf("DELETE FROM `sessions` WHERE `timestamp` < '%s'", mysql_real_escape_string(time() - $max)); return mysql_query($sql, $this->_sess_db); } } //ini_set('session.gc_probability', 50); ini_set('session.save_handler', 'user'); $session = new Session(); session_set_save_handler(array($session, 'open'), array($session, 'close'), array($session, 'read'), array($session, 'write'), array($session, 'destroy'), array($session, 'gc')); // below sample main session_start(); //session_regenerate_id(true); if (isset($_SESSION['counter'])) { $_SESSION['counter']++; } else { $_SESSION['counter'] = 1; } print_r($_SESSION); //unset($_SESSION); //session_destroy(); ?>
<?php // 如下這官網手冊整合 /** 數據表 CREATE TABLE `ws_sessions` ( `session_id` char(100) NOT NULL default '', `session_expires` int(11) unsigned NOT NULL default '0', `session_data` text, PRIMARY KEY (`session_id`) ) engine=InnoDB; */ class MySessionHandler implements SessionHandlerInterface { // 生存時間 public $lifeTime; // 鏈接句柄 public $dbHandle; function open($savePath, $sessName) { // 獲取生存時間 $this->lifeTime = get_cfg_var("session.gc_maxlifetime"); // $dbHandle = new mysqli("主機名", "用戶名", "密碼", "數據庫名"); $dbHandle = new mysqli("localhost", "root", "", "test"); if($dbHandle->connect_error) return false; $this->dbHandle = $dbHandle; return true; } function close() { $this->gc(ini_get('session.gc_maxlifetime')); // 關閉鏈接 return $this->dbHandle->close(); } function read($sessID) { // fetch session-data $res = $this->dbHandle->query("SELECT session_data AS d FROM ws_sessions WHERE session_id = '$sessID' AND session_expires > ".time()); if($dd = $res->fetch_assoc()) { return $dd['d']; } return ""; } function write($sessID,$sessData) { // 新的有效時間 $newExp = time() + $this->lifeTime; $res = $this->dbHandle->query("SELECT * FROM ws_sessions WHERE session_id = '$sessID'"); // 有效 if($res->num_rows) { // 更新 $this->dbHandle->query("UPDATE ws_sessions SET session_expires = '$newExp', session_data = '$sessData' WHERE session_id = '$sessID'"); // 更新是否生效 if($this->dbHandle->affected_rows) return true; } else { $this->dbHandle->query("INSERT INTO ws_sessions ( session_id, session_expires, session_data) VALUES( '" . $sessID ."', " . $newExp .", '" . $sessData ."')"); // 更新是否生效 if($this->dbHandle->affected_rows) return true; } // 發生錯誤 return false; } function destroy($sessID) { // delete session-data $this->dbHandle->query("DELETE FROM ws_sessions WHERE session_id = '$sessID'"); // if session was deleted, return true, if($this->dbHandle->affected_rows) return true; // ...else return false return false; } function gc($sessMaxLifeTime) { // delete old sessions $this->dbHandle->query("DELETE FROM ws_sessions WHERE session_expires < ".time()); // return affected rows return $this->dbHandle->affected_rows; } } ini_set('session.save_handler', 'user'); $handler = new MySessionHandler(); session_set_save_handler($handler, true); // 引用方法,覺得另存文件,如:session.php,新創建文件,如test.php include('session.php'); session_start(); $_SESSION['lin3615'] = date('Y-m-d H:i:s', time()); print_r($_SESSION);