Saturday, March 10, 2007

PHP Sessions in a Load Balanced Environment

One thing that we struggle with in our server environment as many others do is doing load balancing and being able to sync session data between all the machines. Having one dedicated session space or server can be an option but that can get a little messy or expensive. So we added MySQL Sessions to the Simpl framework and it is easy as pie to use.

Originally adopted from Joseph Crawford but implemented completely in Simpl. Josephs was great except it seemed to be connected to a larger whole. The bits and pieces were there for the session but they just needed to be combined with a framework. Below is a fully featured example working and usable.

Prerequisits:
  • PHPSimpl
  • MySQL Database Connection
  • "session" Table
    CREATE TABLE `session` (
    `ses_id` varchar(32) NOT NULL,
    `last_access` int(12) unsigned NOT NULL,
    `ses_start` int(12) unsigned NOT NULL,
    `ses_value` text NOT NULL,
    PRIMARY KEY (`ses_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Used to store the sessions data';
Usage Steps:
  1. Download and copy Simpl to the web server.
  2. Define some base items
    // Directories
    // Always Include trailing slash "/" in Direcories
    define('DIR_ABS', '/usr/local/www/');
    define('FS_SIMPL', DIR_ABS . 'simpl/');
    define('FS_CACHE', DIR_ABS . 'cache/');

    // Enable Database Sessions
    define('DB_SESSIONS', true);

    // Database Connection Options
    define('DB_USER', 'username');
    define('DB_HOST', 'localhost');
    define('DB_PASS', 'password');
    define('DB_DEFAULT', 'site_data');
  3. Include the framework
    // Simpl Framework
    include_once(FS_SIMPL . 'simpl.php');
  4. Connect to the database
    // Make the DB Connection
    $db = new DB;
    $db->Connect();
  5. Use the $_SESSION super global just as you normally would and PHPSimpl does all the work for you.
The only modification may be the page cannot close the database connection since the _SESSION variable has to be written after the page is completely loaded and thus must still have the connection available.

Simpl and the $db object to all the hard work of redirecting the session data and pulling it from the database. No need to call a session_start() or even interact with the session table.

If you are interested in what the Session class looks like here is the source code:
Session.php

1 comment:

ehdesign said...

Brilliant!

Great job at putting together a rather difficult concept inside of a class and framework that is very easy to implement. I've looked around quite a bit for some way to handle session data on load balanced servers. This is far and away the simplest..

Thanks for your work.