ADOdb

Database Abstraction Layer for PHP

User Tools

Site Tools


v6:session:session_index

Version 6 Session Management

Introduction

ADOdb session management extends the standard functionality of PHP sessions, by allowing the normal session data seen to be stored in a database. There are numerous ways that this method enhances the default behavior

  • Simplified clean-up at end of session life
  • Easy analysis of session data
  • Simple session termination
  • Session data can be manipulated by external programs
  • Encryption of session data
  • Allows implementation of session termination callbacks
  • Session data can be retained if used across with load balancing servers

ADOdb session management can be considered an extension of the normal behavior. It uses the same command syntax and structure as normal sessions, and honors the values defined in php.ini for sessions.

These records will be garbage-collected based on the php.ini [session] timeout settings. You can register a notification function to notify you when the record has expired and is about to be freed by the garbage collector.

ADOdb Session Handler Features

  • Ability to define a notification function that is called when a session expires. Typically used to detect session logout and release global resources.
  • Optimization of database writes. We crc32 the session data and only perform an update to the session data if there is a data change.
  • Support for large amounts of session data with CLOBs
  • Support for encrypted session data

Upgrading From Version 5

Session management differs from Version 5 in that it is an integrated part of the core ADOdb object. It can be initialized without additional configuration (assuming that the database table is installed). Access to features such as encryption and compression is much simpler. The methods are no longer static, but a drop-in compatibility class is provided.

Usage

/*
* Standard V6 configuration settings
*/
$acd = new ADOdb\ADOConnectionDefinitions($streamHandlers);
$acd->driver = 'mysqli';
$acd->fetchMode = 1;
 
/*
* Start up a new connection object
*/
$obj = new ADOdb\connector($acd);
 
/*
* Obtain a database connection
*/
$db = $obj->connect('127.0.0.1',"adodb","adodb",'employees');
 
/*
* Create an ADOdb session connection
*/
$session = $obj->startSession();
$session->lifetime(3000);
 
/*
* Start the PHP Session handler
*/
session_start();
 
/*
* Manipulate session data
*/
$_SESSION['name'] = 'MARK';
$_SESSION['data'] = array('bird'=>'chicken',
                          'reptile'=>'paper');

The default name of the table is sessions2.

Extending Functionality

Any change of functionality requires the use of the \ADOdb\session\ADOSessionDefinitions class

Overriding Table Name Defaults

/*
* Establish a standard V6 Connection
*/
$db = $obj->connect(.........);
 
/*
* Instantiate and modify a session definition
*/
$asd = new \ADOdb\session\ADOSessionDefinitions;
 
$asd->tableName = 'my_session_table';
 
/*
* Create an ADOdb session connection, passing the session 
* connection object
*/
$session = $obj->startSession($asd);
$session->lifetime(3000);
 
session_start();

Encrypting The Session Data

If used, the sessdata column of the table must support read-write of binary data.

/*
* Establish a standard V6 Connection
*/
$db = $obj->connect(.........);
 
/*
* Instantiate and modify a session definition
*/
$asd = new \ADOdb\session\ADOSessionDefinitions;
 
/*
* Choose an encryption method
*/
$asd->cryptoMethod = $asd::CRYPTO_SHA1;
 
/*
* Create an ADOdb session connection, passing the session 
* connection object
*/
$session = $obj->startSession($asd);
$session->lifetime(3000);
 
session_start();

Compressing The Session Data

If used, the sessdata column of the table must support read-write of binary data.

/*
* Establish a standard V6 Connection
*/
$db = $obj->connect(.........);
 
/*
* Instantiate and modify a session definition
*/
$asd = new \ADOdb\session\ADOSessionDefinitions;
 
/*
* Choose a compression method
*/
$asd->compressionMethod = $asd::COMPRSS_BZIP;
 
/*
* Create an ADOdb session connection, passing the session 
* connection object
*/
$session = $obj->startSession($asd);
$session->lifetime(3000);
 
session_start();

Installation

Create this table in your database.

MySQL or PDO MySQL

  CREATE TABLE sessions2(
	  sesskey VARCHAR( 64 ) NOT NULL DEFAULT '',
	  expiry DATETIME NOT NULL ,
	  expireref VARCHAR( 250 ) DEFAULT '',
	  created DATETIME NOT NULL ,
	  modified DATETIME NOT NULL ,
	  sessdata LONGTEXT,
	  PRIMARY KEY ( sesskey ) ,
	  INDEX sess2_expiry( expiry ),
	  INDEX sess2_expireref( expireref )
  )

PostgreSQL

  CREATE TABLE sessions2(
   sesskey VARCHAR( 64 ) NOT NULL DEFAULT '',
   expiry TIMESTAMP NOT NULL ,
   expireref VARCHAR( 250 ) DEFAULT '',
   created TIMESTAMP NOT NULL ,
   modified TIMESTAMP NOT NULL ,
   sessdata TEXT DEFAULT '',
   PRIMARY KEY ( sesskey )
   );
 
  CREATE INDEX sess2_expiry ON sessions2( expiry );
  CREATE INDEX sess2_expireref ON sessions2 ( expireref );

