### ADODB Session Management Manual

V4.98 13 Feb 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my)

This software is dual licensed using BSD-Style and LGPL. This means you can use it in compiled proprietary and commercial products.

Useful ADOdb links: Download Other Docs

### Introduction

This documentation discusses the old adodb-session.php. Here is the new documentation on the newer adodb-session2.php.

We store state information specific to a user or web client in session variables. These session variables persist throughout a session, as the user moves from page to page.

To use session variables, call session_start() at the beginning of your web page, before your HTTP headers are sent. Then for every variable you want to keep alive for the duration of the session, call session_register($variable_name). By default, the session handler will keep track of the session by using a cookie. You can save objects or arrays in session variables also.

The default method of storing sessions is to store it in a file. However if you have special needs such as you:

- Have multiple web servers that need to share session info
- Need to do special processing of each session
- Require notification when a session expires

The ADOdb session handler provides you with the above additional capabilities by storing the session information as records in a database table that can be shared across multiple servers.

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.

Important Upgrade Notice: Since ADOdb 4.05, the session files have been moved to its own folder, adodb/session. This is a rewrite of the session code by Ross Smith. The old session code is in adodb/session/old.

#### 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 (see adodb-session-clob.php). Useful for Oracle.
- Support for encrypted session data, see adodb-cryptsession.php. Enabling encryption is simply a matter of including adodb-cryptsession.php instead of adodb-session.php.

### Setup

There are 3 session management files that you can use:

    adodb-session.php        : The default
    adodb-session-clob.php   : Use this if you are storing DATA in clobs
    adodb-cryptsession.php   : Use this if you want to store encrypted session data in the database

Examples

         include('adodb/adodb.inc.php');

        $ADODB_SESSION_DRIVER='mysql';
        $ADODB_SESSION_CONNECT='localhost';
        $ADODB_SESSION_USER ='scott';
        $ADODB_SESSION_PWD ='tiger';
        $ADODB_SESSION_DB ='sessiondb';

        include('adodb/session/adodb-session.php');
        session_start();

        #
        # Test session vars, the following should increment on refresh
        #
        $_SESSION['AVAR'] += 1;
        print "<p>\$_SESSION['AVAR']={$_SESSION['AVAR']}</p>";

To force non-persistent connections, call adodb_session_open() first before session_start():

        include('adodb/adodb.inc.php');

        $ADODB_SESSION_DRIVER='mysql';
        $ADODB_SESSION_CONNECT='localhost';
        $ADODB_SESSION_USER ='scott';
        $ADODB_SESSION_PWD ='tiger';
        $ADODB_SESSION_DB ='sessiondb';

        include('adodb/session/adodb-session.php');
        adodb_sess_open(false,false,false);
        session_start();

The 3rd parameter to adodb_sess_open($path, $sessname, $connectMode) sets the connection method. You can pass in the following:

$connectMode | Connection Method
true | PConnect( )
false | Connect( )
'N' | NConnect( )
'P' | PConnect( )
'C' | Connect( )

To use a encrypted sessions, simply replace the file adodb-session.php:

        include('adodb/adodb.inc.php');

        $ADODB_SESSION_DRIVER='mysql';
        $ADODB_SESSION_CONNECT='localhost';
        $ADODB_SESSION_USER ='scott';
        $ADODB_SESSION_PWD ='tiger';
        $ADODB_SESSION_DB ='sessiondb';

        include('adodb/session/adodb-cryptsession.php');
        session_start();

And the same technique for adodb-session-clob.php:

        include('adodb/adodb.inc.php');

        $ADODB_SESSION_DRIVER='mysql';
        $ADODB_SESSION_CONNECT='localhost';
        $ADODB_SESSION_USER ='scott';
        $ADODB_SESSION_PWD ='tiger';
        $ADODB_SESSION_DB ='sessiondb';

        include('adodb/session/adodb-session-clob.php');
        session_start();

An alternative way to set persistant or non-persistent connections is to call the following function before session_start() is called.

     	ADODB_Session::persist('P'); # 'C' for non-persistent connections

