WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDES  |  PHP CLASSES  |  CODE SEARCH  |  ARTICLES SEARCH  |  PHP FORUMS  |  PHP MANUAL  |  PHP FUNCTIONS LIST  |  WEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Submit Your Code
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
WeberDev's Monthly code contest PHP Code Contest
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Index
PHP Web Logs (BLogs)
Web Development Resources
Web Development Content
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
Submit Site
Forex Trading Online forex trading platform

Go Back Add a Comment Send this example to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES ADD CODE EXAMPLES PRINT
Title : Sessions Stored into the Database
Categories : PHP, Sessions Click here to Update Your Picture
Joseph Crawford
Date : Aug 03rd 2005
Grade : 5 of 5 (graded 1 times)
Viewed : 3004
File : 4210.rar
Images : No Images for this code example.
Search : More code by Joseph Crawford
Action : Grade This Code Example
Tools : My Examples List

 
Like this code?
Show the author your appreciation.
Submit your own code examples 
 

This code has taken me a while to understand and i thought i would share it here. This code uses php 5 and is a work in progress ;)

You can see an example here
http://codebowl.dontexist.net/csaf/

Note it requires that you allow cookies, if you dont you will only see an error message, i have required php to only use cookies for session security. Maybe i should write an article about this no?

init.php
<?php
ini_set
('session.use_only_cookies', 1);
define( 'BASE_PATH', str_replace( '\\', '/', dirname ( __FILE__ ) ) );

include_once(
'lib/database/database.php');
include_once(
'lib/auth/session.php');

$db = new Database("mysql://user:pass@host/db", true);

$s = new session($db);
/* Change the save_handler to use the class functions */
session_set_save_handler (array(&$s, 'open'),
array(&
$s, 'close'),
array(&
$s, 'read'),
array(&
$s, 'write'),
array(&
$s, 'destroy'),
array(&
$s, 'gc'));

/* Start the session */
session_start();
CheckSession();

function
CheckSession() {
    global
$db;
    if(
session_id()) {
       
$res = $db->Query("SELECT ip FROM sessions WHERE ses_id='".session_id()."'");
        if(
$db->NumRows($res) > 0) {
           
$data = $db->FetchArray($res);
           
$curIP = explode('.', $data['ip']);
           
$remIP = explode('.', $_SERVER['REMOTE_ADDR']);
            if( (
$curIP[0] != $remIP[0]) || ($curIP[1] != $remIP[1]) || ($curIP[2] != $remIP[2]) ) {
               
session_destroy();
            }
        }
    }
}
?>


test.php
<?php
ob_start
();
require(
'init.php');

$user = new Admin();
if (!isset (
$_SESSION['counter'])) {
   
$_SESSION['counter'] = 1;
}

echo
$_SESSION['counter'];
$_SESSION['counter']++;

echo
'<head><META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE"><META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE"></head>';
echo
'<br><br>';
echo
'current session id: '.session_id().'<br>';
echo
'<a href="test2.php">Test2</a>';
echo
'<br><br>';
echo
'Current Sessions<br>';
echo
'<table border=0 width="60%" align="center" cellpadding=0 cellspacing=0><tr><td>Type</td><td>Page</td><td>Browser</td><td>OS</td><td>Login Time</td></tr>';
$res = $db->query("SELECT * FROM sessions");
$sessions = $db->FetchAll($res);
foreach(
$sessions as $session) {
   
$time = $session['ses_time'] - $session['ses_start'];
    echo
'<tr><td><img src=\''.$session['typeicon'].'\'></td><td>'.$session['page'].'</td><td><img src=\''.$session['browser'].'\'></td><td><img src=\''.$session['os'].'\'></td><td>'.calculate_time($time).'</td></tr>';
}
echo
'</table>';
ob_end_flush();

function
calculate_time($seconds) {
    if(
$seconds < 60) {
       
$time = $seconds;
       
$time .= ' second';
        if(
$time > 1 || $time < 1) $time .= '(s)';
        return
$time;
    } elseif (
$seconds < 3600) {
       
$time = round(($seconds / 60), 0);
       
$time .= ' minute';
        if(
$time > 1) $time .= '(s)';
        return
$time;
    } elseif (
$seconds < 86400) {
       
$time = (($seconds / 60) / 60);
       
$time .= ' hour';
        if(
$time > 1) $time .= '(s)';
        return
$time;
    }
           
}
?>


session.php
<?php

class session
{
   
/* Define the mysql table you wish to use with
    this class, this table MUST exist. */
   
private $table = "sessions";
    private
$_db;
    private
$_page;
    public
$_ses_id;
    private
$_ip;
    private
$_browser;
    private
$_browserList;
    private
$_os;
    private
$_osList;
    static private
$_type;
    private
$_typeIcon;
    private
$_init;


