<?php
$connection = mysql_connect("localhost", "XXX", "XXX") OR die(mysql_error());
mysql_select_db("XXX");
class SessionSaveHandler_Db {
protected $connection = null;
protected $name = '';
public function __construct($connection) {
$this->connection = $connection;
session_set_save_handler(array(&$this, 'open'),
array(&$this, 'close'),
array(&$this, 'read'),
array(&$this, 'write'),
array(&$this, 'destroy'),
array(&$this, 'gc'));
register_shutdown_function('session_write_close');
session_start();
}
public function open($save_path, $name) {
$this->name = $name;
}
public function close() {}
public function read($session_id) {
$query = "SELECT COUNT(*) AS count, session_data FROM `sessions` WHERE session_id = '" . mysql_real_escape_string($session_id, $this->connection) . "' GROUP BY session_id";
$res = mysql_query($query, $this->connection) OR die(mysql_error());
$result = mysql_fetch_assoc($res);
$count = $result['count'];
$data = $result['session_data'];
if($count > 0) {
$data = explode('|', $data);
array_shift($data);
$data = implode('|', $data);
return unserialize(stripslashes($data));
}else{
return false;
}
}
public function write($session_id, $data) {
$session_data = $this->name . '|' . addslashes(serialize($data));
$session_id = mysql_real_escape_string($session_id, $this->connection);
$query = "REPLACE INTO `sessions` VALUES ('$session_id', '$session_data', " . time() . ")";
mysql_query($query, $this->connection) OR die(mysql_error());
}
public function destroy($session_id) {
$session_id = mysql_real_escape_string($session_id, $this->connection);
$query = "DELETE FROM `sessions` WHERE session_id = '$session_id'";
mysql_query($query, $this->connection) OR die(mysql_error());
}
public function gc($maxlifetime) {
$maxlifetime = (int) $maxlifetime;
$query = "DELETE FROM `sessions` WHERE (session_time + $maxlifetime) < UNIX_TIMESTAMP()";
mysql_query($query, $this->connection) OR die(mysql_error());
}
}
?>