Php session Database
It is very easy to save sesison to the database. It is used to perform CRUD operations on the Database Based on session_id. session_set_save_handler is used to customize the session execution method,
First create a data table
CREATE TABLE `sessions` ( `session_id` varchar(255) NOT NULL, `session_expires` int(11) DEFAULT NULL, `session_data` text, PRIMARY KEY (`session_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8
Then encapsulate the tool class used to operate the session:
LifeTime = get_1__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 "";} fu Nction 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 = '{$ sessData}' WHERE session_id = '{$ sessID }'", $ this-> dbHandle); if (mysql_affected_rows ($ this-> dbHandle) return true;} else {mysql_query ("INSERT INT O 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-> dbHandle); if (mysql_affected_rows ($ this-> dbHandle) return true; return false;} function gc ($ sessMaxLife Time) {mysql_query ("delete from sessions WHERE session_expires <". time (), $ this-> dbHandle); return mysql_affected_rows ($ this-> dbHandle) ;}# test the session. It is found that the database does not store data only session_id, and session_expires. In fact, session_data exists, but we cannot see $ session = new session (); session_set_save_handler (array (& $ session, "open"), array (& $ session, "close"), array (& $ session, "read"), array (& $ session, "write"), array (& $ session, "destr Oy "), array (& $ session," gc "); session_start (); $ session-> write (session_id (), json_encode (array ("name" => "gxx", "pass" => "123"); echo $ session-> read (session_id ();?> Illustrations are not supported here ..
Database Data:
S430j9t480ocbovq6a7a0rlk22 1435054078
Session query data:
JSON
- Name "gxx"
- Pass "123" should not be blinded by things ....