Store PHP Session Data in a Database with ADODB

Storing session data in a database is a great way to plan for scaling your application into a load balanced architecture.

The use of session data is common in websites and applications. Typically a cookie is set in the client's browser that refers to data being stored on a server. This extends a website beyond the stateless model the HTTP protocal is based on. Storing information from a previous request allows applications to "remember" what the end user did. This allows your website to handle things like login status.

When your website grows beyond the capacity of a single server, changing the way session data is handled should be considered. In a load balanced configuration you don't want your session data to be lost when any one server becomes inaccessible. Storing your sessions in a database is a great way to handle it. This creates separation between your application servers and the location of your session data.  Separating this data allows you to load balancing your servers without fear of a poor user expereince when a single instance is removed from the cluster. Using a database is also more secure than the traditional file based method open to unscrupulous attack.

Luckily ADODB offers a very easy way to move your PHP session data into a database.

Refer to Building a Database Agnostic PHP Application with ADODB for the basic installation instructions.

Create the Database Table to Store your Session Data

For MySql run the command below.

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

Configure the Application

Include the adodb-session2.php file to make the session management classes available.

require_once("adodb/session/adodb-session2.php");

Configure the session before starting the session.

ADOdb_Session::config($driver, $host, $user, $password, $database,$options);
$ADODB_SESSION_EXPIRE_NOTIFY = array('userid','NotifyFn');
function NotifyFn($userid,$sessionkey){
#this routine is processed at session expiration
};

Session Usage

Start the session

session_start();

Login user 12345

$_SESSION['userid'] = 12345;

Logout user 12345

unset($_SESSION['userid']);