ADODB Session 2 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 document discusses the newer session handler adodb-session2.php. If you have used the older adodb-session.php, then be forewarned that you will need to alter your session table format. Otherwise everything is backward compatible. Here are the older docs for adodb-session.php.

Why Session Variables in a Database?

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:

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.

An alternative to using a database backed session handler is to use memcached. This is a distributed memory based caching system suitable for storing session information.

The Improved Session Handler

In ADOdb 4.91, we added a new session handler, in adodb-session2.php. It features the following improvements:

Usage is

include_once("adodb/session/adodb-session2.php");
ADOdb_Session::config($driver, $host, $user, $password, $database,$options=false);
session_start();

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

When the session is created in session_start( ), the global variable $ADODB_SESS_CONN holds the connection object.

The default name of the table is sessions2. If you want to override it:

include_once("adodb/session/adodb-session2.php");
$options['table'] = 'mytablename';
ADOdb_Session::config($driver, $host, $user, $password, $database,$options);
session_start();

ADOdb Session Handler Features

Session Handler Files

There are 3 session management files that you can use:

adodb-session2.php        : The default
adodb-cryptsession2.php : Use this if you want to store encrypted session data in the database
adodb-session-clob2.php : Use this if you are storing DATA in clobs and you are NOT using oci8 driver

Usage Examples

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

 
include_once("adodb/session/adodb-session2.php");
$driver = 'mysql'; $host = 'localhost'; $user = 'auser'; $pwd = 'secret'; $database = 'sessiondb';
ADOdb_Session::config($driver, $host, $user, $password, $database,$options=false);
ADOdb_session::Persist($connectMode=false);
session_start();

The parameter to the Persist( ) method sets the connection mode. You can pass 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-session2.php:

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

$driver = 'mysql'; $host = 'localhost'; $user = 'auser'; $pwd = 'secret'; $database = 'sessiondb'; ADOdb_Session::config($driver, $host, $user, $password, $database,$options=false);
adodb_sess_open(false,false,$connectMode=false);
session_start();

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

  
include('adodb/session/adodb-session2-clob2.php');
$driver = 'oci8'; $host = 'localhost'; $user = 'auser'; $pwd = 'secret'; $database = 'sessiondb'; ADOdb_Session::config($driver, $host, $user, $password, $database,$options=false);
adodb_sess_open(false,false,$connectMode=false);
session_start();

Installation

1. Create this table in your database. Here is the MySQL version:

  
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 DEFAULT '',
	  PRIMARY KEY ( sesskey ) ,
	  INDEX sess2_expiry( expiry ),
	  INDEX sess2_expireref( expireref )
)

For PostgreSQL, use:

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 );

Here is the Oracle definition, which 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 $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.

Synchronizing Page Frames

Sometimes you need to load multiple pages in a frameset and make sure that the session variables are synchronized. For example we have a page frame.php with an iframe child1.php:

   frame.php
       child1.php

Assume frame.php receives some $_GET variables and it updates the $_SESSION variables in memory. However the $_SESSION variables are only updated in the database when the page ends. So is possible that child1.php will still have the old $_SESSION variables.

We can fix this by using the php function session_commit:

<?php
session_start();
.
# do any required processing...

session_commit();

# now session variables have been saved to the database, and child1.php will get the latest $_SESSION variables.
?>
<html>
	<body>
	<iframe src=child1.php>
	</iframe>
	</body>
</html>

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

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.

Session Cookie Regeneration: 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:

	include('path/to/adodb/session/adodb-session2.php');
	
	session_start();
	# Approximately 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 is optimization is disabled.

Backwards Compatability

The older method of connecting to ADOdb using global variables is still supported:

 $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-session2.php'); 

In the above example, the only things you need to change in your code to upgrade is

More Info

Also see the core ADOdb documentation. And if you are interested in the obsolete adodb-session.php, see old session documentation.

