Zend - The PHP Company




HTTP

Add Code


Custom session functions  

Type: class
Added by: Syberius
Entered: 09/01/2003
Last modified: 03/12/2002
Rating: **** (6 votes)
Views: 11767
I had allways wondered how sites using PHP could count online users and do lots of fancy stuff with sessions. I decided to experiment and I created a set of session functions to replace the default php session functions. I use session_set_save_handler() to tell php to use my functions for sessions. This worked well but I then decided to make the set of functions into a class for use on any project, quickly and easily. The class uses MySQL but with some modifications can be used with other databases. To use all you have to do is include the class file in your script and change the mysql connection variables.


<?
/*
##############################################
#
#            Filename : session.class
#
#            Created  : 09/01/02 01:47 GMT
#
#                  Created By  : Syberius
#
#            Version : 1.10
#
##############################################
#
#   The session class below was written to allow session records to
#   be stored in a MySQL database. These custom session functions
#   are used with session_set_save_handler to tell PHP to use the
#   functions in this file and NOT the default functions.
#
#   The ses_start field is use to calculate how long a user has been
#   online. The forumla is time() - ses_start.
#
#   To use simply include/require this file and change the values of the
#   variables defined below!
#
##############################################
#
#   Additions and modifications are allowed as long as this message
#   remains. If you do make changes please contact me at this address.
#
#   syberius@tiscali.co.uk
#
#   To inform me of any changes to this file.
#S
#
##############################################
#
#   SQL for the basic table structure
#
#   CREATE TABLE sessions (
#   ses_id varchar(32) NOT NULL default '',
#   ses_time varchar(15) NOT NULL default '',
#   ses_start int(30) NOT NULL default '0',
#   ses_value text NOT NULL,
#   PRIMARY KEY  (ses_id)
#     ) TYPE=MyISAM;
#
##############################################
*/

// Create new object of class
$ses_class = new session($params);

// Change the save_handler to use the class functions
session_set_save_handler(
array(&
$ses_class'_open'),
array(&
$ses_class'_close'),
array(&
$ses_class'_read'),
array(&
$ses_class'_write'),
array(&
$ses_class'_destroy'),
array(&
$ses_class'_gc'));

// Start the session
session_start();

class 
session
{
    
// Define the mysql table you wish to use with this class, this table MUST exist.
    
var $ses_table "ses_table";
    
    
// Change to 'Y' if you want to connect to a db in the _open function
    
var $db_con "Y";
    
    
// Configure the info to connect to mysql, only required if $db_con is set to 'Y'
    
var $db_host "localhost";
    var 
$db_user "user";
    var 
$db_pass "pass";
    var 
$db_dbase "database";
    
    
// Create a connection to a database
    
function db_connect() {
        
$mysql_connect = @mysql_pconnect($this -> db_host$this -> db_user$this -> db_pass);
        
$mysql_database = @mysql_select_db($this -> db_dbase);
        
        if (!
$mysql_connect || !$mysql_database) {
            return (
"false");
        }
        else {
            return (
"true");
        }
    }
    
    
// Open session, if you have your own db connection code, put it in here!
    
function _open($path$name) {
        if (
$this -> db_con == "Y") {
            
$this -> db_connect();
        }
        
        return(
"true");
    }
    
    
// Close session
    
function _close() {
        
$this -> _gc(0); // This is used for a manual call of the session gc function
        
return("true");
    }
    
    
// Read session data from database
    
function _read($ses_id) {
        
$session_sql "SELECT * FROM ".$this -> ses_table."  WHERE ses_id = '$ses_id'";
        
$session_res = @mysql_query($session_sql);
        if (!
$session_res) {
            return(
"false");
        }
        
        
$session_num = @mysql_num_rows($session_res);
        if (
$session_num 0) {
            
$session_row mysql_fetch_assoc($session_res);
            
$ses_data $session_row["ses_value"];
            return(
$ses_data);
        }
        else {
            return(
"");
        }
    }
    
    
// Write new data to database
    
function _write($ses_id$data) {
        
$session_sql "UPDATE ".$this -> ses_table."  SET ses_time='".time()."', ses_value='$data' WHERE ses_id='$ses_id'";
        
$session_res = @mysql_query($session_sql);
        if (!
$session_res) {
            return(
"false");
        }
        if (
mysql_affected_rows()) {
            return(
"true");
        }
        
        
$session_sql "INSERT INTO ".$this -> ses_table."  (`ses_id`, `ses_time`, `ses_start`, `ses_value`) ";
        
$session_sql .= "VALUES ('$ses_id', '".time()."', '"time() ."', '$data')";
        
$session_res = @mysql_query($session_sql);
        if (!
$session_res) {
            return (
"false");
        }
        else {
            return(
"true");
        }
    }
    
    
// Destroy session record in database
    
function _destroy($ses_id) {
        
$session_sql "DELETE FROM ".$this -> ses_table."  WHERE ses_id = '$ses_id'";
        
$session_res = @mysql_query($session_sql);
        if (!
$session_res) {
            return(
"false");
        }
        else {
            return(
"true");
        }
    }
    
    
// Garbage collection, deletes old sessions
    
function _gc($life) {
        
$this -> db_connect();
        
        
$ses_life strtotime("-5 minutes");
        
        
$session_sql "DELETE FROM ".$this -> ses_table."  WHERE ses_time < $ses_life";
        
$session_res = @mysql_query($session_sql);
        
        if (!
$session_res) {
            return(
"false");
        }
        else {
            return(
"true");
        }
    }
}
?>


Usage Example


include("session.class");


Rate This Script





Search



This Category All Categories