    public function
__construct(Database $db) {
       
$this->_db = $db;

       
       
$this->_browserList = array('offbyone' => 'ob1.gif', '3b_web' => '3b.gif', 'getrig' => 'get.gif', 'webtv' => 'webtv.gif', 'aol' => 'aol.gif', 'opera' => 'opera.gif', 'netposit' => 'netp.gif', 'ibrowse' => 'ibrowse.gif', 'abrowse' => 'abrowse.gif', 'firefox' => 'firefox.gif', 'firebird' => 'firebird.gif', 'phoenix' => 'firebird.gif', 'omniweb' => 'omni.gif', 'safari' => 'safari.gif', 'camino' => 'camino.gif', 'chimera' => 'camino.gif', 'konqueror' => 'konq.gif', 'icab' => 'icab.gif', 'dillo' => 'dillo.gif', 'epiphany' => 'epiph.gif', 'oregano' => 'oregano.gif', 'k-meleon' => 'kmel.gif', 'webcapture' => 'webcap.gif', 'galeon' => 'galeon.gif', 'lynx' => 'lynx.gif', 'netscape' => 'netscape.gif', 'entergy' => 'entergy.gif', 'msie' => 'ie.gif', 'mozilla' => 'moz.gif');
       
$this->_osList = array('linspire' => 'linspire.gif', 'lindows' => 'linspire.gif', 'beos' => 'beos.gif', 'skyos' => 'skyos.gif', 'atheos' => 'athe.gif', 'palmos' => 'palm.gif', 'nokia' => 'nokia.gif', 'blackberry' => 'blackb.gif', 'zeta' => 'zeta.gif', 'irix' => 'irix.gif', 'risc' => 'riscos.gif', 'os/2' => 'os2.gif', 'amigaos' => 'amiga.gif', 'freebsd' => 'fbsd.gif', 'netbsd' => 'nbsd.gif', 'sunos' => 'solaris.gif', 'solaris' => 'solaris.gif', 'os x' => 'osx.gif', 'osx' => 'osx.gif', 'darwin' => 'osx.gif', 'macintosh' => 'macintosh.gif', 'mac_' => 'macintosh.gif', 'qnx' => 'qnx.gif', 'linux' => 'linux.gif', 'unix' => 'unix.gif', 'x11' => 'x11.gif', 'windows' => 'windows.gif', 'win95' => 'windows.gif', 'win98' => 'windows.gif', 'winnt' => 'windows.gif');
       
self::setType();
       
$this->_init = FALSE;
       
$this->sniff();
    }

    private function
init($ses_id) {
       
$this->_ses_id = $ses_id;
       
$this->_ip = $_SERVER['REMOTE_ADDR'];
       
$this->_init = TRUE;
    }
   
    public function
sniff() {
       
$this->_page = $_SERVER['REQUEST_URI'];
       
$this->setUserIcon();
       
$this->setUserBrowser();
       
$this->setUserOS();
    }

