Copy CodeThe 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, ' Destroy '),
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 above describes the easyrecoveryprofessional session saved to the database of PHP class sharing, including the easyrecoveryprofessional aspects of the content, I hope that the PHP tutorial interested in a friend helpful.