Jump to content


Photo

Help Coding Classes with sessions


  • Please log in to reply
6 replies to this topic

#1 tobeyt23

tobeyt23
  • Members
  • PipPipPip
  • Advanced Member
  • 259 posts
  • LocationSalisbury

Posted 15 August 2006 - 07:15 PM

I am trying to clean up some exsiting code by using classes, however I am completely bombing big time. Seems that when I want to use my session variables they are being lost and I dont understand why. Can someone look at my code and explain what I may be doing wrong please.

<?php
include 'lib/header.php';
include 'lib/configs.php';
include 'page_class.php';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Class Test</title>
</head>

<body>
<?php
$Customer = new Customer;
$test = $_SESSION['eshop_customer_id'];
$Customer->Set_Customer_Id($test);
$Customer->Customer_Start();
?>
</body>
</html>

<?php
class Customer {
	
	var $Customer_Id;
	
	function Customer_Start() {
		global $defaults, $_REQUEST;
		if (isset($this->Customer_Id))  {
			$this->UserLogged();
		}
		elseif ((isset($_REQUEST["UpDateCust"])) && (isset($this->Customer_Id)))  {
			$this->UserUpdate();
		}
		elseif (isset($_REQUEST["UpDateCard"])) {
			$this->UserCardUpdate();
		}
		elseif (isset($_REQUEST["UpDatePasswd"])) {
			$this->UserPasswdUpdate();
		}
		elseif (isset($_REQUEST["CustUpdate"])) {
			$this->CustDBupdate();
		}
		elseif (isset($_REQUEST["PassUpdate"])) {
			$this->PassDBUpdate();
		}
		elseif (isset($_REQUEST["CardUpdate"])) {
			$this->CardDBupdate();
		}
		elseif (isset($_REQUEST["SignIn"])) {
			$this->UserValid();
		}
		elseif (isset($_REQUEST['Logout'])) {
			$this->LogOut();
		}
		else {
			$this->login_form($error);
		}
	}

	function login_form($error) {
		global $defaults, $_REQUEST;
		echo "\t\t<div id=\"login\">\n";
		echo "\t\t\t<form action=\"test2.php\" method=\"post\">\n";
		echo "\t\t\t<input type=\"hidden\" name=\"SignIn\" value=\"1\">\n";
		if (isset($error)) {
			echo "\t$error<br><br>\n";
		}
		echo "\t\t\tUsername:<br /><input type=\"text\" name=\"username\" /><br /><br />\n";
		echo "\t\t\tPassword:<br /><input type=\"password\" name=\"password\" /><br /><br />\n";
		echo "\t\t\t<input type=\"submit\" value=\" Sign In \" class=\"submit\" /><br /><br />\n";
		echo "\t\t\t</form>\n";
		echo "\t\t</div>\n";
	}

	function UserValid() {
		global $defaults, $_REQUEST;
		$link = mysql_connect($defaults["db_server"], $defaults["db_username"], $defaults["db_password"]) or die ('Could not connect: ' . mysql_error());
		mysql_select_db($defaults["db_database"]) or die('Could not select database');
		$query = "SELECT customer_id, fname, lname, email, phone, card_type, card_number, password, account_type from customer where username='".$_REQUEST["username"]."'";
		$result = mysql_query($query) or die('Query failed: ' . mysql_error());
		if (mysql_num_rows($result) > 0) {
			while ($sqldatarow = mysql_fetch_assoc($result)) {
				$customer_id = $sqldatarow["customer_id"];
				$customer_fname = $sqldatarow["fname"];
				$customer_lname = $sqldatarow["lname"];
				$customer_email = $sqldatarow["email"];
				$customer_phone = $sqldatarow["phone"];
				$customer_cc_type = $sqldatarow["card_type"];
				$customer_cc = $sqldatarow["card_number"];
				$hashed_password = $sqldatarow["password"];
				$account_type = $sqldatarow["account_type"];
			}
			$password = $_REQUEST["password"];
			if (PasswordHasher::Hash($password) != $hashed_password) {
				$error = $error."&curren; Incorrect Password! &curren;";
				$this->login_form($error);
			}
			else {
				$_SESSION["eshop_customer_id"] = $customer_id;
				$_SESSION["eshop_customer_fname"] = $customer_fname;
				$_SESSION["eshop_customer_lname"] = $customer_lname;
				$_SESSION["eshop_customer_email"] = $customer_email;
				$_SESSION["eshop_customer_phone"] = $customer_phone;
				$_SESSION["eshop_customer_cc_type"] = $customer_cc_type;
				$_SESSION["eshop_customer_cc"] = $customer_cc;
				$_SESSION["eshop_account_type"] = $account_type;
				$this->UserLogged($error);
			}
		}
		else {
			$error = $error."&curren; Unkown Username! &curren;";
			$this->login_form($error);
		}
		mysql_free_result($result);
		mysql_close($link);
	}
	
