Saving PHP Session Data to a Database

by Tony Marston
TonyMarston.net
Friday, 22nd September 2006

Define session handler

This is as described in the manual for the session_set_save_handler() function. These lines must come before the session_start() function.

require_once 'classes/php_session.class.inc';
$session_class = new php_Session;
session_set_save_handler(array(&$session_class, 'open'),
array(&$session_class, 'close'),
                         array(&$session_class, 'read'),
                         array(&$session_class, 'write'),
                         array(&$session_class, 'destroy'),
                         array(&$session_class, 'gc'));

Notice that the arguments describe methods in a class and not stand-alone functions.

Conclusion

As you should be able to see it is a relatively straightforward process to switch the recording of session data from ordinary disk files to a database table. This overcomes the drawbacks inherent with ordinary disk files:

  1. The session data is more secure as a potential hacker must be able to log into the database before he can access anything.
  2. The use of multiple servers would not create a problem as all session data now resides in a single central place and is accessible by all servers.
  3. It is much easier to query the database should the site administrator require information about current sessions or current users.

Options:
Printer Friendly
Email Friend

About The Author:

I have been a software engineer, both designing and developing, since 1977. I have worked with a variety of 2nd, 3rd and 4th generation languages on a mixture of mainframes, mini- and micro-computers. I have worked with flat files, indexed files, hierarchical databases, network databases and relational databases. The user interfaces have included punched card, paper tape, teletype, block mode, CHUI, GUI and web. I have written code which has been procedural, model-driven, event-driven, component-based and object oriented. I have built software using the 1-tier, 2-tier, 3-tier and Model-View-Controller (MVC) architectures. After working with COBOL for 16 years I switched to UNIFACE in 1993, starting with version 5, then progressing through version 6 to version 7. In the middle of 2002 I decided to teach myself to develop web applications using PHP and MySQL.

Developer Categories



Developer Tutorials
ASP
CGI & Perl
CSS
Flash
HTML
Java
JavaScript
MySQL
PHP
Python
XML

Developer Documentation

Developer Tools



Search our Developer Tutorials
  The DevSyndicate Network