This Sesison storage to the database is very simple, is based on the SESSION_ID database crud operations, mainly used, Session_set_save_handler this method, custom session execution method,
Create a data table first
CREATE TABLE ' Sessions ' ( ' session_id ' varchar (255) NOT NULL, ' session_expires ' int (one-by-one) DEFAULT NULL, ' Session_data ' text, PRIMARY KEY (' session_id ') Engine=innodb DEFAULT Charset=utf8
Then encapsulate the tool class that operates the session:
<?php//error_reporting (0); class Session {Var $lifeTime; var $dbHandle; function open ($savePath, $sessName) {$this->lifetime = Get_cfg_var ("Session.gc_maxlifetime"); $dbHandle = mysql_connect ("localhost", "root", "root"); $dbSel = mysql_select_db ("mysession", $dbHandle); if (! $dbHandle | |! $dbSel) return false; $this->dbhandle = $dbHandle; return true; } function Close () {$this->GC (ini_get (' session.gc_maxlifetime ')); Return @mysql_close ($this->dbhandle); function Read ($sessID) {$res = mysql_query ("Select Session_data as D from sessions WHERE session_id = ' $sessID ' and Session_expires > '. Time (), $this->dbhandle); if ($row = Mysql_fetch_assoc ($res)) return $row [' d ']; Return ""; function Write ($sessID, $sessData) {$newExp = time () + $this->lifetime; $res = mysql_query ("SELECT * from sessions where session_id = ' $sessID '", $this- Dbhandle); if ($res) {mysql_query ("UPDATE sessions SET session_expires = ' {$newExp} ', Session_data = ' {$sessDat A} ' WHERE session_id = ' {$sessID} ' ", $this->dbhandle); if (Mysql_affected_rows ($this->dbhandle)) return true; } else {mysql_query ("INSERT into sessions (session_id, Session_expires, Session_data) VALUES ( ' {$sessID} ', ' {$newExp} ', ' {$sessData} ') ', $this->dbhandle); if (Mysql_affected_rows ($this->dbhandle)) return true; } return false; } function Destroy ($sessID) {mysql_query ("DELETE from sessions WHERE session_id = ' $sessID '", $this->DBH Andle); if (Mysql_affected_rows ($this->dbhandle)) return true; return false; } function GC ($sessMaxLifeTime) {mysql_query ("DELETE from sessions WHERE Session_expires <". Time (), $th Is->dbhandle); Return Mysql_affected_rows ($this->dbhandle); }} #对session进行测试, found that the database is not stored data only session_id, and session_expires values, in fact, Session_data is the existence of just we do not see $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"), session _start (); $session->write (session_id (), Json_encode (Array ("name" = "Gxx", "pass" = "123")); Echo $session- >read (session_id ());? > here actually does not support illustrations.Database data:
S430j9t480ocbovq6a7a0rlk22 1435054078
Session Query data:
JSON
Don't be blinded by things ....
PHP Session Storage Database