#### Installation

1. Create this table in your database (MySQL syntax):

       create table sessions (
           SESSKEY char(32) not null,
           EXPIRY int(11) unsigned not null,
           EXPIREREF varchar(64),
    	   DATA text not null,
    	   primary key (sesskey)
    	   );

You may want to rename the 'data' field to 'session_data' as 'data' appears to be a reserved word for one or more of the following:

- ANSI SQL
- IBM DB2
- MS SQL Server
- Postgres
- SAP

If you do, then execute:

    		ADODB_Session::dataFieldName('session_data');

For the adodb-session-clob.php version, create this:

        create table sessions (
           SESSKEY char(32) not null,
           EXPIRY int(11) unsigned not null,
           EXPIREREF varchar(64),
           DATA CLOB,
          primary key (sesskey)
      );

2. Then define the following parameters. You can either modify this file, or define them before this file is included:

        $ADODB_SESSION_DRIVER='database driver, eg. mysql or ibase';
        $ADODB_SESSION_CONNECT='server to connect to';
        $ADODB_SESSION_USER ='user';
        $ADODB_SESSION_PWD ='password';
        $ADODB_SESSION_DB ='database';
        $ADODB_SESSION_TBL = 'sessions'; # setting this is optional

When the session is created, $ADODB_SESS_CONN holds the connection object.
3. Recommended is PHP 4.0.6 or later. There are documented session bugs in earlier versions of PHP.

### 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 $USERID is passed in as the first parameter, eg. 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.

### Using Oracle CLOBs

Suppose you are storing the DATA field in a CLOB:

       CREATE TABLE sessions (
           SESSKEY VARCHAR(32) NOT NULL,
           EXPIRY NUMBER(16)  NOT NULL,
           EXPIREREF VARCHAR(64),
           DATA CLOB,
          PRIMARY KEY (sesskey)
      );

Then your PHP code could look like this:

    	ADODB_SESSION_DRIVER='oci8';
    	$ADODB_SESSION_CONNECT=$tnsname;
    	$ADODB_SESSION_USER ='scott';
    	$ADODB_SESSION_PWD = 'tiger';
    	$ADODB_SESSION_DB ='';

    	$ADODB_SESSION_USE_LOBS = 'clob';
    	$ADODB_SESSION_TBL = 'sessions';

    	$ADODB_SESS_DEBUG=0;

    	include(ADODB_DIR.'/session/adodb-session.php');

    	ADODB_Session::persist('P'); # use 'C' for non-persistent connects

    	session_start();

Note that you can set persistance using ADODB_Session::persist('P').

### Compression/Encryption Schemes

Since ADOdb 4.05, thanks to Ross Smith, 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.

### adodb_session_regenerate_id()

Dynamically change the current session id with a newly generated one and update database. Currently only works with cookies. Useful to improve security by reducing the risk of session-hijacking. See this article on Session Fixation for more info on the theory behind this feature. Usage:

    	$ADODB_SESSION_DRIVER='mysql';
    	$ADODB_SESSION_CONNECT='localhost';
    	$ADODB_SESSION_USER ='root';
    	$ADODB_SESSION_PWD ='abc';
    	$ADODB_SESSION_DB ='phplens';

    	include('path/to/adodb/session/adodb-session.php');

    	session_start();
    	# Every 10 page loads, reset cookie for safety.
    	# This is extremely simplistic example, better
    	# to regenerate only when the user logs in or changes
    	# user privilege levels.
    	if ((rand()%10) == 0) adodb_session_regenerate_id();

This function calls session_regenerate_id() internally or simulates it if the function does not exist.

### Vacuum/Optimize Database

During session garbage collection, if postgresql is detected, ADOdb can be set to run VACUUM. If mysql is detected, then optimize database could be called.You can turn this on or off using:

    $turnOn = true; # or false
    ADODB_Session::optimize($turnOn);

The default for optimization is it is disabled.

## More Info

Also see the core ADOdb documentation.