Introduction

PHP4 is packed with good features. One of the most popular is session variables. These are variables that persist throughout a session, as the user moves from page to page. Session variables are great holders of state information and other useful stuff.

PHP4's session variables are stored in files by default. However for true scalability, it is better to store this data in a database.

For connecting to the database, I decided to use ADODB, a database wrapper library, for true cross-platform database independence.

ADODB supports many databases, including MySQL, PostgreSQL, Oracle, Microsoft SQL Server, Access, FoxPro, Interbase, ODBC and ADO.

ADODB is available from http://php.weblogs.com/adodb and the latest version of the following session code is available at http://php.weblogs.com/adodb-sessions

Installation

For ADODB's implementation, you need to create a table called sessions in your database. It should have the following structure:

 create table sessions (
       SESSKEY char(32) not null,
       EXPIRY int(11) unsigned not null,
       DATA text not null,
      primary key (sesskey)
}
Then modify the following variables in the adodb-session.php file:

 $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';

Usage

Here is example of how it is used. Click on the refresh button to see the AVAR variable increase.

GLOBAL $HTTP_SESSION_VARS;
include('adodb.inc.php');
include('adodb-session.php');
session_start();
session_register('AVAR');
$HTTP_SESSION_VARS['AVAR'] += 1;
print "variable={$HTTP_SESSION_VARS['AVAR']}";
=========================================== SOURCE CODE
<?php
/*
V0.83 12 Dec 2000 (c) 2000 John Lim (jlim@natsoft.com.my). All rights reserved.
  Released under Lesser GPL library license. 
  See License.txt. 
  

  Requires the ADODB class library, 
  which is available at http://php.weblogs.com/adodb
  ======================================================================
  
 This file provides PHP4 session management using the 
 ADODB database wrapper library.
 
 Example
 =======
 	GLOBAL $HTTP_SESSION_VARS;
	include('adodb.inc.php');
	include('adodb-session.php');
	session_start();
	session_register('AVAR');
	$HTTP_SESSION_VARS['AVAR'] += 1;
	print "\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}";

 
 Installation
 ============
 1. Create a new database in MySQL or Access "sessions" like so:

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

  2. Then define the following parameters in this file:
  	$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';
*/

if (!defined('_ADODB_LAYER')) {
	include ('adodb.inc.php');
}

/* SET THE FOLLOWING PARAMETERS */
$ADODB_SESSION_DRIVER='ado_access';
$ADODB_SESSION_CONNECT=
 'PROVIDER=Microsoft.Jet.OLEDB.4.0;'
  .'DATA SOURCE=d:\inetpub\wwwroot\php\phplens\adodb.mdb;';
$ADODB_SESSION_USER ='';
$ADODB_SESSION_PWD ='';
$ADODB_SESSION_DB ='';



if (!defined('ADODB_SESSION')) {

 define('ADODB_SESSION',1);
// configuration file in ../phpconfig/ADODB/config.inc.php
GLOBAL 	$ADODB_SESSION_CONNECT, 
	$ADODB_SESSION_DRIVER,
	$ADODB_SESSION_USER,
	$ADODB_SESSION_PWD,
	$ADODB_SESSION_DB,
	$ADODB_SESS_CONN,
	$ADODB_SESS_LIFE,
	$ADODB_SESS_INSERT; 

$ADODB_SESS_LIFE = get_cfg_var("session.gc_maxlifetime");


function adodb_sess_open($save_path, $session_name) 
{
GLOBAL 	$ADODB_SESSION_CONNECT, 
	$ADODB_SESSION_DRIVER,
	$ADODB_SESSION_USER,
	$ADODB_SESSION_PWD,
	$ADODB_SESSION_DB,
	$ADODB_SESS_CONN;
		
	if ($ADODB_SESS_CONN) return true;
	ADOLoadCode($ADODB_SESSION_DRIVER);
	
	$ADODB_SESS_CONN = ADONewConnection($ADODB_SESSION_DRIVER);
	#$ADODB_SESS_CONN->debug =true;
	$ADODB_SESS_CONN->PConnect($ADODB_SESSION_CONNECT,
        $ADODB_SESSION_USER,$ADODB_SESSION_PWD,
        ADODB_SESSION_DB);
	
	return true;
}

function adodb_sess_close() 
{
global $ADODB_SESS_CONN;

	if ($ADODB_SESS_CONN) $ADODB_SESS_CONN->Close();
	return true;
}

function adodb_sess_read($key) 
{
	global $ADODB_SESS_CONN,$ADODB_SESS_INSERT;
	
	$rs = $ADODB_SESS_CONN->Execute(
  "SELECT data FROM sessions WHERE sesskey = '$key' AND expiry >= " . time());
	if ($rs) {
		$v = $rs->fields[0];
		if ($rs->EOF) $ADODB_SESS_INSERT = true;
		$rs->Close();
		return ($v) ? $v : '';
	}
	$ADODB_SESS_INSERT = true;
	return false;
}

function adodb_sess_write($key, $val) 
{
	global $ADODB_SESS_INSERT,$ADODB_SESS_CONN, $ADODB_SESS_LIFE;


	$expiry = time() + $ADODB_SESS_LIFE;

	$qry = "UPDATE sessions SET expiry=$expiry,data="
 .$ADODB_SESS_CONN->qstr($val,get_magic_quotes_runtime())." WHERE sesskey='$key'";
	$rs = $ADODB_SESS_CONN->Execute($qry);

	if ($rs) $rs->Close();
	if ($ADODB_SESS_INSERT || $rs === false) {
		$qry = "INSERT INTO sessions VALUES ('$key',$expiry,"
.$ADODB_SESS_CONN->qstr($val,get_magic_quotes_runtime()).")";
		$rs = $ADODB_SESS_CONN->Execute($qry);
		if ($rs) $rs->Close();
	}

	return isset($rs);
}

function adodb_sess_destroy($key) 
{
	global $ADODB_SESS_CONN;

	$qry = "DELETE FROM sessions WHERE sesskey = '$key'";
	$rs = $ADODB_SESS_CONN->Execute($qry);
	if ($rs) $rs->Close();
	return $rs;
}

function adodb_sess_gc($maxlifetime) {
	global $ADODB_SESS_CONN;

	$qry = "DELETE FROM sessions WHERE expiry < " . time();
	$rs = $ADODB_SESS_CONN->Execute($qry);
	if ($rs) $rs->Close();
	return true;
}


session_set_save_handler(
	"adodb_sess_open",
	"adodb_sess_close",
	"adodb_sess_read",
	"adodb_sess_write",
	"adodb_sess_destroy",
	"adodb_sess_gc");
}

/*  TEST SCRIPT -- UNCOMMENT */

if (0) {
GLOBAL $HTTP_SESSION_VARS;

	session_start();
	session_register('AVAR');
	$HTTP_SESSION_VARS['AVAR'] += 1;
	print "\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}";
}

?>