	function UserLogged($error) {
		global $defaults, $_REQUEST;
		if (isset($_SESSION['eshop_customer_id'])) {
			echo "\t\t".$_SESSION['eshop_customer_id']."\n";
			echo "\t\t".$this->Customer_Id."\n";	
			echo "\t\t<br>\n";
			echo "\t\t<br>\n";
			echo "\t\t<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\" class=\"LoginTable\">\n";
			echo "\t\t<tr>\n";
			echo "\t\t\t<td class=\"LoginHead\">Welcome ".$_SESSION["eshop_customer_fname"]." ".$_SESSION["eshop_customer_lname"]."</td>\n";
			echo "\t\t</tr>\n";
			if (isset($error)) {
				echo "\t\t<tr>\n";
				echo "\t\t\t<td class=\"LoginContentError\">".$error."</td>\n";
				echo "\t\t</tr>\n";
			}
			if ($_SESSION["eshop_account_type"] != "Shopper") {
				echo "\t\t<tr>\n";
				echo "\t\t\t<td class=\"LoginContent\">&bull;<a href=\"test2.php?UpDateCust=1\" class=\"link\">Update Account Details</a></td>\n";
				echo "\t\t</tr>\n";
				echo "\t\t<tr>\n";
				echo "\t\t\t<td class=\"LoginContent\">&bull;<a href=\"test2.php?UpDatePasswd=1\" class=\"link\">Update Password</a></td>\n";
				echo "\t\t</tr>\n";
			}
			echo "\t\t<tr>\n";
			echo "\t\t\t<td class=\"LoginContent\">&bull;<a href=\"test2.php?UpDateCard=1\" class=\"link\">Update Credit Card</a></td>\n";
			echo "\t\t</tr>\n";
			if ($_SESSION["eshop_account_type"] == "Admin") {
				echo "\t\t<tr>\n";
				echo "\t\t\t<td class=\"LoginContent\">&bull;<a href=\"admin\" class=\"link\">Site Administration</a></td>\n";
				echo "\t\t</tr>\n";
			}
			if ($_SESSION["eshop_account_type"] == "Approver") {
				echo "\t\t<tr>\n";
				echo "\t\t\t<td class=\"LoginContent\">&bull;<a href=\"admin\" class=\"link\">View Orders</a></td>\n";
				echo "\t\t</tr>\n";
			}
			echo "\t\t<tr>\n";
			echo "\t\t\t<td class=\"LoginContent\">&bull;<a href=\"test2.php?Logout=1\" class=\"link\">Log Out</a></td>\n";
			echo "\t\t</tr>\n";
			echo "\t\t</table><br>\n";
		}
		else {
			$this->login_form();
		}
	}
	