Free online source of motorcycle videos, pictures, insurance, and Forums.The Dodge intrepid is a large four-door, full-size, front-wheel drive sedan car model that was produced for model years 1993 to 2004 .The Mazda 323 name appeared for the first time on export models 323f.Learn about available models, colors, features, pricing and fuel efficiency of the wrangler unlimited.The official website of American suzuki cars.Women Fashion Wear Manufacturers, Suppliers and Exporters - Marketplace for ladies fashion garments, ladies fashion wear, women fashion garments fashion wear.New Cars and Used Cars; Direct Ford new fords.Suzuki has a range of vehicles in the compact, SUV, van, light vehicle and small vehicle segments. The Suzuki range includes the Grand suzuki vitara.View the Healthcare finance group company profile on LinkedIn. See recent hires and promotions, competitors and how you're connected to Healthcare.bmw 6 series refers to two generations of automobile from BMW, both being based on their contemporary 5 Series sedans.Read expert reviews of the nissan van.Read reviews of the Mazda protege5.Locate the nearest Chevrolet Car chevy dealerships.Top Searches: • nissan for sale buy nissan.Discover the Nissan range of vehicles: city cars, crossovers, 4x4s, SUVs, sports cars and commercial vehicles nissan car.GadgetMadness is your Review Guide for the Latest new gadget.Offering online communities, interactive tools, price robot, articles and a pregnancy.Time to draw the winner of the Timex iron man health.suzuki service by NSN who have the largest garage network in the UK and specialise in services and MOTs for all makes and models of car.Site of Mercury Cars and SUV's. Build and Price your 2009 Mercury Vehicle. See Special Offers and Incentives mercurys cars.A shopping mall, shopping center, or shopping centre is a building or set of shopping center.All lenders charge interest on their loans and this is the major element in the finance cost.The Web site for toyota center in houston tx.New 2009, 2010 subarus.Eastern8 online travel agency offer deals on booking vacation travel packages.Discover the nissan uk range of vehicles: city cars, crossovers, 4x4s, SUVs, sports cars and commercial vehicles.Welcome to Grand Cherokee UnLimited's zj.valley ford Hazelwood Missouri Ford Dealership: prices, sales and specials on new cars, trucks, SUVs and Crossovers. Pre-owned used cars and trucks.Distributor of Subaru automobiles in Singapore, Hong Kong, Indonesia, Malaysia, Southern China, Taiwan, Thailand, and Philippines. impreza wrx sti.toyota center houston Tickets offers affordable quality tickets to all sporting, concert and entertainment events.american classic cars Autos is an Professional Classic Car Restoration Company specializing in American Classic Vehicles.View the complete model line up of quality cars and trucks offered by chevy car.Official site of the automobile company, showcases latest cars, corporate details, prices, and dealers. hyundai motor.Research Kia cars and all new models at Automotive.com; get free new kia.The 2009 all new nissan Cube Mobile Device is here. Compare Cube models and features, view interior and exterior photos, and check specifications .Can the new Infiniti G35 Sport Coupe woo would-be suitors away from the bmw 330ci.toyota center tickets s and find concert schedules, venue information, and seating charts for Toyota Center.Electronics and gadgets are two words that fit very well together. The electronic gadget.Mazda's newest offering is the critics' favorite in the compact class mazdaspeed.Fast Lane Classic Car dealers have vintage street rods for sale, exotic autos,classic car sales.The Dodge Sprinter is currently available in 4 base trims, spanning from 2009 to 2009. The Dodge sprinter msrp.Welcome to masda global website .The kia carnival is a minivan produced by Kia Motors.Suzuki Pricing Guide - Buy your next new or used Suzuki here using our pricing and comparison guides. suzuki reviews.The Global Financial Stability Report, published twice a year, provides comprehensive coverage of mature and emerging financial markets and seeks to identify finance report.Companies for honda 250cc, Search EC21.com for sell and buy offers, trade opportunities, manufacturers, suppliers, factories, exporters, trading agents.Complete information on 2009 bmw m3 coupe.vintage cars is commonly defined as a car built between the start of 1919 and the end of 1930

Davidian church in Waco

King George

dating sites

music files

used car

hard dick

pull away

naked body

Australian agriculture

get started

fire department

better way

six speed

online marketing

condo hotel

right now

maximum speed

Tokyo Japan

free online

car buying

waited until

feel better

FTP hosting

video conferencing

great way

truck driver

take control

Vision Video

good health

is highly subjective

massive immigration

healthy eating

ass hole

customer service

little bit

low libido

Windows Vista

good quality

trance personage

Port Authority

waited until

big city

Kegel exercises

Online Casino

home work

Lectures in however

up use

special relativity

pay attention

recent decades

Indigenous Australians

front wheel

set of resource constraints

scuba diving

numeric character

online community

could use

over again

airsoft gun

cars which

constitutional matters

London Underground

hard work

loud moan

long way

adult dog

Nuttall's book Bomb

should help

Queen Elizabeth

dry dog

left behind

lawn business

interest rate

search engine

real life

right now

right now

is also often

a certain extent

graduate students

moved around

get away

good chance

home based

didnt know

facial hair

tight ass

regular basis

and were only

always advisable

take advantage

animal jewelry

vacation spots

LED lights

Erica Janet

data entry

individuals who were

iPod video

watch satellite

makes sense

long term

Stimulated Emission of Radiation

bottom line

