[eluser]leonglass[/eluser]
OK here it is.
Session.php
Code:
<?php
/*
CREATE TABLE `<insert table name>` (
`sid` char(32) NOT NULL,
`expire` int(11) NOT NULL,
`value` text NOT NULL,
PRIMARY KEY (`sid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
*/
class Session
{
var $CI;
/*
class constructor. sets the callback functions for using
a database with the session. Sets the session name and starts the
session.
*/
function __construct()
{
$this->CI =& get_instance();
session_set_save_handler(array(&$this, "open"),
array(&$this, "close"),
array(&$this, "select"),
array(&$this, "write"),
array(&$this, "destroy"),
array(&$this, "gc"));
session_name($this->CI->config->item('sess_cookie_name'));
session_start();
}
/*
class destructor. Does nothing yet
*/
function __destruct()
{
/*session_write_close();*/
}
/*
* Don't do anything as I dont open a db
* The assumption is that the db has been autoloaded
*/
function open($session_path, $session_name)
{
return 1;
}
/*
* Doesn't actually do anything as I don't close the db
* allow the script ending to auto close db connections
*/
function close()
{
return 1;
}
/*
* Reads the session data from the database
*/
function select($SID)
{
$where = array('sid' => $SID, 'expire >' => time());
$this->CI->db->select('value');
$query = $this->CI->db->get($this->CI->config->item('sess_table_name'));
$row = $query->row();
return $row->value;
}
/*
* This function writes the session data to the database.
* If that SID already exists, then the existing data will be updated.
*/
function write($SID, $value)
{
$expiration = time() + $this->CI->config->item('sess_expiration');
$query = "INSERT INTO " . $this->CI->config->item('sess_table_name') .
" VALUES('$SID', '$expiration', '$value')";
if( !$this->CI->db->simple_query($query))
{
$query = "UPDATE " . $this->CI->config->item('sess_table_name') .
" SET expire='" . $expiration .
"', value='" . $value . "' WHERE sid='". $SID .
"' AND expire > '". time() . "'";
$this->CI->db->query($query);
}
}
/*
* Deletes all session information having input SID (only one row)
*/
function destroy($SID)
{
$query = "DELETE FROM " . $this->CI->config->item('sess_table_name') . " WHERE sid = '$SID'";
$this->CI->db->query($query);
}
/*
* Deletes all sessions that have expired.
*/
function gc($lifetime)
{
$query = "DELETE FROM " . $this->CI->config->item('sess_table_name') . " WHERE expire < " . time();
$this->CI->db->query($query);
return $query->num_rows();
}
}//end class
?>
It seems to be working after the minimal testing I have done on it. Place the php file in application/libraries and use the same configuration from application/config/config.php. Hope someone finds it usefull. Once this class is loaded you should be able to use $_SESSION['var_name'] as before and see the updates in your db. Let me know how you get on with this class.