Using Sessions in PHP can be extremely useful, and is almost a requirement when making dynamic web applications. However, sessions do have drawbacks, and one of these is security. When a session is created, it gets written to a file on the server. If the server you are using has other hosting accounts, they will also be using the same directory as your session files. If you’re storing any personal information about your website visitors, you have quite a serious problem.
For this reason, I would strongly suggest storing your sessions in a database. This tightens security considerably, and also allows for a wealth of new possibilities, such as running SQL queries on the database to see how many users are logged in. It is also the only logical solution if you are using multiple servers that need to access the same user sessions.
It’s quite simple to make the change to storing sessions in the database, and all you need for the following example is PHP 5 and MySQL.
First of all you will need to include the following PHP code in every page on your website that needs database or session access. It should be the very first thing included on every page.
Don’t forget to change your database details!
Secondly, you will need the following at the bottom of each page:
//You must call the following at the bottom of every page that uses sessions session_write_close();
The last thing you need to do is to create the database table to store the sessions. Here is the SQL to do so for a MySQL database:
CREATE TABLE `sessions` ( `id` char(32) NOT NULL, `data` longtext NOT NULL, `last_accessed` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Tags: database, PHP, security, session, sessions