	function UserUpdate() {
		global $defaults, $_REQUEST;
		$link = mysql_connect($defaults["db_server"], $defaults["db_username"], $defaults["db_password"]) or die ('Could not connect: ' . mysql_error());
		mysql_select_db($defaults["db_database"]) or die('Could not select database');
		$query = "SELECT fname, lname, email, phone, username FROM customer where customer_id='".$_SESSION['eshop_customer_id']."'";
		$result = mysql_query($query) or die('Query failed: ' . mysql_error());
		if (mysql_num_rows($result) > 0) {
			while ($sqldatarow = mysql_fetch_assoc($result)) {
				$fname = $sqldatarow["fname"];
				$lname = $sqldatarow["lname"];
				$email = $sqldatarow["email"];
				$phone = $sqldatarow["phone"];
				$username = $sqldatarow["username"];
			}
		}
		mysql_free_result($result);
		mysql_close($link);
		echo "\t\t<p>".$this->Customer_Id."</p>\n";
		echo "\t\t<p>Please enter your account details:</p>\n";
		echo "\t\t<form action=\"test2.php\" method=\"post\">\n";
		echo "\t\t<input type=\"hidden\" name=\"CustUpdate\"  value=\"1\">\n";
		echo "\t\t<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\">\n";
		echo "\t\t<tr>\n";
		echo "\t\t\t<td class=\"data_table_right\">First Name:</td>\n";
		echo "\t\t\t<td class=\"data_table_left\"><input type=\"text\" name=\"fname\" value=\"".$fname."\" size=\"32\"></td>\n";
		echo "\t\t</tr>\n";
		echo "\t\t\t<td class=\"data_table_right\">Last Name:</td>\n";
		echo "\t\t\t<td class=\"data_table_left\"><input type=\"text\" name=\"lname\" value=\"".$lname."\" size=\"32\"></td>\n";
		echo "\t\t</tr>\n";
		echo "\t\t<tr>\n";
		echo "\t\t\t<td class=\"data_table_right\">Email Address:</td>\n";
		echo "\t\t\t<td class=\"data_table_left\"><input type=\"text\" name=\"email\" value=\"".$email."\" size=\"32\"></td>\n";
		echo "\t\t</tr>\n";
		echo "\t\t<tr>\n";
		echo "\t\t\t<td class=\"data_table_right\">Phone:</td>\n";
		echo "\t\t\t<td class=\"data_table_left\"><input type=\"text\" name=\"phone\" value=\"".$phone."\" size=\"32\"></td>\n";
		echo "\t\t</tr>\n";
		echo "\t\t<tr>\n";
		echo "\t\t\t<td class=\"data_table_right\">Username:</td>\n";
		echo "\t\t\t<td class=\"data_table_left\"><input type=\"text\" name=\"username\" value=\"".$username."\" size=\"32\"></td>\n";
		echo "\t\t</tr>\n";
		echo "\t\t</table>\n";
		echo "\t\t<input type=\"submit\" value=\"Update Account Details\" class=\"submit\">\n";
		echo "\t\t</form>\n";
	}
	
	function CustDBupdate() {
		global $defaults, $_REQUEST;
		$chars = array('.', '-', ',', 'x', '(', ')', ' ');
		$cleanphone = str_replace($chars, "", $_REQUEST['phone']);
		$regexp = "([0-9]{10})";
		if  (ereg($regexp, $cleanphone)) {
			$begin = substr($cleanphone, 0, 3);
			$middle = substr($cleanphone, 3, 3);
			$end = substr($cleanphone, 6, 4);
			$link = mysql_connect($defaults["db_server"], $defaults["db_username"], $defaults["db_password"]) or die ('Could not connect: ' . mysql_error());
			mysql_select_db($defaults["db_database"]) or die('Could not select database');
			$query = "update customer set fname='".addslashes(strip_tags($_REQUEST["fname"]))."', lname='".addslashes(strip_tags($_REQUEST["lname"]))."', email='".addslashes(strip_tags($_REQUEST["email"]))."', phone='".$begin."-".$middle."-".$end."', username='".addslashes(strip_tags($_REQUEST["username"]))."' where customer_id='".$_SESSION['eshop_customer_id']."'";
			if ($result = mysql_query($query) or die('Query failed: ' . mysql_error())) {
				$error ="<p style=\"color:#BC0000; font-weight:bold;\">&curren; Account Details Sucsessfully<br>Updated! &curren;</p>\n";
				$this->UserLogged($error);
			}	
		} else {
			$error ="<p style=\"color:#BC0000; font-weight:bold;\">&curren; Phone doesn't contain enough numbers! &curren;</p>\n";
			$this->UserLogged($error);
		}
	}
	
