PHP
  Home arrow PHP arrow Page 5 - Storing PHP Sessions in a Database
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Storing PHP Sessions in a Database
By: Rich Smith
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 38
    2007-05-02


    Table of Contents:
  • Storing PHP Sessions in a Database
  • Why did they fail?
  • Overriding the session storage
  • Opening and closing the session
  • Reading and Writing Session Data
  • Cleaning up the session
  • Putting it all together
  • Finishing it up

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Storing PHP Sessions in a Database - Reading and Writing Session Data
    ( Page 5 of 8 )

    Okay.  We've intercepted PHP's session handling logic, and are systematically replacing it with our own.  After the open and close, the next to areas to address are the read and write methods.

    Let's first take a look at the read method:

            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;

            }

    In the above example, you will see that I used functions called db_query(), db_num_rows(), and db_fetch_assoc().  These functions are from the application I wrote this class for.

    But a close look will show you that when the function is called, the unique session identifier is passed along with it.  I then query the database to see if I can find a record for that session that has not expired.  If successful, you return the data to the calling program.

    Now take a look at the code to write the 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;

          }

    In the above example, you see that the write function is passed the unique session identifier, as well as the data to save to the database.  One thing to note is what we are doing with the time.  We grab the current time, then add to it the number of seconds that were defined in the constructor as lifetime.  So basically, each time the data is written, we reset the timeout.  So if your system is configured to expire sessions after 20 minutes of inactivity, this code supports it.

    You will also notice that, when writing the database, we utilize the replace function instead of an insert.  Replace  works exactly like an insert if the record already exists, or only updates it.

    And assuming all went well with the update, we return true.



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

       

    PHP ARTICLES

    - Using Directory Iterators to Build Loader Ap...
    - Using the spl_autoload() Functions to Build ...
    - Working Out of the Object Context to Build L...
    - Using the _autoload() Magic Function to Buil...
    - The Destruct Magic Function in PHP 5
    - The Autoload Magic Function in PHP 5
    - Developing a Recursive Loading Class for Loa...
    - The Sleep and Wakeup Magic Functions in PHP 5
    - Using the Clone Magic Function in PHP 5
    - Including Files Recursively with Loader Appl...
    - The Call Magic Function in PHP 5
    - Designing a Captcha System with PHP and MySQL
    - Using Static Methods to Build Loader Apps in...
    - The Isset and Unset Magic Functions in PHP 5
    - Advanced PHP Form Input Validation to Check ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 3 hosted by Hostway
    Stay green...Green IT