Saving PHP Session Data to a Database
by Tony MarstonTonyMarston.net
Friday, 22nd September 2006
Define database class
Within my development infrastructure it is my practice to use a separate class to access each database table. Each table class is actually a subclass to a generic table class which contains all the functionality which is standard across all database tables. This section identifies the contents of the subclass. A copy of the superclass is contained within the source code for my sample application.
The table class exists in a file called <tablename>.class.inc which is described in A Data Dictionary for PHP Applications.
require_once 'std.table.class.inc';
class php_Session extends Default_Table
{
// ****************************************************************************
// This class saves the PHP session data in a database table.
// ****************************************************************************
// ****************************************************************************
// class constructor
// ****************************************************************************
function php_Session ()
{
// save directory name of current script
$this->dirname = dirname(__file__);
$this->tablename = 'php_session';
$this->dbname = 'audit';
$this->fieldspec = $this->getFieldSpec_original();
// there is absolutely NO logging of the audit database
$this->audit_logging = false;
} // php_Session
The member variable $session_open is for use in the close() method (see below).
The constructor forces the member variable $audit_logging to be false as updates to this database table are not to appear in the audit log.
function open ($save_path, $session_name)
// open the session.
{
// do nothing
return TRUE;
} // open
The open() function does not have to do anything as the database is not actually opened until control is passed to my DML class.
function close ()
// close the session.
{
if (!empty($this->fieldarray)) {
// perform garbage collection
$result = $this->gc(0);
return $result;
} // if
return FALSE;
} // close
The close() function is responsible for calling the gc() function to perform garbage collection.
function read ($session_id)
// read any data for this session.
{
$fieldarray = $this->_dml_getData("session_id='$session_id'");
if (isset($fieldarray[0]['session_data'])) {
$this->fieldarray = $fieldarray[0];
$this->fieldarray['session_data'] = '';
return $fieldarray[0]['session_data'];
} else {
return ''; // return an empty string
} // if
} // read
The read() function is responsible for retrieving the data for the specified session. Note that if there is no data it must return an empty string, not the value NULL.
function write ($session_id, $session_data)
// write session data to the database.
{
if (!empty($this->fieldarray)) {
if ($this->fieldarray['session_id'] != $session_id) {
// user is starting a new session with previous data
$this->fieldarray = array();
} // if
} // if
if (empty($this->fieldarray)) {
// create new record
$array['session_id'] = $session_id;
$array['date_created'] = getTimeStamp();
$array['last_updated'] = getTimeStamp();
$array['session_data'] = addslashes($session_data);
$this->_dml_insertRecord($array);
} else {
// update existing record
if (isset($_SESSION['logon_user_id'])) {
$array['user_id'] = $_SESSION['logon_user_id'];
} // if
$array['last_updated'] = getTimeStamp();
$array['session_data'] = addslashes($session_data);
$this->_dml_updateRecord($array, $this->fieldarray);
} // if
return TRUE;
} // write
The write() function is responsible for creating or updating the database with the session data which is passed to it.
function destroy ($session_id)
// destroy the specified session.
{
$fieldarray['session_id'] = $session_id;
$this->_dml_deleteRecord($fieldarray);
return TRUE;
} // destroy
If the session_destroy() function is issued in the code then this will be responsible for deleting the session data from the database.
function gc ($max_lifetime)
// perform garbage collection.
{
$real_now = date('Y-m-d H:i:s');
$dt1 = strtotime("$real_now -2 hours");
$dt2 = date('YmdHis', $dt1);
$count = $this->_dml_deleteSelection("last_updated < $dt2");
return TRUE;
} // gc
// ****************************************************************************
} // end class
// ****************************************************************************
?>
This is the garbage collection or "clean-up" function. Notice that the time limit of 2 hours has been hard-coded. This means that any session record which has not been modified within this time limit Will be deleted.
Options:
Printer Friendly
Email Friend
I have been a software engineer, both designing and developing, since 1977. I have worked with a variety of 2nd, 3rd and 4th generation languages on a mixture of mainframes, mini- and micro-computers. I have worked with flat files, indexed files, hierarchical databases, network databases and relational databases. The user interfaces have included punched card, paper tape, teletype, block mode, CHUI, GUI and web. I have written code which has been procedural, model-driven, event-driven, component-based and object oriented. I have built software using the 1-tier, 2-tier, 3-tier and Model-View-Controller (MVC) architectures. After working with COBOL for 16 years I switched to UNIFACE in 1993, starting with version 5, then progressing through version 6 to version 7. In the middle of 2002 I decided to teach myself to develop web applications using PHP and MySQL.