	function LogOut() {
		unset($_SESSION['eshop_customer_id']);
		unset($_SESSION['eshop_fname']);
		unset($_SESSION['eshop_lname']);
		unset($_SESSION["eshop_customer_email"]);
		unset($_SESSION["eshop_customer_phone"]);
		unset($_SESSION["eshop_customer_cc_type"]);
		unset($_SESSION["eshop_customer_cc"]);
		unset($_SESSION["eshop_account_type"]);
		$this->login_form($error);
	}
	
	function Set_Customer_Id ($data) {
		$this->Customer_Id = $data;
	}
}

class PasswordHasher {                                                                                              
	static public function Hash($password, $withPrefix = true) {                                                                                            
		if ($withPrefix) {                                                                       
   			$hashed_password = sha1(HASH_PREFIX . $password);
		}                                      
		else {                                                                                       
   			$hashed_password = sha1($password);
		}                                                 
	return $hashed_password;                                                                   
	}                                                                                            
}
?>


#2 tobeyt23

tobeyt23
  • Members
  • PipPipPip
  • Advanced Member
  • 259 posts
  • LocationSalisbury

Posted 16 August 2006 - 02:50 AM

Do I need to start the session within the class, I currently do so in header.php? Any suggestions, hints or tips please !

#3 tobeyt23

tobeyt23
  • Members
  • PipPipPip
  • Advanced Member
  • 259 posts
  • LocationSalisbury

Posted 16 August 2006 - 11:15 AM

Still looking for a resolution?

#4 Jenk

Jenk
  • Members
  • PipPipPip
  • Advanced Member
  • 778 posts

Posted 16 August 2006 - 12:42 PM

What's the exact problem? No session data? Session not starting? Session collisions?

Also, using globals in classes is frowned upon. have a look into designing a session handler object. (NOT related to session_set_save_handler(), but the design pattern "session handler")

#5 tobeyt23

tobeyt23
  • Members
  • PipPipPip
  • Advanced Member
  • 259 posts
  • LocationSalisbury

Posted 16 August 2006 - 01:12 PM

The session starts and i can log in. After that it is like the session is closed and the user is logged out everytime i try to continue.

#6 Jenk

Jenk
  • Members
  • PipPipPip
  • Advanced Member
  • 778 posts

Posted 16 August 2006 - 01:13 PM

are you session_start()'ing at the top of every page? and before any and all output? (error messages can also be a problem as they are output before _anything_ else is.)

#7 tobeyt23

tobeyt23
  • Members
  • PipPipPip
  • Advanced Member
  • 259 posts
  • LocationSalisbury

Posted 16 August 2006 - 02:30 PM

I start the session on the index.php page referenceing the header.php which contains the sesssion_start(). This has been working with a bunch of functions and I was just trying to clean my code up and become better a coding styles. As I said once I started putting my functions in side a class they work however when I want to reference a session variable the first time they work then they don't

Example when page loads get login form. Try logging in and it checks username/password for 1. if it exist 2. the password is correct and 3.logs user in. This all work correctly but once the user is logged in I reference $_SESSION['eshop_customer_id'], to verify that the users is logged in and let them continue but that seems to be lost and kicks them back to the login form.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users