Oracle

This definition uses a CLOB for the SESSDATA field:

    CREATE TABLE SESSIONS2
  (
     SESSKEY    VARCHAR2(48 BYTE)                  NOT NULL,
     EXPIRY     DATE                               NOT NULL,
     EXPIREREF  VARCHAR2(200 BYTE),
     CREATED    DATE                               NOT NULL,
     MODIFIED   DATE                               NOT NULL,
     SESSDATA   CLOB,
    PRIMARY KEY(SESSKEY)
  );
 
  CREATE INDEX SESS2_EXPIRY ON SESSIONS2(EXPIRY);
  CREATE INDEX SESS2_EXPIREREF ON SESSIONS2(EXPIREREF);

We need to use a CLOB here because for text greater than 4000 bytes long, Oracle requires you to use the CLOB data type. If you are using the oci8 driver, ADOdb will automatically enable CLOB handling. So you can use either adodb-session2.php or adodb-session-clob2.php - in this case it doesn't matter.

Notifications

You can receive notification when your session is cleaned up by the session garbage collector or when you call session_destroy().

PHP's session extension will automatically run a special garbage collection function based on your php.ini session.cookie_lifetime and session.gc_probability settings. This will in turn call adodb's garbage collection function, which can be setup to do notification.

PHP Session --> ADOdb Session  --> Find all recs  --> Send          --> Delete queued
GC Function     GC Function        to be deleted      notification      records
executed at     called by                             for all recs
random time     Session Extension                     queued for deletion

When a session is created, we need to store a value in the session record (in the EXPIREREF field), typically the userid of the session. Later when the session has expired, just before the record is deleted, we reload the EXPIREREF field and call the notification function with the value of EXPIREREF, which is the userid of the person being logged off.

ADOdb uses a global variable $ADODB_SESSION_EXPIRE_NOTIFY that you must predefine before session start to store the notification configuration. $ADODB_SESSION_EXPIRE_NOTIFY is an array with 2 elements, the first being the name of the session variable you would like to store in the EXPIREREF field, and the 2nd is the notification function's name.

For example, suppose we want to be notified when a user's session has expired, based on the userid. When the user logs in, we store the id in the global session variable $USERID. The function name is NotifyFn.

So we define (before session_start() is called):

$ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn');

And when the NotifyFn is called (when the session expires), the $EXPIREREF holding the user id is passed in as the first parameter, e.g. NotifyFn($userid, $sesskey). The session key (which is the primary key of the record in the sessions table) is the 2nd parameter.

Here is an example of a Notification function that deletes some records in the database and temporary files:

function NotifyFn($expireref, $sesskey)
{
	global $ADODB_SESS_CONN; # the session connection object
	$user = $ADODB_SESS_CONN->qstr($expireref);
 
	$ADODB_SESS_CONN->execute("delete from shopping_cart where user=$user");
	system("rm /work/tmpfiles/$expireref/*");
}

NOTE 1: If you have register_globals disabled in php.ini, then you will have to manually set the EXPIREREF. e.g.

$GLOBALS['USERID'] = GetUserID();
$ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn');

NOTE 2: If you want to change the EXPIREREF after the session record has been created, you will need to modify any session variable to force a database record update.

Neat Notification Tricks

ExpireRef normally holds the user id of the current session.

  1. You can then write a session monitor, scanning expireref to see who is currently logged on.
  2. If you delete the sessions record for a specific user, eg. delete from sessions where expireref = '$USER' then the user is logged out. Useful for ejecting someone from a site.
  3. You can scan the sessions table to ensure no user can be logged in twice. Useful for security reasons.

Compression/Encryption Schemes

Multiple encryption and compression schemes are supported. Currently, supported are:

  • MD5Crypt (crypt.inc.php)
  • MCrypt
  • Secure (Horde's emulation of MCrypt, if MCrypt module is not available.)
  • GZip
  • BZip2

These are stackable. E.g.

ADODB_Session::filter(new ADODB_Compress_Bzip2());
ADODB_Session::filter(new ADODB_Encrypt_MD5());

will compress and then encrypt the record in the database.

Backwards Compatibility

The older method of connecting to ADOdb using global variables is now deprecated, and will be removed in ADOdb version 6.0:

$ADODB_SESSION_DRIVER='mysql';
$ADODB_SESSION_CONNECT='localhost';
$ADODB_SESSION_USER ='root';
$ADODB_SESSION_PWD ='abc';
$ADODB_SESSION_DB ='employees';
 
include 'adodb/adodb-session.php';
v6/session/session_index.txt · Last modified: by 127.0.0.1