複製程式碼程式碼如下:
class SessionToDB
{
private $_path = null;
私人$_name = null;
私人$_pdo = null;
私人$_ip = null;
私人$_maxLifeTime = 0;
public function __construct(PDO $pdo)
{
session_set_save_handler(
array(&$this, 'open'),
array(&$this, 'close'),
array(&this, 'ready(')
array(&$this, 'write'),
array(&$this, 'destroy'),
array(&$this, 'gc')
);
$this->_pdo = $pdo;
$this->_ip = !empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 空;
$this->_maxLifeTime = ini_get('session.gc_maxlifetime');
}
公用函數 open($path,$name)
{
return true;
}
公用函數 close()
{
回傳 true;
}
public function read($id)
{
$sql = 'SELECT * FROM session where PHPSESSID = ?';
$stmt = $this->_pdo->prepare($sql);
$stmt->執行(數組($id));
if (!$result = $stmt->fetch(PDO::FETCH_ASSOC)) {
return null;
} elseif ($this->_ip != $result['client_ip']) {
return null;
} elseif ($result['update_time']+$this->_maxLifeTime $this->destroy($id);
返回空;
} else {
return $result['data'];
}
}
public function write($id,$data)
{
$sql = 'SELECT * FROM session where PHPSESSID = ?';
$stmt = $this->_pdo->prepare($sql);
$stmt->執行(數組($id));
if ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
if ($result['data'] != $data) {
$sql = '更新會話 SET update_time =?哪裡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));
}
}
回傳 true;
}
public function destroy($id)
{
$sql = '從會話中刪除 PHPSESSID = ?';
$stmt = $this->_pdo->prepare($sql);
$stmt->執行(數組($id));
回傳真;
}
public function gc($maxLifeTime)
{
$sql = '從會話中刪除,其中 update_time $stmt->execute(array(time() - $maxLifeTime));
回傳真;
}
}
嘗試{
$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 '錯誤:'.$e->getMessage();
}