Object-Oriented MySQLi based session handler

I ran into a problem with my file session handler, so that I decided to make a database session handler for myself.

You just need to create an instance of Session object-type. session_start() is required if in your php.ini, session.auto_start is set to Off, though you can declare $ini['auto_start']=1 before creating the session object, then pass the $ini array into constructor.

These are parameters you can pass through the constructor

$ini['gc_probability']
$ini['gc_divisor']
$ini['gc_maxlifetime']
$ini['auto_start']
CREATE TABLE `sessions` (
`id` varchar(32) binary NOT NULL default '',
`access` int(10) unsigned NOT NULL default '0',
`data` text,
PRIMARY KEY  (`id`)
) TYPE=InnoDB
< ?php
/**
* link2caro PHP Library
* Class: Object-Oriented MySQLi based session handler
*
* @name: Object-Oriented MySQLi based session handler
* @version 1.0
* /

class Session {

private $_db;
private $_dbinfo;

/**
* Session Construction
* @return void
* @param mixed $dbinfo Database Information
* @param mixed $ini     Initialization Parameters
*/
public function __construct($dbinfo,$ini=null)
{
$this->_dbinfo = $dbinfo;
$this->_dbinfo = $dbinfo;

ini_set('session.save_path', '');
if(!empty($ini['gc_probability']))
ini_set('session.gc_probability', $ini['gc_probability']);
if(!empty($ini['gc_divisor']))
ini_set('session.gc_divisor', $ini['gc_divisor']);
if(!empty($ini['gc_maxlifetime']))
ini_set('session.gc_maxlifetime', $ini['gc_maxlifetime']);

register_shutdown_function('session_write_close');
session_set_save_handler(array(&amp;$this,"_open"),
array(&amp;$this,"_close"),
array(&amp;$this,"_read"),
array(&amp;$this,"_write"),
array(&amp;$this,"_destroy"),
array(&amp;$this,"_gc"));
if(get_cfg_var("session.auto_start") || $ini['autostart'])
session_start();
}

/**
* Open connection to database
* @return bool
*/
public function _open()
{
$this->_db = new mysqli($this->_dbinfo['host'], $this->_dbinfo['user'], $this->_dbinfo['pass'], $this->_dbinfo['database']);
unset($this->_dbinfo['pass']);

if(phpversion() > '5.3.0')
{
if($this->_db->connect_error())
{
printf("Database Connection failed: %s", $this->_db->connect_error());
return FALSE;
}
}
else
{
if(mysqli_connect_error())
{
printf("Database Connection failed: %s", mysqli_connect_error());
return FALSE;
}
}
return TRUE;
}

/**
* Open connection to database
* @return bool
*/
public function _close()
{
if(is_object($this->_db))
return $this->_db->close();
return FALSE;
}

/**
* Open connection to database
* @return bool
* @param string $id Session id
*/
public function _read($id)
{
$sql = "SELECT data
FROM   ".$this->_dbinfo['table']."
WHERE  id = ?";
$query = $this->_db->prepare($sql);
$query->bind_param('s',$id);
$query->execute();
$query->bind_result($data);
$query->fetch();
if(!empty($data))
return $data;
else
return '';
}

/**
* Save/Edit data of this session
* @return bool
* @param string $id     Session id
* @param string $data     Data of this session
*/
public function _write($id, $data)
{
$sql = "REPLACE
INTO    ".$this->_dbinfo['table']."
VALUES  (?, ?, ?)";
$query = $this->_db->prepare($sql);
$query->bind_param("sis", $id, time(), $data);
$query->execute();
return $query->close();
}

/**
* Destroy this session
* @return bool
*/
public function _destroy($id)
{
$sql = "DELETE
FROM   ".$this->_dbinfo['table']."
WHERE  id = ?";
$query = $this->_db->prepare($sql);
$query->bind_param('s', $id);
$query->execute();
$query->close();
@session_unset();
//TODO: check recursivity
@session_destroy();
if($this->_db->affected_rows)
return TRUE;
else
return FALSE;
}

/**
* Garbage Collector
* @return bool
*/
public function _gc()
{
$sql = "DELETE
FROM   ".$this->_dbinfo['table']."
WHERE  access < ?";

$expire = time() - get_cfg_var("session.gc_maxlifetime");
$query = $this->_db->prepare($sql);
$query->bind_param('i', $expire);
$query->execute();
$query->close();
if($this->_db->affected_rows)
return TRUE;
else
return FALSE;
}
}

$dbinfo['host']      = 'mac.lan.link2caro.net';
$dbinfo['user']      = 'root';
$dbinfo['pass']      = 'azerty1973';
$dbinfo['database']  = 'test';
$dbinfo['table']     = 'sessions';
$ini['autostart']     = 1;

$session = new Session($dbinfo,$ini);
?>
1 Comments

One Response to “Object-Oriented MySQLi based session handler”

  1. Humza Ahmed 19/12/2009 at 14:20 #

    Thanks it is really a creative piece of programming.

Leave a Reply