Helping ordinary people create extraordinary websites!
HOME TUTORIALS SCRIPTS WEB HOSTING BLOG FORUM
Get Our Newsletter
Your Email:

Saving PHP Session Data to a Database

By Tony Marston
2005-07-11


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.


<?php

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.



Tutorial Pages:
» Introduction
» Define database table
» Define database class
» Define session handler
» Conclusion


 | Bookmark
Related Tutorials:
» Port Scanning and Service Status Checking in PHP
» Web Database Access from Desktop Applications
» CubeCart 3.0 Installation and Configuration
» PHP Site Search Made Easy
» Installing and Configuring Drupal 6.1
» Desktop Application Development with PHP-GTK