    public function
open($path, $name) {
        return
TRUE;
    }

   
/* Close session */
   
public function close() {
       
/* This is used for a manual call of the
        session gc function */
       
$this->gc(0);
        return
TRUE;
    }

   
/* Read session data from database */
   
public function read($ses_id) {
       
$session_sql = "SELECT * FROM " . $this->table
       
. " WHERE ses_id = '$ses_id'";

       
$session_res = $this->_db->Query($session_sql);
        if (!
$session_res) {
            return
'';
        }
       
$session_num = $this->_db->NumRows($session_res);
        if (
$session_num > 0) {
           
$session_row = $this->_db->FetchArray($session_res);
           
$ses_data = $session_row["ses_value"];
            return
$ses_data;
        } else {
            return
'';
        }
    }

   
/* Write new data to database */
   
public function write($ses_id, $data) {
       
$this->sniff();
        if(
$this->_init == FALSE) $this->init($ses_id);
       
$session_sql = "SELECT * FROM ".$this->table." WHERE ses_id='".$this->_ses_id."'";
       
$res = $this->_db->Query($session_sql);
        if(
$this->_db->NumRows($res) == 0 ) {
           
$session_sql = "
            INSERT INTO "
           
.$this->table." (ses_id, type, typeicon, ses_time, ses_start, page, ip, browser, os, ses_value)
            VALUES
                ('"
.$this->_ses_id."', '".self::$_type."', '".$this->_typeIcon."', ".time().", ".time().", '".$this->_page."', '".$this->_ip."', '".$this->_browser."', '".$this->_os."', '".$data."')";
        } else {
           
$session_sql = "UPDATE ".$this->table." SET type='".self::$_type."', typeicon='".$this->_typeIcon."', ses_time=".time().", page='".$this->_page."', ses_value='".$data."' WHERE ses_id='".$this->_ses_id."'";
        }
       
//echo $session_sql;
       
$session_res = $this->_db->Query($session_sql);

        if (!
$session_res) return FALSE;
        else return
TRUE;

    }

   
/* Destroy session record in database */
   
public function destroy($ses_id) {
       
$session_sql = "DELETE FROM " . $this->table
       
. " WHERE ses_id = '$ses_id'";

       
$session_res = $this->_db->Query($session_sql);
       
$this->_browser = null;
       
$this->_ip = null;
       
$this->_os = null;
       
$this->_page = null;
       
$this->_ses_id = null;
       
$this->_typeIcon = null;
       
session_regenerate_id();
        if (!
$session_res) return FALSE;
        else return
TRUE;
    }

   
/* Garbage collection, deletes old sessions */
   
public function gc($life) {
       
$ses_life = time() - 300;

       
$session_sql = "DELETE FROM " . $this->table
       
. " WHERE ses_time < $ses_life";

       
$session_res = $this->_db->Query($session_sql);


        if (!
$session_res) return FALSE;
        else return
TRUE;
    }

    private function
setUserIcon() {
        switch(
self::$_type) {
            case
'AD':
           
$this->_typeIcon = 'images/icons/user/admin.png';
            break;
            case
'CL':
           
$this->_typeIcon = 'images/icons/user/client.png';
            break;
            case
'CO':
           
$this->_typeIcon = 'images/icons/user/contractor.png';
            break;
            default:
           
$this->_typeIcon = 'images/icons/user/guest.png';
        }
    }

    private function
setUserBrowser() {
        foreach (
$this->_browserList as $browser => $img) {
            if(
stristr($_SERVER['HTTP_USER_AGENT'], $browser)) {
               
$this->_browser = 'images/icons/browser/'.$img;
                break;
            }
        }
    }

    private function
setUserOS() {
        foreach (
$this->_osList as $os => $img) {
            if(
stristr($_SERVER['HTTP_USER_AGENT'], $os)) {
               
$this->_os = 'images/icons/os/'.$img;
                break;
            }
        }
    }

    static public function
setType( $type = 'GU' ) {
       
$type = substr($type, 0, 2);
        if(isset(
$type) && is_string($type) && strlen($type) == 2) self::$_type = strtoupper($type);
    }
}
?>


DB SCHEMA
--
-- Table structure for table `sessions`
--

CREATE TABLE `sessions` (
  `ses_id` varchar(32) NOT NULL default '',
  `type` enum('GU','CL','CO','AD') NOT NULL default 'GU',
  `typeicon` varchar(255) NOT NULL default '',
  `ses_time` int(11) NOT NULL default '0',
  `ses_start` int(11) NOT NULL default '0',
  `page` varchar(255) NOT NULL default '',
  `ip` varchar(15) NOT NULL default '',
  `browser` varchar(255) NOT NULL default '',
  `os` varchar(255) NOT NULL default '',
  `ses_value` text NOT NULL,
  PRIMARY KEY  (`ses_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;



Demo of Alternate Pagination Paradigm (Paging)
Categories : PHP, User Interface, Sessions
XDT Topsite (Gold v1.0)
Categories : Databases, CSS, PHP, HTML and PHP, Sessions
Problem passing session variables
Categories : Sessions, PHP
GuestBook Light - a plug and play application for any website.
Categories : PHP, Complete Programs, Filesystem, Sessions
A beginner's session handling class
Categories : PHP, PHP Classes, Sessions, Beginner Guides
base64 with encryption - encode and decode sessions
Categories : PHP, PHP Classes, Encryption, Sessions
A simple PHP login script that you can modify to suite your needs. It use a session to store data in a session file submited by the page.
Categories : PHP, Sessions, Security, Authentication
SPL and ITERATOR : examples
Categories : PHP, Object Oriented, PHP Classes, Sessions
Form Security - Match A Value For Success
Categories : PHP, Authentication, HTML and PHP, Sessions, Security
AITSH Statistics
Categories : Complete Programs, Databases, HTML and PHP, Sessions, PHP
Session Validation Methods (Security Checks)
Categories : PHP, Sessions, Security
How to implement a session tracking system.
Categories : PHP, Sessions, Variables
Prevent multi submit
Categories : PHP, Sessions
CAPTCHA[Image verification]
Categories : PHP, Security, GD image library, Graphics, Sessions
Sessions and -enable-trans-sid
Categories : PHP, PHP Configuration, PHP Options and Info, Sessions
 Joseph Crawford wrote :1344
In my latest version i no longer use the users IP address in the session check.  It was brought to my attention that this is not a good way to go, so i used an alternate method.