Saving PHP Sessions to MySQL

In most cases, websites don’t necessarily need to be managed by sessions that end as soon as the user closes his browser. Most websites even offer to keep their session alive for whatever amount of time. This is really less of a hassle for your users and adds to the positive user experience.

Learning what not to do

On TMT, I used to handle sessions manually by storing the encrypted value of the user’s id in a cookie. That’s is highly unrecommended for security reasons as its fairly easy to hack your way around using an id that isn’t yours (and which might be the administrator’s!). I experimented by storing some ‘unique’ values in MySQL to have better validation when decrypting the cookie, but since you can spoof most $_SERVER values (which provides the user’s IP), it really wasn’t good enough.

Hardcore PHP-ing

You can override the whole session object using PHP’s session_set_save_handler() function. Basically, you re-program what the object does when it reads and writes session values or when it destroys itself.

Instead of writing the session values to a file on the server as the default behavior is set to do, you can redirect the data handling to an insert or update query in your favorite database.

Advantages

The most obvious advantage is that you can keep the sessions alive as long as your server is live, more or less. You can also change the condition of how session expiration are done. For instance, through a simple MySQL query, TMT sessions can be kept for one week before being destroyed if no activity is logged.

I’ve read it’s safer to store session values that way too, as a possible hacker would need the database’s password to access it. While I’m not sure how harder this system actually makes it for hackers, I really feel safer to use PHP’s native object rather than a shaky class I would have written.

Fully using PHP’s native session object allows more flexibility as you can handle a session of a user that is not logged in. You can therefore validate that the user is human and not a spam bot, save the user’s preferred language or do whatever else your website offers as possible features. In my previous horrible system, it wasn’t even a possibility.

Examples

Apart from stalker at ruun dot de’s very good comment on PHP.net’s documentation page, I found Tony Marston’s version of the object. The latter is harder to grasp as he uses his own object-oriented system to get database data — that’s good practice, but a bit harder to learn from. You can also see TMT’s class in our SVN repository.

The important thing is just to understand what you’re trying to do rather than copy pasting each of our codes. TMT’s only started working once I got the concept.

Comments are closed.