PHP Code:
<?php
class SessionManager {
const table = 'sessions';
const id = 'id';
const data = 'data';
const expiration = 'expiration';
protected $_life;
protected $_db;
public function __construct(PDO $pDb) {
$this->_life = get_cfg_var('session.gc_maxlifetime');
$this->_db = $pDb;
$this->_init();
}
protected function _init() {
$this->_register();
}
protected function _register() {
session_set_save_handler(
array($this,'open')
,array($this,'close')
,array($this,'read')
,array($this,'write')
,array($this,'destroy')
,array($this,'gc')
);
}
public function open($pSavePath,$pSessionName) {
global $sessSavePath;
$sessSavePath = $pSavePath;
return true;
}
public function close() {
return true;
}
public function read($pId) {
$data = '';
$time = time();
$sql = 'SELECT t0.'.self::id.' AS id, t0.'.self::data.' AS data, t0,'.self::expiration.' AS expiration FROM '.self::table.' AS t0 WHERE t0.'.self::id.'= :id AND t0.'.self::expiration.' > :expiration LIMIT 1';
if($stmt = $this->_db->prepare($sql)) {
$stmt->bindParam(':id',$pId,PDO::PARAM_STR);
$stmt->bindParam(':expiration',$time,PDO::PARAM_INT);
if($stmt->execute()) {
if($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data = $row['data'];
}
}
}
return $data;
}
public function write($pId,$pData) {
$time = time() + $this->_life;
$sql = 'REPLACE '.self::table.' ('.self::id.','.self::data.','.self::expiration.') VALUES (:id,:data,:expiration)';
if($stmt = $this->_db->prepare($sql)) {
$stmt->bindParam(':id',$pId,PDO::PARAM_STR);
$stmt->bindParam(':data',$pData,PDO::PARAM_STR);
$stmt->bindParam(':expiration',$time,PDO::PARAM_INT);
if($stmt->execute()) {
return true;
}
}
}
public function destroy($pId) {
$sql = 'DELETE FROM '.self::table.' WHERE '.self::id.' = :id LIMIT 1';
if($stmt = $this->_db->prepare($sql)) {
$stmt->bindParam(':id',$pId,PDO::PARAM_STR);
if($stmt->execute()) {
return true;
}
}
}
public function gc() {
$sql = 'DELETE FROM '.self::table.' WHERE '.self::expiration.' < UNIX_TIMESTAMP()';
if($stmt = $this->_db->prepare($sql)) {
$stmt->execute();
}
return true;
}
}
?>
Bookmarks