PHP
  Home arrow PHP arrow Page 4 - Using Session Handling Objects to Main...
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
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

Using Session Handling Objects to Maintain the State of Applications with PHP Sessions
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 22
    2006-05-10

    Table of Contents:
  • Using Session Handling Objects to Maintain the State of Applications with PHP Sessions
  • A procedural implementation of the “session_set_save_handler()” function
  • Developing an object-oriented session management module
  • Coding the session handling class

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb 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


    Using Session Handling Objects to Maintain the State of Applications with PHP Sessions - Coding the session handling class


    (Page 4 of 4 )

    Since I already defined the structure of the pertinent session handling class, specifically writing each of its methods is just a matter of translating the callback functions defined for the procedural session handling approach into class methods. Even when I’m pretty sure that you know how the complete class will look, I’ll do most of the hard work for you. Please, take a look at the definition of this class:

    class SessionHandler {
        function SessionHandler(){

            session_set_save_handler(array
    (&$this,'openSession'),array(&$this,'closeSession'),array
    (&$this,'readSession'),array(&$this,'writeSession'),array
    (&$this,'destroySession'),array(&$this,'gcSession'));
        }
        function openSession($sessionPath,$sessionName){
            return true;
        }
        function closeSession(){
            return true;
        }
        function readSession($sessionId){
            global $db;
            // escape session ID
            if(!get_magic_quotes_gpc()){
                $sessionId=mysql_real_escape_string($sessionId);
            }
            $result=$db->query("SELECT sessiondata FROM sessions
    WHERE sessionid='$sessionId' AND expiry > NOW()");
            if($result->countRows()>0){
                $row=$result->fetchRow();
                return $row['sessiondata'];
            }
            // return empty string
            return "";
        }
        function writeSession($sessionId,$sessionData){
            global $db;
            $expiry=time()+get_cfg_var('session.gc_maxlifetime')-1;
            // escape session ID & session data
            if(!get_magic_quotes_gpc()){
                $sessionId=mysql_real_escape_string($sessionId);
            }
            $result=$db->query("SELECT sessionid FROM sessions WHERE
    sessionid='$sessionId'");
            // check if a new session must be stored or an existing
    one must be updated 
            ($result->countRows()>0)?$db->query("UPDATE sessions SET
    sessionid='$sessionId',expiry='$expiry',sessiondata=
    '$sessionData'WHERE sessionid='$sessionId'"):$db->query("INSERT
    INTO sessions(sessionid,expiry,sessiondata) VALUES
    ('$sessionId','$expiry','$sessionData')");
            return true;
        }
        function destroySession($sessionId){
            global $db;
            // escape session ID
            if(!get_magic_quotes_gpc()){
                $sessionId=mysql_real_escape_string($sessionId);
            }
            $db->query("DELETE FROM sessions WHERE
    sessionid='$sessionId'");
            return true;
        }
        function gcSession($maxlifetime){
            global $db;
            $db->query("DELETE FROM sessions WHERE expiry < NOW()");
            return true;
        }      
    }

    As you can see, the above class now includes each of the previous callback functions directly as methods, which maintain the same original definition. Of course, the most important thing to note here is the inclusion of the “session_set_save_handler()” function inside the class constructor, and the corresponding registration of each method to be appropriately called.

    In this case, the “session_set_save_handler()” function accepts an input array, containing both a self reference to the “SessionHandler” object (represented by the &$this pointer) and the name of the callback method to be used. The following expression illustrates this condition:

    session_set_save_handler(array(&$this,'openSession'),array
    (&$this,'closeSession'),array(&$this,'readSession'),array
    (&$this,'writeSession'),array(&$this,'destroySession'),array
    (&$this,'gcSession'));

    Now that you know how the “SessionHandler” class looks, here’s a simple implementation of it, using the pair of additional MySQL processing classes shown before:

    // include classes
    require_once 'mysqlclass.php';
    require_once 'resultclass.php';
    // connect to MySQL
    $db=&new MySQL(array('host'=>'localhost','user'=>'user',
    'password'=>'password','database'=>'database'));
    // instantiate new 'SessionHandler' object
    $sessionHandler=&new SessionHandler;
    session_start();
    // register some session variables
    $_SESSION['firstname']='Alejandro';
    $_SESSION['lastname']='Gervasio';

    That’s it. The above script demonstrates how to integrate a “SessionHandler” object with the other MySQL processing classes, in order to implement a MySQL-driven session management module. Notice that after instantiating a new session handler object, the session is started normally, by the “session_start()” function, as one would expect using flat files. Definitely, the above source code now looks very compact and readable, since all the hard work for managing sessions is done behind the scenes, by the methods of the useful “SessionHandler” class.

    At this point, you hopefully learned how to create a session handling class, which encapsulates all the required methods for implementing a MySQL-based session management module. However, due to their versatility, the methods can be easily rewritten, in order to use another RDBMS. As with most things in Web programming, this will depend on your own development requirements.

    To wrap up

    Unfortunately, this series has now concluded. Over its different parts, I covered the most relevant aspects of session management in PHP, starting out with the basics of how to create, use and destroy sessions, and additionally explaining the correct implementation of advanced functions, such as “session_set_save_handler()”, which can be used to develop custom session modules, similar to the one I built before.

    I hope you find the material I provided you in this series to be useful, so you can use it for extending the boundaries of your grounding in PHP sessions. Meet you in the next PHP series!


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · Over the last part of this series, you´ll learn how to build session handling...
       · Hi Alejandro,In this series you've done an excellent job of illustrating how to...
       · Hi friend,Thank you for your kind comments on my PHP series. I really appreciate...
       · Hi again,I am on APache and can write .htaccess files, but what can I change in...
       · Hello Craig,The Apache site has a lot of info about .htacess files. There are...
       · Again you did some awesome work. I look forwark to read what you wrote on other...
       · Hi Sig again,I read your previous comment and I thank for you for this one too....
     

       

    PHP ARTICLES

    - Using Aliases and the Autoload Function with...
    - Authentication Scripts for a User Management...
    - Utilizing the Use Keyword for Namespaces in ...
    - Building a User Management Application
    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Sub Classing Exceptions in PHP 5
    - Building a Content Management System with Co...
    - Filters and Login Systems for Web Applicatio...

     
    Application Delivery: Everything You Wanted to Know, but Didn`t Know You Needed to Ask
    A comprehensive guide to examining the topics of Wide-area Data Services and app....

     
    Best Practices: Safe and Secure Hardware Asset Recovery
    Companies increasingly must meet EPA and local requirements for the disposal of ....

     
    Managing SSL Security in Multi-Server Environments
    Read this white paper to learn how to simplify management of your organization's....

     
    Open Source Security Myths
    Open Source Software (OSS) is computer software whose source code is available t....

     
    Power and Cooling Capacity Management for Data Centers
    This paper describes the principles for achieving power and cooling capacity man....

     




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