Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

8.6. Storing Sessions in a Database

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.

Solution

Set session.save_handler to user in php.ini and use the pc_DB_Session class shown in Example 8-1. For example:

$s = new pc_DB_Session('mysql://user:password@localhost/db');
ini_get('session.auto_start') or session_start();

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 pc_DB_Session class stores the session data in a database. If this 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 they get sent to.

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

CREATE TABLE php_session (
  id CHAR(32) NOT NULL,
  data MEDIUMBLOB,
  last_access INT UNSIGNED NOT NULL,
  PRIMARY KEY(id)
)

If you want the table name to be different than php_session, set session.save_path in

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata