I’ll start with code
:
require_once('../database/class.database.php');
class UserSession {
private $php_session_id;
private $native_session_id;
private $db;
private $conn;
private $logged_in;
private $user_id;
private $session_timeout = 600;
private $session_lifespan = 3600;
public function __construct() { //Connection to DB
try {
$this->conn = Database::instance();
if(DB::isError($this->conn)) {
throw new Exception($this->conn->getMessage(), $this->conn->getCode());
}
} catch (Exception $e) {
echo $e->getMessage();
exit(2);
}
//Session Handler
session_set_save_handler(
array(&$this, '_session_open_method'),
array(&$this, '_session_close_method'),
array(&$this, '_session_read_method'),
array(&$this, '_session_write_method'),
array(&$this, '_session_destroy_method'),
array(&$this, '_session_gc_method')
);
//Check the cookie passed - if one is - if it looks wrong we will scrub it right away
$strUserAgent = $GLOBALS["HTTP_USER_AGENT"];
if(isset($_COOKIE["PHPSESSID"])) {
//Security and Age Check
$this->php_session_id = $_COOKIE["PHPSESSID"];
$stmt = "
SELECT id
FROM user_session
WHERE ascii_session_id = '" . $this->php_session_id . "'
AND ((now() - created) < ' " . $this->session_lifespan . " seconds')
AND user_agent='" . $strUserAgent . "'
AND ((now() -last_impression) <= '".$this->session_timeout." seconds'
OR last_impression IS NULL)
";
$result = mysql_query($stmt) or die("mysql error in session_set_save_handler " . mysql_error() . " in query $query");
if(mysql_num_rows($result)==0) {
//Set failed flag
$failed = 1;
//Delete from database - we do garbage cleanup at the same time
$stmt = "
DELETE FROM session_variable
WHERE session_id
NOT IN (
SELECT id FROM user_session)
";
$result = mysql_query($stmt) or die("mysql error in session_set_save_handler " . mysql_error() . " in query $query");
//Get rid of this one... this will force PHP to give us another
unset($_COOKIE["PHPSESSID"]);
};
};
//Set the life time for the cookie
session_set_cookie_params($this->session_lifespan);
//Call up Session Handler here ??????????????
//Call the session_start method to get things started
session_start();
}
public function Impress() {
if($this->native_session_id) {
$stmt = "
UPDATE user_session
SET last_impression = now()
WHERE id = '" . $this->native_session_id . "'
";
$result = mysql_query($stmt) or die("mysql error in Impress " . mysql_error() . " in query $query");
};
}
public function IsLoggedIn() {
return($this->logged_in);
}
public function GetUserID() {
if($this->logged_in) {
return($this->user_id);
} else {
return(false);
};
}
public function GetUserObject() {
if($this->logged_in) {
if(class_exists("user")) {
$objUser = new User($this->user_id);
return($objUser);
} else {
return(false);
};
};
}
public function GetSessionIdentifier() {
return($this->php_session_id);
}
public function Login($strEmail, $strPlainPassword) {
$strMD5Password = md5($strPlainPassword);
$stmt = "
SELECT id
FROM users
WHERE email = '$strEmail'
AND password = '$strMD5Password'
";
$result = mysql_query($stmt) or die("mysql error in Login " . mysql_error() . " in query $query");;
if(mysql_num_rows($result)>0) {
$row = mysql_fetch_array($result);
$this->user_id = $row["id"];
$this->logged_in = true;
$stmt = "
UPDATE user_session
SET logged_in = true
, user_id = " . $this->user_id . "
WHERE id = '". $this->native_session_id . "'
";
$result = mysql_query($stmt) or die("mysql error in Login " . mysql_error() . " in query $query");
return(true);
} else {
return(false);
};
}
public function LogOut() {
if($this->logged_in == true) {
$stmt = "
UPDATE user_session
SET logged_in = false
, user_id = 0
WHERE id = '" . $this->native_session_id . "'
";
$result = mysql_query($stmt) or die("mysql error in Logout " . mysql_error() . " in query $query");
$this->logged_in = false;
$this->user_id = 0;
return(true);
} else {
return(false);
};
}
public function __get($nm) {
$stmt = "
SELECT variable_value
FROM session_variable
WHERE session_id = " . $this->native_session_id . "
AND variable_name = '" . $nm . "'
";
echo "$stmt"; die();
$result = mysql_query($stmt) or die("mysql error in __get " . mysql_error() . " in query $query");
if(mysql_num_rows($result)>0) {
$row = mysql_fetch_array($result);
return(unserialize($row["variable_value"]));
} else {
return(false);
};
}
public function __set($nm, $val) {
$strSer = serialize($val);
$stmt = "
INSERT INTO session_variable(
session_id
, variable_name
, variable_value)
VALUES(" . $this->native_session_id . ", '$nm', '$strSer')
";
echo "stmt in __set(): $stmt"; die();
$result = mysql_query($stmt,$this->conn) or die("mysql error in __set " . mysql_error() . " in query $query");
}
private function _session_open_method($save_path, $session_name) {
//Do Nothing
return(true);
}
private function _session_close_method() {
$this->conn->disconnect();
return(true);
}
private function _session_read_method($id) {
//We use this to determine whether or not our session actually exists
$strUserAgent = $GLOBALS["HTTP_USER_AGENT"];
$this->php_session_id = $id;
//Set failed flag to 1 for now
$failed = 1;
//See if this exists in the database or not.
$stmt = "
SELECT
id
, logged_in
, user_id
FROM user_session
WHERE ascii_session_id = '$id'
";
$result = mysql_query($stmt) or die("mysql error _session_read_method 1 " . mysql_error() . " in query $stmt");
if(mysql_num_rows($result)>0) {
$row = mysql_fetch_array($result);
$this->native_session_id = $row["id"];
if($row["logged_in"] == "1") {
$this->logged_in = true;
$this->user_id = $row["user_id"];
} else {
$this->logged_in = false;
};
} else {
$this->logged_in = false;
//We need to create an entry to the database
$stmt = "
INSERT INTO user_session(
ascii_session_id
,logged_in
,user_id
,created
,user_agent)
VALUE ('$id','f',0,now(),'$strUserAgent')
";
$result = mysql_query($stmt) or die("mysql error in _session_read_method 2 " . mysql_error() . " in query $query");
//Now get the true ID
$stmt = "
SELECT id
FROM user_session
WHERE ascii_session_id = '$id'
";
$result = mysql_query($stmt) or die("mysql error in _session_read_method 3 " . mysql_error() . " in query $query");
$row = mysql_fetch_array($result);
$this->native_session_id = $row["id"];
};
return("");
}
private function _session_write_method($id, $sess_data) {
return(true);
}
private function _session_destroy_method($id) {
$stmt = "
DELETE FROM user_session
WHERE ascii_session_id = 'id'
";
$result = mysql_query($stmt) or die("mysql error in _session_destroy_method " . mysql_error() . " in query $query");
return($result);
}
private function _session_gc_method($maxlifetime) {
return(true);
}
}
That’s my revised copy. Changed some things around. Mostly query’s.
sessiontest.php:
require_once("usersession.phpm");
require_once("../debug/class.debugger.php");
$objSession = new UserSession();
$objSession->Impress();
Debugger::debug($objSession,'objSession');
?>
UserSession Test Page
<hr>
<b>Current Session ID: </b> <?=$objSession->GetSessionIdentifier();?><br>
<b>Logged in? </b> <?=(($objSession->IsLoggedIn() == true) ? "Yes" : "No")?><br>
Attempting to log in ...
<?php $objSession->Login("ed@example.com","12345"); ?>
<br><br><?php Debugger::debug($objSession,'objSession');?>
<b>Logged in? </b> <?=(($objSession->IsLoggedIn() == true) ? "Yes" : "No")?><br>
<b>User ID of logged in user: </b> <?=$objSession->GetUserID();?><br>
<br><br>
Now Logging Out ...
<?php $objSession->LogOut();?><br>
<b>Current Session ID: </b> <?=$objSession->GetSessionIdentifier();?><br>
<br><br>
<b>Logged in? </b><?=(($objSession->IsLoggedIn() == true) ? "Yes" : "No")?><br><br><br>
<?php
?>
Sessions are being created and stored correctly in the database. I’m that far along. However, they’re not being deleted. I have read up a bit on session_set_save_handler and there’s some things I’m not understanding. It’s stated that in php5.0.5 that write and close are called after the deconstructor. How can I act on the object? How/when do I know when it’s been destroyed?
session_set_cookie_params($this->session_lifespan);
//Call up Session Handler here ??????????????
//Call the session_start method to get things started
session_start();
Since I have overridden the methods do I need to call session_set_save_hander like the documentation shows?
session_set_save_handler("open", "close", "read", "write", "destroy", "gc");
Any insight is so very much appreciated. Doing my best to learn :).