PHP
  Home arrow PHP arrow Page 4 - Using Advanced Functions to Maintain t...
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 Advanced Functions 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 / 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:
      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 Advanced Functions to Maintain the State of Applications with PHP Sessions - Getting the MySQL-based session module complete: listing MySQL processing classes


    (Page 4 of 4 )

    As I promised, here’s the source code for the couple of MySQL processing classes used within the definition of the prior callback functions:

    class MySQL {
        var $conId; // connection identifier
        var $host; // MySQL host
        var $user; // MySQL username
        var $password; // MySQL password
        var $database; // MySQL database
        // constructor
        function MySQL($options=array()){
            // validate incoming parameters
            if(count($options)>0){
                foreach($options as $parameter=>$value){
                    if(empty($value)){
                        trigger_error('Invalid parameter
    '.$parameter,E_USER_ERROR);
                    }
                    $this->{$parameter}=$value;
                }
                // connect to MySQL
                $this->connectDB();
            }
            else {
                trigger_error('No connection parameters were
    provided',E_USER_ERROR);
            }
        }
        // connect to MYSQL server and select database
        function connectDB(){
            if(!$this->conId=mysql_connect($this->host,$this-
    >user,$this->password)){
                trigger_error('Error connecting to the
    server',E_USER_ERROR);
            }
            if(!mysql_select_db($this->database,$this->conId)){
                trigger_error('Error selecting
    database',E_USER_ERROR);
            }
        }
        // perform query
        function query($query){
            if(!$this->result=mysql_query($query,$this->conId)){
                trigger_error('Error performing query
    '.$query,E_USER_ERROR);
            }
            // return new Result object
            return new Result($this,$this->result); 
        }
    }

    class Result {
        var $mysql; // instance of MySQL object
        var $result; // result set
        function Result(&$mysql,$result){
            $this->mysql=&$mysql;
            $this->result=$result;
        }
        // fetch row
        function fetchRow(){
            return mysql_fetch_array($this->result,MYSQL_ASSOC);
        }
        // count rows
        function countRows(){
            if(!$rows=mysql_num_rows($this->result)){
                return false;
            }
            return $rows;
        }
        // count affected rows
        function countAffectedRows(){
            if(!$rows=mysql_affected_rows($this->mysql->conId)){
                trigger_error('Error counting affected
    rows',E_USER_ERROR);
            }
            return $rows;
        }
        // get ID from last inserted row
        function getInsertID(){
            if(!$id=mysql_insert_id($this->mysql->conId)){
                trigger_error('Error getting ID',E_USER_ERROR);
            }
            return $id;
        }
        // seek row
        function seekRow($row=0){
            if(!mysql_data_seek($this->result,$row)){
                trigger_error('Error seeking data',E_USER_ERROR);
            }
        }
        function getQueryResource(){
            return $this->result;
        }
    }

    Right. Now that I showed you the pair of MySQL processing classes used by the previous callback functions, let me set up an example which implements this user-defined session storage system, by the respective “session_set_save_handler()” function. Have a look at the code listed below:

    // 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'));
    // use 'session_set_save_handler function'
    session_set_save_handler
    ('openSession','closeSession','readSession','writeSession',
    'destroySession',
    'gcSession');
    session_start();
    // register some session variables
    $_SESSION['firstname']='Alejandro';
    $_SESSION['lastname']='Gervasio';

    That’s it. After connecting to MySQL, the above script uses the “session_set_save_handler()” in order to register all the callback functions that you saw before, and as a result, all the session data will be stored in a sample “sessions” database table. By tweaking the correct session settings within the php.ini file, in conjunction with implementing this MySQL-driven session storage module, it’s possible to construct a more efficient and secure session management mechanism than the one provided as default by PHP. As you’ve seen, the experience can be instructive and educational, so why don’t you try it for yourself?

    Wrapping up

    That’s all for the moment. Over this second part of the series, I explored the powerful “session_save_path()” and “session_set_save_handler()” functions. Particularly, this last function can be extremely helpful for developing a custom session management system that uses a MySQL database table for storing session-related data, instead of conventional flat files.

    Since this approach is used in many situations where a personalized session storage mechanism is preferred over the default offered by PHP, in the last article, I’ll encapsulate all the pertinent callback functions defined before within a class. In this way, the entire session handling process can be centralized at only one handler object. Therefore, don’t miss the next part!


    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.

       · In this part of the series, you'll learn how to tweak the PHP session storage...
       · Hi Alejandro, I greatly appreciate your efforts in bringing us these useful...
       · Hi Rafael,Thank you for commenting on my PHP article. Regarding your question,...
       · Hi Alejandro, thank you so much for the example, it worked to perfection. I'm so...
       · Hi Rafael,Thank you for the kind word on my PHP articles, and certainly I feel...
       · Hello again Alejandro, I run into a bug as I got my application onto the production...
       · Hi Rafael,Thank you for posting your comments. Concerning your particular...
       · Hi Alejandro, a million thanks for your help. I stayed awake for a long time last...
       · Hi Rafael. I'm glad to know you fixed up the problem regarding the use of mysqli and...
       · Hi alejandroIts me again, ive been making your tutorial as my book, im working...
       · Hi Alejandro,thanks for this wonderful tutorial.When i tried to use your...
       · Hi Roy,Thanks for posting your comments, and I’m glad to know you’re learning...
       · Thansk again for the comments. In fact, $id isn't necessary when coding this...
       · Hello Alejandro,Thanks for the prompt reply. Im still confused, on your reply you...
       · Hello Alejandro,I temporarily placed this code inside the writeSession()...
       · Hi Roy,with your last example, I see the possible reason of your problem....
       · Hello alehandro... i set up my expiry as a timestamp, and that the expiry colum...
       · Hello Roy,Thanks for the comments. Using "time()" to insert your timestamps is a...
     

       

    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...





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