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

Reading and Writing Session Data - 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



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

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: