PHPBuilder - Custom Session Handlers in PHP4 Page 3

RSS Twitter

Custom Session Handlers in PHP4 - Page 3

by: Ying Zhang
July 30, 2000

A DBM Session Handler

Our first example is to write a customized session handler to save session data into a DBM file. (This is the session_dbm.php file from There are many reasons why you might want to do this, for example, if you were on a shared server from your ISP and you did not want your sessions mixing with those from their other client's scripts.
You must have DBM support in your PHP4 before you try this. If you do not things can get ugly, real ugly!
The approach we are going to take is to have one DBM file that stores all the session data (in case you don't know, a DBM file is like a very simple database that only holds key/value pairs). To fit this into the 6 functions:
  1. sess_open($sess_path, $session_name);
    We will open the DBM file in read/write mode by calling dbmopen(). The name of our DBM file will be /tmp/PHPSESSID unless you've modified the session path and name settinsg in your php.ini file.

  2. sess_close();
    In this function, we are simply going to close the DBM file properly by calling dbmclose().

  3. sess_read($key);
    Here we just call dbmfetch() to load up the session data associated with the session key. When loading up a session, it is necessary to make sure I'm not reading something that's been expired, so we will attach a timestamp to the session.

  4. Why? So that incase it has expired, but hasn't been removed out for whatever reason, we don't accidentally read in expired data. This would be a big no-no!
    We know that DBM only stores key/value pairs, so we have to glue the timestamp onto the value when writing the session data, and extract it when reading in the session data. Any session who's timestamp has been expired will be ignored. See the source code, it will make more sense there.

  5. sess_write($key, $val);
    To write a session, we will use the dbmreplace() function. Note from above that we want to save an expiry timestamp on the session, so we will attach it to the value.

  6. sess_destroy($key);
    Destroying a session is easy, we just call dbmdelete() to remove it from the session file.

  7. sess_gc($maxlifetime);
    Garbage collection is a bit nasty and intensive here, what we must do is loop through all the sessions that we've saved in our DBM file and delete the ones that have expired. This can be slow because we must loop through all the sessions stored in the file.

So now we've got a DBM session handler, cool! Now let's get these sessions stored in a MySQL database.

« Previous Page
Next Page »

Comment and Contribute

Your comment has been submitted and is pending approval.

Ying Zhang



(Maximum characters: 1200). You have characters left.