PHP
  Home arrow PHP arrow Page 2 - Using Advanced Functions to Maintain the State of Applications with PHP Sessions
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

Using Advanced Functions to Maintain the State of Applications with PHP Sessions
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 12
    2006-05-03


    Table of Contents:
  • Using Advanced Functions to Maintain the State of Applications with PHP Sessions
  • Tweaking the PHP session storage module: using the “session_set_save_handler ()” function
  • Going deeper into PHP session management: creating a MySQL-based session storage module
  • Getting the MySQL-based session module complete: listing MySQL processing classes

  • 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


    Using Advanced Functions to Maintain the State of Applications with PHP Sessions - Tweaking the PHP session storage module: using the “session_set_save_handler ()” function
    ( Page 2 of 4 )

    As you learned before, the PHP built-in session management mechanism uses as default the “/tmp” directory, in order to store session data, which is first serialized and then saved in the dynamically-generated session file (remember that session IDs also are saved in cookies in the client).

    However, due to the versatility of the session module, it’s possible to modify this behavior and change the location –- and eventually the way –- in which session data is stored. Regarding this useful feature, PHP provides developers with the ability to define six callback functions, which can be used in conjunction with the “session_set_save_handler()” function, in order to construct a user-defined session storage module.

    In this case, a custom callback function must be defined for each of the corresponding operations performed to manage a particular session, that is when reading, writing and destroying session data, and when the PHP built-in garbage collection mechanism is triggered. This process can be translated into the definition of six generic functions, which are listed below:

    function open(){
        // called when a session is opened
    }
    function close(){
        // called when a session is closed
    }
    function read(){
        // called when session is read
    }
    function write(){
        // called when session is written
    }
    function destroy(){
        // called when session is destroyed
    }
    function gc(){
        // called when the garbage collection mechanism is triggered
    }

    As you can see, each of the above defined functions can be used in conjunction with the “session_set_save_handler()” function. This is handy for constructing a custom session mechanism, which eventually can be more efficient and secure that the one provided as the default by PHP.

    In order to illustrate this useful concept, first I’ll show you a basic and admittedly inefficient implementation, which utilizes user-defined callback functions to store session data on a different directory. Here’s the corresponding code example:

    // define new file path for storing session data
    define("SESSION_PATH","c:session_path"); // double
    backslashes is used on Windows systems
    // not required to implement 'open()' method
    function open(){
        return true;
    }
    // not required to implement 'close()' method
    function close(){
        return true;
    }
    // define 'read()' method
    function read($id){
        $sessionFile=SESSION_PATH.'sess_'.$id;
        if(!file_exists($sessionFile)||!
    $sessionData=@file_get_contents($sessionFile)){
            return "";
        }
        return $sessionData;
    }
    // define 'write()' method
    function write($id,$sessionData){
        if(!$fp=fopen(SESSION_PATH.'sess_'.$id,'w')){
            return "";
        }
        return fwrite($fp,$sessionData);
    }
    // define 'destroy()' method
    function destroy($id){
        // delete session file
        return unlink(SESSION_PATH.'sess_'.$id);
    }
    function gc($maxlifetime){
        $sessionFile=SESSION_PATH.'sess_'.$id;
        if(filemtime($sessionFile)>(time()-$maxlifetime)){
            unlink($sessionFile);
        }
        return true;
    }
    // define custom session handling functions
    session_set_save_handler
    ('open','close','read','write','destroy','gc');
    // use sessions as one would expect
    session_start();
    // register some session variables
    $_SESSION['firstname']='Alejandro';
    $_SESSION['lastname']='Gervasio'; 

    In short, what I’ve done with the above example is define the corresponding six callback functions that will be called up during the regular occurrence of a session. Notice that the first two functions, “open()” and close(),” don’t need to be concretely defined, thus they’re simply specified as empty.

    The remaining functions take care of reading, writing and eventually deleting session data, by using the value of the constant “SESSION_PATH,” which I defined right at the beginning of the script. Of course, as I said before, this isn’t the best way of building a user-defined session storage module, but my intention is that you learn how these callback functions are used as parameters by the “session_set_save_handler()” function.

    Once the “session_set_save_handler()” function is invoked with the proper callback functions, all the session data will be stored and read from the “C:session_path” directory (you can change this, in case you're using a UNIX-based operating system), which means that all the session files will be created within the mentioned directory. In case you want to see how this session mechanism works, first run the above script and use the $_SESSION superglobal array to store some session data. Then open the custom directory, and you should see that PHP has created the corresponding session files on that directory.

    Nevertheless, I said the previous example was pretty useless. Why? Well, in fact there’s no need to reinvent the wheel if you just want to change the physical directory where session data is saved. Fortunately, PHP offers the “session_save_path()” function, which takes as an argument the new path where you want session data to be stored. Being aware of the existence of this function, the entire prior example might be rewritten as follows:

    // use 'session_save_path()' function
    session_save_path("c:session_path");// double backslashes is
    used on Windows systems
    session_start();
    // register some session variables
    $_SESSION['firstname']='Alejandro';
    $_SESSION['lastname']='Gervasio';

    Definitely, you’ll agree with me that the above script is much simpler to code and read. And the best thing is that you’ll get the same result, just using the “session_save_path()” function. However, the example that you learned before for using callback functions is quite good for introducing the “session_set_save_handler()” function, and serves as a nice preface for showing a more useful example of how to use this function. To see the development of a more complex example, please go ahead and keep on reading.



     
     
    >>> More PHP Articles          >>> More By Alejandro Gervasio
     

       

    PHP ARTICLES

    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL
    - Method Chaining: Adding More Methods to the ...
    - Method Chaining in PHP 5
    - The Role of Interfaces in Applying the Depen...
    - Dependency Injection: Using a Setter Method ...
    - Using a Model Class with the Dependency Inje...
    - Injecting Objects Using Setter Methods with ...
    - Injecting Objects by Constructor with the De...
    - The Dependency Injection Design Pattern in P...
    - Performing Inferential Statistical Analysis ...
    - Performing Descriptive Statistical Analysis ...





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