Zend Framework: Storing session data in database

The reason behind saving session data in database is that data become more secure and can be easily retrieved later on.
Let’s look how simple and easy it is to save session data in database using Zend_Session_SaveHandler_DbTable in Zend Framework.
1. Creating database table for holding session data
Before writing code you will need to create a table in the database for holding session data. Execute the following query for this purpose.
CREATE TABLE `session` (
`id` char(32),
`modified` int,
`lifetime` int,
`data` text,
PRIMARY KEY (`id`)
);

2.Making necessary configuration in your bootstrap file.
You will only need only few lines of code in your bootstrap file.
After making database configuration in your bootstrap file, write the following code.
$config = array(
‘name’ => ‘session’,
‘primary’ => ‘id’,
‘modifiedColumn’ => ‘modified’,
‘dataColumn’ => ‘data’,
‘lifetimeColumn’ => ‘lifetime’
);
Zend_Session::setSaveHandler(new
Zend_Session_SaveHandler_DbTable($config));
Zend_Session::start();

In the $config array we tell the name of the table that will store the session information, primary key of the table, column that will store the session modification timestamp(*nix timestamp), column that will store the session data, and the column that save the information about how long the session will last.

After defining this configuration array we call setSaveHandler() method- static method, of the Zend_Session. This setSaveHandler() method accept Zend_Session_SaveHandler_DbTable object. Zend_Session_SaveHandler_DbTable take configuration array as an argument.

We have now done all the necessary configuration. The only thing we will need to do now is to start our session. Session can be started in the bootstrap file, however it’s not necessary for the session to be started here. You can start it in any controller you needed.

Anywhere in your controller, write
$namespace = new Zend_Session_Namespace();
$namespace->name = “Viral”;

and check your session table. The table will not only hold session id, but also the modified timestamp of when session was modified, life time of the session and the session data in special format.
Try it. Its really cool.