Saving Session in a Database

New Articles

Clean up Spilled Tar.

The PHP Java Extension.

The Mystery Of The Dead Speaker.

In a previous article we had a look at sessions; what they are and what they are not. We discussed how saving session data at the server is far more secure than using cookies.

When keeping session variable at the server they are usually placed in files, at a location specified by ssession.save_path, you can use a call to phpinfo() to find out where that is. Unfortunately if you are on a shared server you cannot rule out the possibility possibility of other users of your server sneaking a peek at these files.

Does that mean sessions should never be used? hardly. You can store your session information in a table of your database and effectively protect against peeping toms. In order to do so you need to override the following methods.


There are two other functions but they are not as important when you are using a database instead of a file. Before filling out the function bodies let's look at what our table ought to look like.

	CREATE TABLE sessions (
	session_id varchar(32) NOT NULL default '',
	session_data text NOT NULL,
	session_expiration timestamp NOT NULL,
	PRIMARY KEY  (session_id)

The table is obviously for mysql but you can easily obtain it's counterpart for postgresql by putting it through the mysql2pgsql converter. The table is populated in the on_session_write() method and the data is read back in on_session_read(). One very important factor to note is that you cannot use echo or similar calls to produce debugging output from with in the on_session_write() method. You have to use error_log() instead.

In the next step we need to register our session handler functions using the session_set_save_handler method call then you can safely follow up with the session_start() method as you normally would.

	session_set_save_handler("on_session_start",   "on_session_end",
				"on_session_read",    "on_session_write",
				"on_session_destroy", "on_session_gc");

Even though the session_set_save_handler() has six different parameters only the last four are really usefull to us.

download the code