Session saved to the php class of the database. For more information, see.
Session saved to the php class of the database. For more information, see.
The Code is as follows:
Class SessionToDB
{
Private $ _ path = null;
Private $ _ name = null;
Private $ _ pdo = null;
Private $ _ ip = null;
Private $ _ maxLifeTime = 0;
Public function _ construct (PDO $ pdo)
{
Session_set_save_handler (
Array (& $ this, 'open '),
Array (& $ this, 'close '),
Array (& $ this, 'read '),
Array (& $ this, 'write '),
Array (& $ this, 'deststroy '),
Array (& $ this, 'gc ')
);
$ This-> _ pdo = $ pdo;
$ This-> _ ip =! Empty ($ _ SERVER ['remote _ ADDR '])? $ _ SERVER ['remote _ ADDR ']: null;
$ This-> _ maxLifeTime = ini_get ('session. gc_maxlifetime ');
}
Public function open ($ path, $ name)
{
Return true;
}
Public function close ()
{
Return true;
}
Public function read ($ id)
{
$ SQL = 'select * FROM session where PHPSESSID =? ';
$ Stmt = $ this-> _ pdo-> prepare ($ SQL );
$ Stmt-> execute (array ($ id ));
If (! $ Result = $ stmt-> fetch (PDO: FETCH_ASSOC )){
Return null;
} Elseif ($ this-> _ ip! = $ Result ['client _ ip']) {
Return null;
} Elseif ($ result ['Update _ time'] + $ this-> _ maxLifeTime <time ()){
$ This-> destroy ($ id );
Return null;
} Else {
Return $ result ['data'];
}
}
Public function write ($ id, $ data)
{
$ SQL = 'select * FROM session where PHPSESSID =? ';
$ Stmt = $ this-> _ pdo-> prepare ($ SQL );
$ Stmt-> execute (array ($ id ));
If ($ result = $ stmt-> fetch (PDO: FETCH_ASSOC )){
If ($ result ['data']! = $ Data ){
$ SQL = 'Update session SET update_time =? , Date =? Where phpsessid =? ';
$ Stmt = $ this-> _ pdo-> prepare ($ SQL );
$ Stmt-> execute (array (time (), $ data, $ id ));
}
} Else {
If (! Empty ($ data )){
$ SQL = 'insert INTO session (PHPSESSID, update_time, client_ip, data) VALUES (?,?,?,?) ';
$ Stmt = $ this-> _ pdo-> prepare ($ SQL );
$ Stmt-> execute (array ($ id, time (), $ this-> _ ip, $ data ));
}
}
Return true;
}
Public function destroy ($ id)
{
$ SQL = 'delete FROM session WHERE PHPSESSID =? ';
$ Stmt = $ this-> _ pdo-> prepare ($ SQL );
$ Stmt-> execute (array ($ id ));
Return true;
}
Public function gc ($ maxLifeTime)
{
$ SQL = 'delete FROM session WHERE update_time <? ';
$ Stmt = $ this-> _ pdo-> prepare ($ SQL );
$ Stmt-> execute (array (time ()-$ maxLifeTime ));
Return true;
}
}
Try {
$ Pdo = new PDO ('mysql: host = localhost; dbname = rphp4zf ', 'root', 'rickyfeng ');
$ Pdo-> setAttribute (PDO: ATTR_ERRMODE, PDO: ERRMODE_EXCEPTION );
New SessionToDB ($ pdo );
} Catch (PDOException $ e ){
Echo 'error: '. $ e-> getMessage ();
}