felt great
Find and buy toyota park.Official site of the 2009 Jeep wrangler.Visit Subaru of America for reviews, pricing and photos of impreza.2006 Nissan 350Z highlights from Consumer Guide Automotive. Learn about the 2006 nissan 350z.Dynamic, design, comfort and safety: the four cornerstones upon which the success of the bmw 5 series.Find and buy toyota center kennewick.Contact: View company contact information fo protege.What does this mean for legacy.The website of American suzuki motorcycle.The site for all new 2009 chevy.Use the Organic natural food stores.Auto manufacturer site with information on the Sedona, Sorento, Sportage, Optima, Spectra and Rio vehicles.kia.Get more online information on hyundai getz.Find and buy used nissan 350z.Kia cars, commercial vehicles, dealers, news and history in Australia. kia com.Site for Ford's cars and minivans, trucks, and SUVs. Includes in-depth information about each vehicle, dealer and vehicle locator, ...fords dealers.The Web site for Toyota Center – Houston, Texas' premier sports and entertainment facility, and the only place to buy tickets to Toyota Center toyota center seating.Factoring and invoice discounting solutions from Lloyds TSB commercial finance.Read Fodor's reviews to find the best travel destinations, hotels and restaurants. Plan your trip online with Fodor's.travel guide.Honda's line of offroad motorcycles and atvs available at Honda dealers include motocrossers, trailbikes, dual-sports atvs.Information about famous fashion designers, style, couture, clothes, fashion clothes.Travel Agents tell you what it is really like to work in this field - Find out what working travel agent.Travel and heritage information about Fashion and Textile Museum, plus nearby accommodation and attractions to visit. Part of the Greater London Travel fashion.Get buying advice on the Mazda rx8

jollibee foods corporation mission and vision

Labor Party

mistic drinks and juices

credit card

seminario reina valera

could keep

guy patterson puget sound washington

new home

treatments of bunyons

well worth

marks and spencer board

long term

jenny gilbertson model fargo

would give

intel r 82801aa ac 97 update

sucked hard

heritage animal hospital dundee mi

would need

weight shift trike sale

search engines

chloe nicole thumbnail

hard work

gelatin food molds

constitutional matters

yiffer fox

craft supplies

piccadilly restaurant baked chicken recipe

each other

leslie thomas

Cologne review

jeffrey allens bloomington il

little bit

panini bread recipes

the pragmatic theory

social stories and trying new foods

said looking

unilateral tonsil enlargement

right now

chinese sweet ball recipe tong yuen

pay off

eastside marios menu

long legs

577 t rex rifle overview

gas mileage

viejas culonas

fiber optics

mike morhaime bio

toll booths

newstar bambi videos

Park City

puso ng saging recipe

music with which

nidol tablet

trouble shout

gortex coats

wrapped around

mastasia type of sites

jewelry photography

trillians fakes

sentiment without

thomas layouts

vehicles like

the breakfast club sociological perspective

of her sittings and personal

ancient chinese lotus

companies offer

digital concepts cyber pix driver

web pages

jennings truck centre tullamore

natural gas

tracy beams

high technology

easy rider biker magazine

unsecured loans

vacation planning itinerary template

the knowledge of which on

rubics cube cheats

pet food

african food webs diagrams

grunge nu metal

cream of brocoli cheese soup recipes

rheumatoid arthritis

blythe hotel southwold

Big Ticket

illumina records scam

him back

flying blue

way through

achaea quest guides

year old

los solesitos

high schools

hairy gurlz

great way

chicken casadilla

affiliate program

upgrade farsi starsat x50

broke case middle

teletabies

real estate

jason williams murder trial

become true

new orleans seafood ruby tuesday recipe

rheumatoid arthritis

turandot story

feel like

johnny carinos sangria recipe

cock off

meals on wheels orange county california

acid reflux

olivia de bernardis

couldnt think

hollicost

New York

shannon sullivan s

nuclear power

brainiac dolly girl

million people

carn evil soundtrack

carpal tunnel

harley cam tensioner

Atlantic City

hiromi oshima playboy issue

computers which

microsoft outlook error 0x80040900

five feet

patricia farinelli

local Italian

leon medical center miami

Inc Headquartered

recipes from the czech republic

help keep

toyota portal axle conversion kit

integral part

webco brakes

ultraviolet light

bishop dwight pate

look good

oak park gymnastics center

ice cubes

elderbeerman dept store

national park

celcius to faranheit chart

chart hat sell

characteristics of volvox

wine gift

dudley s drc 28

good quality

cake recipes for diabetics

dog food

mini steros

kissed passionately

bushcraft canada

result burn hill

ledyard cayuga county fathers

over million

recipe for date squares

daily basis

neffie keyshia cole s sister

nasal problem

skinvideos net

surface deep

ezteens net

loved hearing

cemi concept ii

cold air

kellys music roanoke

community radio

nvidia geforce model p118

pop culture

pseudocyesis

pet food

florida trawlers for sale

ebook Craft

sharon lush cleaning advice

Dmitri Shostakovich

satellite m115 s3094 notebook

credit card

maryse manios

wait plan figure star

young defloration

of that knowledge

easy tiramisu recipe lady fingers

unlimited music

mikael jakson

right now

koch homes maryland

good way

vinnie zucchini toronto

look good