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

Putting it all together - 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.

TABLE OF CONTENTS:
  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
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

On the last few pages, we've talked about a bunch of little pieces that make up the sessions class.  I thought I would take a minute and give you the complete class in one shot.

class SessionManager {

   var $life_time;

   function SessionManager() {

      // Read the maxlifetime setting from PHP
      $this->life_time = get_cfg_var("session.gc_maxlifetime");

      // Register this object as the session handler
      session_set_save_handler( 
        array( &$this, "open" ), 
        array( &$this, "close" ),
        array( &$this, "read" ),
        array( &$this, "write"),
        array( &$this, "destroy"),
        array( &$this, "gc" )
      );

   }

   function open( $save_path, $session_name ) {

      global $sess_save_path;

      $sess_save_path = $save_path;

      // Don't need to do anything. Just return TRUE.

      return true;

   }

   function close() {

      return true;

   }

   function read( $id ) {

      // Set empty result
      $data = '';

      // Fetch session data from the selected database

      $time = time();

      $newid = mysql_real_escape_string($id);
      $sql = "SELECT `session_data` FROM `sessions` WHERE
`session_id` = '$newid' AND `expires` > $time";

      $rs = db_query($sql);                           
      $a = db_num_rows($rs);

      if($a > 0) {
        $row = db_fetch_assoc($rs);
        $data = $row['session_data'];

      }

      return $data;

   }

   function write( $id, $data ) {

      // Build query                
      $time = time() + $this->life_time;

      $newid = mysql_real_escape_string($id);
      $newdata = mysql_real_escape_string($data);

      $sql = "REPLACE `sessions`
(`session_id`,`session_data`,`expires`) VALUES('$newid',
'$newdata', $time)";

      $rs = db_query($sql);

      return TRUE;

   }

   function destroy( $id ) {

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

      db_query($sql);

      return TRUE;

   }

   function gc() {

      // Garbage Collection

                       

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

      db_query($sql);

      // Always return TRUE
      return true;

   }

}



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

blog comments powered by Disqus
   

PHP ARTICLES

- 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...
- PHP: Building Concrete Validators
- Sanitizing Input with PHP
- Executing Shell Commands with PHP
- Handling File Data with PHP
- File Security and Resources with PHP
- ArrayObject PHP Class Examples
- ArrayObject PHP Class: An Introduction
- Getting File System Data with PHP
- PHP Tools for Working with the File and Oper...
- Working with the File and Operating System w...
- PHP Proxy Patterns: Completing a Blog


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 6 - Follow our Sitemap

Dev Shed Tutorial Topics: