MySQL
  Home arrow MySQL arrow Page 3 - Developing Custom PHP Sessions
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Sun Developer Network 
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? 
MYSQL

Developing Custom PHP Sessions
By: Brian Rosner
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 2 stars2 stars2 stars2 stars2 stars / 21
    2002-07-21

    Table of Contents:
  • Developing Custom PHP Sessions
  • Developing the Backend
  • Creating the Session Functions (contd.)
  • Using Our Sessions
  • Conclusion

  • 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


    Developing Custom PHP Sessions - Creating the Session Functions (contd.)


    (Page 3 of 5 )

    Now let's take a look at our functions that read and expire the session. The first function is read(). It will read the session in the database, fetch it and store it to $sess_var. Here's the code:

    function read() {

    // set $sess_val global - the variable of the session value.
    global $sess_val;

    // if the cookie doesn't exisit send them back to the login screen.
    if(!$_COOKIE["sess_key"]) {
    header("Location: login.php");
    exit;
    }

    // fetch the session key from the cookie.
    $this->key = $_COOKIE["sess_key"];

    // fetch the session value
    $query = mysql_query("SELECT val FROM sessions WHERE sess_key = '" . $this->key . "'") or die("query failed - line 55");

    if(mysql_num_rows($query) == 0) {
    header("Location: login.php");
    exit;
    }

    $fetch = mysql_fetch_array($query);

    // store the session value to $sess_val
    $sess_val = stripslashes($fetch["val"]);

    // test if session has reached the expiration point
    $this->expire();

    // this code will only run if expire() returned falsed - we update the last access point to now.
    $update = mysql_query("UPDATE sessions SET access = " . time() . " WHERE sess_key = '" . $this->key . "'") or die("query failed - line 70");

    }


    We tested the user in two places to see if they are logged in or not. The user is required to be logged in for the user to have the cookie and for the database entry to remain logged in. If not, they must login again.

    Next, the code pulls the session value from the database and stores it in the $sess_val variable. When you are using the code in your pages to output the sessions' value, you should use the $sess_val variable. We will discuss that later on.

    Finally, we test the session for expiration and if it returns false then it will update the last access field to "refresh" the session. I will now show you how to test the session for expiration. It's quite simple, but requires some mathematical skill.

    // this function will test if the user has been inactive for the defined timeout
    function expire() {

    // fetch the last access and expirations from the database
    $query = mysql_query("SELECT access, sec_expire, stamp_expire FROM sessions WHERE sess_key = '" . $this->key . "'") or die("query failed - line 78");
    $fetch = mysql_fetch_array($query);

    $access = $fetch["access"];
    $expire = $fetch["sec_expire"];
    $timeout = $fetch["stamp_expire"];

    // test if session is expired based on defined timeout
    if(($timeout - $access) <= ($expire - $expire)) {
    $this->destory();
    die("Your session has expired. Please re-login.");
    }
    }


    All of our session timestamps and timeout values are stored in the database, so we fetch that information first. If $timeout (a regular timestamp plus the session timeout) minus the last time the session was accessed is less than or equal to the seconds for the session minus itself, then we destroy the session and inform the user. If false, the code continues to execute.

    We now know our sessions pretty well. What if we wanted to change the value of the session because the value is the users' username? If the username is changed and the session isn’t updated and you test it, the script would think it's somebody else. No problem. Our next function is replace(). It simply updates the current value with a new value.

    // this function will update the session value
    function replace($val) {

    // fetch the user key from cookie
    $this->key = $_COOKIE["sess_key"];

    // update the database with the new value
    $query = mysql_query("UPDATE sessions SET val = '" . $val . "' WHERE sess_key = '" . $this->key) or die("query failed - line 77");
    }


    Our function asks for the new value and then it will update the current value with it. Finally, we reach our last function:

    // this function will kill the session
    function destroy($key = "") {

    // fetch the user key from cookie
    $this->key = $_COOKIE["sess_key"];

    // delete session from database
    $query = mysql_query("DELETE FROM sessions WHERE sess_key = '" . $this->key . "'") or die("query failed - line 86");

    // remove cookie from the user's computer
    $delete = setcookie("sess_key" , $this->key, time()-3600);

    if($query && $delete) {
    header("Location login.php");
    exit;
    }
    }


    The destroy() function will kill the session. It deletes the session from the database and removes the cookie from the users' computer. We now know everything about creating our sessions. We still have one more issue to cover, which is how to use them.

    More MySQL Articles
    More By Brian Rosner


     

    MYSQL ARTICLES

    - MySQL and BLOBs
    - Two Lessons in ASP and MySQL
    - Lord Of The Strings Part 2
    - Lord Of The Strings Part 1
    - Importing Data into MySQL with Navicat
    - Building a Sustainable Web Site
    - Creating An Online Photo Album with PHP and ...
    - Creating An Online Photo Album with PHP and ...
    - PhpED 3.2 – More Features Than You Can Poke ...
    - Creating An Online Photo Album with PHP and ...
    - Creating An Online Photo Album with PHP and ...
    - Security and Sessions in PHP
    - Setup Your Personal Reminder System Using PHP
    - Create a IP-Country Database Using PERL and ...
    - Developing a Dynamic Document Search in PHP ...






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