Session: shares the php class stored in the database. Copy the code as follows :? PhpclassSessionToDB {private $ _ pathnull; private $ _ namenull; private $ _ pdonull; private $ _ ipnull; private $ _ maxLifeTime0; publicfunct
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 ();
}
The http://www.bkjia.com/PHPjc/324512.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/324512.htmlTechArticle code is as follows :? Php class SessionToDB {private $ _ path = null; private $ _ name = null; private $ _ pdo = null; private $ _ ip = null; private $ _ maxLifeTime = 0; public funct...