Recipe 11.4. Storing Sessions in a Database


11.4.1. Problem

You want to store session data in a database instead of in files. If multiple web servers all have access to the same database, the session data is then mirrored across all the web servers.

11.4.2. Solution

Use a class or a set of functions in conjunction with the session_set_save_handler( ) function to define database-aware routines for session management. For example, use PEAR's HTTP_Session package for convenient database session storage:

<?php require_once 'HTTP/Session/Container/DB.php'; $s = new HTTP_Session_Container_DB('mysql://user:password@localhost/db'); ini_get('session.auto_start') or session_start(); ?>

11.4.3. Discussion

One of the most powerful aspects of the session module is its abstraction of how sessions get saved. The session_set_save_handler( ) function tells PHP to use different functions for the various session operations such as saving a session and reading session data.

The PEAR HTTP_Session package provides classes that take advantage of PEAR's DB, MDB, and MDB2 database abstraction packages to store session data in a database. If the database is shared between multiple web servers, users' session information is portable across all those web servers. So if you have a bunch of web servers behind a load balancer, you don't need any fancy tricks to ensure that a user's session data is accurate no matter which web server she gets sent to.

To use HTTP_Session_Container_DB, pass a data source name (DSN) to the class when you instantiate it. The session data is stored in a table called sessiondata whose structure is:

CREATE TABLE sessiondata (   id CHAR(32) NOT NULL,   data MEDIUMBLOB,   expiry INT UNSIGNED NOT NULL,   PRIMARY KEY (id) );

If you want the table name to be different than sessiondata, you can set a new table name with an options array when instantiating the HTTP_Session_Container_DB class:

<?php require_once 'HTTP/Session/Container/DB.php'; $options = array(   'table'  => 'php_session',   'dsn'    => 'mysql://user:password@localhost/db' ); $s = new HTTP_Session_Container_DB($options); ini_get('session.auto_start') or session_start(); ?>

To customize an aspect of how the container classes provided by HTTP_Session manipulate session data, you can modify the behavior by extending one of the container classes. This is better than writing a completely new session handler class.

11.4.4. See Also

Documentation on session_set_save_handler( ) at http://www.php.net/session-set-save-handler; information on installing PEAR packages, such as HTTP_Session, is covered in Recipes 13.12.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net