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?
$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;
}
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;
/* 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'";
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.