Home arrow PHP arrow Page 6 - Storing PHP Sessions in a Database

Cleaning up the session - PHP

There are many reasons to utilize sessions when creating a web-based application using PHP. Session information, by default, is stored in a file on your web server. But what if that becomes a problem? In this article, I'll talk about why you might want to move your PHP sessions to a database, and show you how to do it.

  1. Storing PHP Sessions in a Database
  2. Why did they fail?
  3. Overriding the session storage
  4. Opening and closing the session
  5. Reading and Writing Session Data
  6. Cleaning up the session
  7. Putting it all together
  8. Finishing it up
By: Rich Smith
Rating: starstarstarstarstar / 54
May 02, 2007

print this article



You can't properly have your own session handler without writing code to clean up after yourself.  The last two methods for our class will be the destroy and gc (garbage collection) methods.

When the session_destroy() function is called, it triggers a call to our destroy method.  Here's a look at the code:

      function destroy( $id ) {

         // Build query
         $newid = mysql_real_escape_string($id);
         $sql = "DELETE FROM `sessions` WHERE `session_id` =


         return TRUE;


The above logic is fairly straightforward.  The destroy method is called, passing the unique session identifier.  We then make a call to delete the record.  Boom, session information no longer exists.

Periodically, PHP will trigger a garbage collection routine, meant to handle the conditions where people left before the system got a chance to clean up their sessions.  Here's the code:

      function gc() {

         // Garbage Collection


         // Build DELETE query.  Delete all records who have
passed the expiration time
         $sql = 'DELETE FROM `sessions` WHERE `expires` <


         // Always return TRUE
         return true;


In the above query, we delete all records that are expired, and SHOULD have been deleted by the destroy method, but the method was apparently never called.  This garbage collection could be considered "self-maintenance," and stops you from needing to write a cronjob to keep your sessions table clean.

>>> More PHP Articles          >>> More By Rich Smith

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: