Hey all,

I'm not sure where I'm going wrong here - here's the code:

<?php
function session_init()
{
	if (!isset($_SESSION['cart']))
	{
		$_SESSION['cart'] = array();
	}

}

function productlist ()
{
	$query='SELECT pr.prId AS prId, pr.name AS name, pr.price AS price, pr.shortdesc AS shortdesc, g.image AS image, c.cId AS cId, c.desc AS colourname, c.colour AS colour FROM products AS pr, colour AS c, productstocolour AS prtoc LEFT JOIN gallery AS g ON g.gId = prtoc.FK_gId  WHERE pr.prId = prtoc.FK_prId AND prtoc.FK_cId = c.cId';

$result = mysql_query($query);


while ($row = mysql_fetch_assoc($result))
{
	echo '<div class="productlist">';
	echo '<div class="prodimg">';

	if ($row['image'] != '')
	{
		$image = 'gallery/' . $row['image'];
	}
	else
	{
		$image = 'images/noimg.gif';
	}
	echo '<img src="' . $image . '" alt="' . $row['image'] . '">';
	echo '</div>';
	echo '<div class="prodtext">';
	echo '<h4>' . $row['name'] . '</h4><h5><div style="color:' . $row['colour'] . ';">' . $row['colourname'] . '</div></h5><p>' . $row['shortdesc'] . '</p>';
	echo 'Price: &#163;' . $row['price'] . ' each <br>Size <select name="a_size[' . $row['prId'] . ':' . $row['cId'] . ']">';

	$sizequery = 'SELECT s.sId AS sId, s.size AS size FROM sizes AS s, productstosizes AS prtos WHERE prtos.FK_prId = ' . $row['prId'] . ' AND s.sId = prtos.FK_sId';
	$sizeres = mysql_query($sizequery);

	while ($srow = mysql_fetch_assoc($sizeres))
	{
		echo '<option value="' . $srow['sId'] . '">' . $srow['size'] . '</option>';
	}

	echo '</select> | <label>Quantity: <input type="text" name="a_qty[' . $row['prId'] . ':' . $row['cId'] . ']" id="quantity"size="3" value="0" /></label>';
	echo '</div>';

	echo '</div>';
}

}
function form_check()
{					
	// check to see if the form has been submitted
// and which submit button was clicked
// if this is an add operation
// add to already existing quantities in shopping cart

if ($_POST['add'])
{

foreach ($_POST['a_qty'] as $k => $v)
{

	// if the value is 0 or negative
	// don't bother changing the cart
	if ($v > 0)
	{
		$k .= ':' . $_POST['a_size'][$k];
		$_SESSION['cart'][$k] = $_SESSION['cart'][$k] + $v;


	}
}

}
// if this is an update operation
// replace quantities in shopping cart with values entered
else if ($_POST['update'])
{
	foreach ($_POST['u_qty'] as $k => $v)
	{

	// if the value is empty, 0 or negative
	// don't bother changing the cart
	if ($v != "" && $v >= 0)
	{
	//	$_SESSION['cart'][$k] = $v;
		$k .= ':' . $_POST['u_size'][$k];
		$_SESSION['cart'][$k] = $_SESSION['cart'][$k] + $v;
	}
}
}
// if this is a clear operation
// reset the session and the cart
// destroy all session data
else if ($_POST['clear'])
{
	$_SESSION = array();
	session_destroy();
}
}

function display_basket()
{
	// initialize a variable to hold total cost
$total = 0;
// check the shopping cart
// if it contains values
// look up the SKUs in the $CATALOG array
// get the cost and calculate subtotals and totals
if (is_array($_SESSION['cart']))
{
	foreach ($_SESSION['cart'] as $k => $v)
	{
		if ($v > 0)
		{

//	echo $k . ' - ' . $v . '<br>';
//	echo $_POST['a_size'][$k];
//	$k .= ':' . $_POST['a_size'][$k];
//	echo '<br>' . $k;

	$id = explode(":", $k);

	$query='SELECT pr.prId AS prId, pr.name AS name, pr.price AS price, g.image AS image, c.cId AS cId, c.desc AS colourname, c.colour AS colour FROM products AS pr, colour AS c, productstocolour AS prtoc LEFT JOIN gallery AS g ON g.gId = prtoc.FK_gId  WHERE pr.prId = prtoc.FK_prId AND prtoc.FK_cId = c.cId AND pr.prId = ' . $id[0] . ' AND prtoc.FK_cId = ' . $id[1];


	$result = mysql_query($query);

	while ($row = mysql_fetch_assoc($result))
	{
		echo '<div class="productlist">';
		echo '<div class="prodimg">';

		if ($row['image'] != '')
		{
			$image = 'gallery/' . $row['image'];
		}
		else
		{
			$image = 'images/noimg.gif';
		}
		echo '<img src="' . $image . '" alt="' . $row['image'] . '">';
		echo '</div>';
		echo '<div class="prodtext">';
		echo '<h4>' . $row['name'] . '</h4><h5><div style="color:' . $row['colour'] . ';">' . $row['colourname'] . '</div></h5>';
		echo 'Price: &#163;' . $row['price'] . ' each <br>Size <select name="u_size[' . $row['prId'] . ':' . $row['cId'] . ']">';

		$sizequery = 'SELECT s.sId AS sId, s.size AS size FROM sizes AS s, productstosizes AS prtos WHERE prtos.FK_prId = ' . $row['prId'] . ' AND s.sId = prtos.FK_sId';
		$sizeres = mysql_query($sizequery);



		while ($srow = mysql_fetch_assoc($sizeres))
		{
			echo '<option value="' . $srow['sId'] . '"';
			if ($srow['sId'] == $id[2])
			{
				echo ' selected="selected"';
			}
			echo '>' . $srow['size'] . '</option>';
		}

		echo '</select> | <label>Quantity: <input type="text" name="u_qty[' . $row['prId'] . ':' . $row['cId'] . ']" id="quantity" size="3" value="' . $v . '" /></label>';
		echo '</div>';

		echo '</div>';

		$subtotal = $row['price'] * $v;


		$total += $subtotal;

		}

	}
}
}
return $total;
}
?>

and the html:

<html>
<head>
<link href="window.css" rel="stylesheet" type="text/css" />
<link href="style.css" rel="stylesheet" type="text/css" />
<?php 
require ('includes/widgets.php');
require ('includes/database.php');

db_connect();
session_init();

?>
</head>
<body>
<form id="form1" name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div class="wrapper">
	<div class="content">
		<div class="header">
			<div class="headerleft">
				<img src="images/JSCwebmauve.jpg" height="70" /><img src="images/jsclogo.jpg" height="50" />
			</div>
			<div class="headerright">
				<img src="images/MistressCollection.jpg" height="50" /><img src="images/JHS-.jpg" height="70"/>
			</div>
		</div>
		<div class="window" style="float:left;">

		<div class="top">
			<h1>Products</h1>
		</div>
			<div class="middle">
				<div class="scrollbox">

				<?php
				form_check();

				productlist();
				?>

				</div>
		</div>
		<div class="bottom">
		</div>
	</div>
	<div class="submit">

		<input type="image" src="images/add.png" value="submit"
alt="submit" name="add">  
</div> <div class="window" style="float:right;"> <div class="top"> <h1>Basket</h1> </div> <div class="middle"> <div class="scrollbox"> <?php $total = display_basket(); ?> </div> </div> <div class="bottom"> <div style="text-align:center; margin-right:20px; margin-left:10px; padding-top:1px; width:365px; border-top:1px dotted;">Total: &#163;<?php echo sprintf("%0.2f", $total); ?> | <input name="clear" style="margin: 0; padding: 0; border: 0; background-color: transparent; font-size:10px; " type="submit" value="Clear Basket" class="submit-button" /> | <input name="update" style="margin: 0; padding: 0; border: 0; background-color: transparent; font-size:10px; " type="submit" value="Update Total" class="submit-button" /> | Checkout </div> </div> </div> </div> <div class="bottominfo"> For wedding dresses and corsets (made to order) telephone 07887 482326 or email <a href="mailto:juliahsmith@mac.com">juliahsmith@mac.com </a> </div> </div> </form> </body> </html>
  • What's supposed to happen is that when you enter quantities into the catalog and then submit (name ="add") then it adds items to the session['cart'] and displays them in a basket. When you do the same process again with another item it should add the item to the basket in the same way, so that now there are two items. However, as it stands, each time you "add" the basket only displays the most recently added item, and I'm pretty sure that means that the $_SESSION['cart'] array has been wiped and started again.

Any ideas how to make this work?

Cheers
Edd

    I don't see a session_start() anywhere in the code you posted.

      nogdog is right. you can set $_SESSION variables all day long but unless you call [man]session_start/man first, all is for naught.

        a month later

        Login.php that calls itself:

        <?php session_start() ?>
        <html>
        <head>
         <title>Login</title>
         </head>
        
         <body>
         <h2>Login</h2>
         <?php	
         	$user = $_POST['user'];
         	$pass = $_POST['pass'];
         	$links = "<a href='main.php'>To the main page</a><br /><br />";
         	$links .= "<a href='logout.php'>Click here to log out.</a>";
         	if ($user && $pass) {
         		if ($logged_in_user == $user) {
         			echo $user.", you are already logged in.<br /><br />";
         			echo $links;
         			exit;
         		}
         		$db = mysql_connect("localhost", "root");
         		mysql_select_db("userlist", $db);
         		$result = mysql_query("SELECT * FROM users WHERE name = '".$user."'
         					AND password = md5('".$pass."')");
         		if (!$result) {
         			echo "Sorry, there has been a technical hitch. We cannot enter your details.";
         			exit;
         		}
         		if (mysql_num_rows($result) > 0) {
         			$logged_in_user = $user;
         			$_SESSION['us'] = $logged_in_user;
        
        		echo "Welcome, ".$logged_in_user.".<br /><br />";
        		echo $links;
        		exit;
        	} else {
        		echo "invalid login. Please try again.<br /><br />";
        	}
        } else if ($user || $pass) {
        	echo "Please fill in both fields.<br /><br />";
        }
        
         ?>
         <form method=post action="login.php">
         Your username:
         <input name="user" type=text maxlength=20 size=20>
         <br />
         Your password:
         <input name="pass" type=password maxlength=10 size=10>
         <br />
         <input type=submit value="login">
         </form>
         </body>
         </html>

        Login works now. But when proceeding to next page (either main.php or logout.php I get message Session not set! with this piece that I put into.

         	if (!isset($_SESSION['us'])) {
         		echo "Session not set!";
         	}

        Bare in mind that these are based on some 2002 tutorial (PHP4 that is): is there anything else left that should be "converted" to PHP5?

          Thanks guys, problem solved.

          Cheers
          Edd

            you may want to change this,
            even if it does not often happen,
            that anyone would try to login if isalready logged in

            the test for if is logged in already may be even before everything else

            but anyway, there is no value $logged_in_user, in beginning of this script

             <h2>Login</h2>
            <?php    
            $user = $_POST['user']; $pass = $_POST['pass']; $links = "<a href='main.php'>To the main page</a><br /><br />"; $links .= "<a href='logout.php'>Click here to log out.</a>"; if ($user && $pass) { if ( isset($_SESSION['us']) && $_SESSION['us'] == $user ) { //if ($logged_in_user == $user) // etc ?>

              This is the code that my PHP4 guide wrote:

              <?
              
              // keep hyperlinks in a string variable
              $links = "<A HREF='main.php'>Click here to proceed to the main page</A><BR><BR><A HREF='logout.php'>Click here to log out.</A>";
              
              // check to see if details have been passed to the script by the form
              if ($user && $pass) {
              
              	// if already logged in *as this user*, let them know, and show them the links.
              	// .. of course, if they are logged in as someone else, let them log in as a different user
              	if ($logged_in_user == $user) {
              		echo $user.", you are already logged in.<BR><BR>";
              		echo $links;
              		exit;
              	}
              
              	// connect to database and select 'userlist' database
              	$db = mysql_connect("localhost");
              	mysql_select_db("userlist", $db);
              
              	// check input variables against database
              	$result = mysql_query("SELECT * FROM users WHERE name = '".$user."'
              					AND password = PASSWORD('".$pass."')");
              
              	// in case of an error, throw up an error message and exit
              	if (!$result) {
              		echo "Sorry, there has been a technical hitch. We cannot enter your details.";
              		exit;
              	}
              
              	// greet valid user and show links
              	if (mysql_num_rows($result) > 0) {
              		$logged_in_user = $user;
              		session_register("logged_in_user");
              		echo "Welcome, ".$logged_in_user.". <BR><BR>";
              		echo $links;
              		exit;
              
              	// on invalid login, show user HTML form to login again
              	} else {
              		echo "Invalid login. Please try again.<BR><BR>";
              	}
              
              // in case user only fills in one field, show error message and HTML form ..
              } else if ($user || $pass) {
              	echo "Please fill in both fields.<BR><BR>";
              }
               ?>
               <FORM METHOD=POST ACTION="login.php">
               Your username:
               <INPUT NAME="user" TYPE=TEXT MAXLENGTH=20 SIZE=20>
               <BR>
               Your password:
               <INPUT NAME="pass" TYPE=PASSWORD MAXLENGTH=10 SIZE=10>
               <BR>
               <INPUT TYPE=SUBMIT VALUE="Login">
               </FORM>

              As you see there isn't any $_POST, etc. that should go with PHP5. What intrigues me is...

              ... this line

              if ($logged_in_user == $user) {

              Can he declare $logged_in_user before puting in $logged_in_user = $user?

              ....and this part of code:

              // greet valid user and show links
                      if (mysql_num_rows($result) > 0) {
                          $logged_in_user = $user;
                          echo "Welcome, ".$logged_in_user.". <BR><BR>";
                          echo $links;
                          exit;

              session_register("logged_in_user"); is obviously obsolete with PHP5 so $_SESSION should be used instead.

              I wrote

              $_SESSION['us'] = $user

              and session still wasn't set!

                3 months later

                Still can't get it to work. Succesfully loging in (with login.php) but when I (try to🙂 ) transfer the user's data to main.php problem arises.

                With this piece I try to check whether $SESSION is set...

                if (!isset($_SESSION['us'])) {
                        echo "Session not set!";
                    } else {
                    	echo "Session set.";
                    }

                ...and it says Session set.!

                Login.php:

                <?php 
                session_start();
                require "forum.php";
                
                $user = $_POST['user'];
                $pass = $_POST['pass'];
                $links = "<a href='main.php'>To the main page</a><br /><br />";
                $links .= "<a href='enter.php'>Click here to log out.</a>";
                if ($user && $pass) {
                	if ($logged_in_user == $user) {
                 		setup_page("Already logged in", "Whoops");
                 		echo $user.", you are already logged in.<br /><br />";
                 		echo $links;
                 		exit;
                 	}
                	doConnect();
                 	$result = mysql_query("SELECT * FROM users WHERE name = '".$user."'
                 					AND password = md5('".$pass."')");
                 	if (!$result) fail ("database query failed, login page", true);
                 	if (mysql_num_rows($result) > 0) {
                 		$record = mysql_fetch_assoc($result);
                 		$logged_userID = $record["userID"];
                 		$_SESSION['userID'] = $logged_userID;
                 		$logged_in_user = $user;
                 		$_SESSION['us'] = $logged_in_user;
                 		if ($record["mod"]) {
                 			$logged_as_mod = TRUE;
                 			$_SESSION['us'] = $logged_as_mod;
                 		}
                 		setup_page("Welcome", "Welcome");
                 		echo $links;
                 		exit;
                 	} else {
                 		setup_page("Invalid", "Invalid login");
                 		echo "That username-password combination does not appear to match our records. 
                 			Please 	try again.";
                 	}
                } else if ($user || $pass) {
                	setup_page("Invalid", "Invalid login");
                	echo "Please fill in both fields.<br /><br />";
                } else {
                	setup_page("Login", "Login");
                	echo "Please enter your details to log in.";
                }
                
                 ?>
                 <form method=post action="login.php">
                 Your username:
                 <input name="user" type=text maxlength=20 size=20>
                 <br />
                 Your password:
                 <input name="pass" type=password maxlength=10 size=10>
                 <br />
                 <input type=submit value="Login">
                 </form>
                 </body>
                 </html>

                Main.php:

                //extracted piece from main.php that (together with external script) outputs:
                //"Sorry. There has been an error (not logged in)."
                if (!$logged_userID) {
                	fail ("not logged in", true);
                }

                I strongly suspect that the problem lies in

                if ($logged_in_user == $user) {...........}...
                
                ...$_SESSION['userID'] = $logged_userID;
                        $logged_in_user = $user;
                        $_SESSION['us'] = $logged_in_user;
                ...

                halojoy also warned me: "but anyway, there is no value $logged_in_user, in beginning of this script". Should I declare $logged_in_user before? How?

                • that also main.php requires !$logged_userID NOT $logged_in_user

                EDIT: Is it alright to use two $SESSIONs ($SESSION['us'] and $_SESSION['userID'])?

                  When adapting the modest login page (made from scratch from previous tutorial), my PHP(4) guide added these two lines after MySQL query (in the later part of the tutorial):

                   		$record = mysql_fetch_assoc($result);
                   		$logged_userID = $record["userID"];

                  Doing so, he was saying "whereas before (that is, with simple login page) we didn't have to actually do anything with that data we just had to make sure it was found"

                  This part of the PHP4 code (which I presume produces problems) now looks like

                  	dbConnect();
                  	$result = mysql_query("SELECT * FROM users WHERE name = '".$user."'
                  					AND password = PASSWORD('".$pass."')");
                  
                  	// find the userID and register it as a session variable
                  	$record = mysql_fetch_assoc($result);
                  	$logged_in_user = $user;
                  	session_register("logged_in_user");
                  	$logged_userID = $record["userID"];
                  	session_register("logged_userID");

                  Now, (trying) to convert it to PHP5, I wrote

                  	dbConnect();
                   	$result = mysql_query("SELECT * FROM users WHERE name = '".$user."'
                   					AND password = md5('".$pass."')");
                  
                  	$record = mysql_fetch_assoc($result);
                  	$logged_in_user = $user;
                  	$_SESSION['us'] = $logged_in_user;
                      $logged_userID = $record["userID"];
                  	$_SESSION['userID'] = $logged_userID;

                  BTW, should I write instead

                  $_SESSION['us'] = $logged_userID;

                  so that there are 2 same associative $_SESSION keys?

                  EDIT:
                  Now I've rechecked my main.php with this piece:

                  echo "UserID: ".$_SESSION['userID']."<br />";
                  
                  if (!$logged_userID) {
                  	fail ("not logged in", true);
                  }

                  if statement still gets carried out, although echo outputs UserID: 11

                    Okay, your issue here is that you don't fully understand what register globals does, and how it's changed between php4 and php5.

                    Each php version below php5 has had register globals turned on. What this means is that those array keys in the $POST, $GET, $SESSION, $COOKIE, $REQUEST, $HTTP*VARS each become variable names, and the values translate over to the variable values. For example, in PHP 4, this would output the same:

                    <?php
                    session_start();
                    $_SESSION['myName'] = 'bpat1434';
                    
                    echo 'My Name Is: ' . $myName;
                    
                    echo 'My Name Is: ' . $_SESSION['myName'];

                    Notice how the array key "myName" becomes a variable with registered globals turned on? Now, in php5, it's turned off by default, which means that everything we thought was a variable before, is no longer. So we have to explicitly use $SESSION, $POST, $GET, $REQUEST, $_COOKIE. So in PHP5, $logged_userID is an uninitialized variable. So your code asks to see if "$logged_userID" evaluates to false. Since it's uninitialized, it should return null or an empty string in which case that equates to false, and as such, your if() statement will fire.

                    This is going to sound like a lot of work for you, but in order ot fix it, you have to walk through all of your code, and remove any register globals dependent items. It may take you time to look through and figure out if it's truly part of a global item, or whether it's just another variable. So if you find it taking you too long, just redo it.

                      That helped a lot.

                      It should look like

                      if (!$_SESSION['userID']) {
                      	fail ("not logged in", true);
                      }

                      right?

                      Can I also "pass on" $SESSION's value from login.php to new variable on main.php like this

                      $userID = $_SESSION['userID'];
                      if (!$userID) {
                      	fail ("not logged in", true);
                      }

                      Could this be potentially security troublesome?

                        Yes, both of those are correct. Although please remember, if you do set a local variable like that in your second example, if you modify $userID, you will not modify the $_SESSION value. So be careful using this type of coding.

                        For session security, you'd want to make sure that they're handled on the server (i.e. not "cookies"). For good session security, you'll need to do more though. There are many books on the subject of security. As a start, I suggest you read Chris Shiflett's book "Essential PHP Security" for a good security start. It covers all the basic essentials of security (as the title hints) and gives you a good base to stand upon.

                          It should look like

                          More likely:

                          if (empty($_SESSION['userID'])) {
                              fail("not logged in", true);
                          }

                          Can I also "pass on" $_SESSION's value from login.php to new variable on main.php like this

                          Of course, but if there is no good reason to have another variable, don't do it.

                          Could this be potentially security troublesome?

                          No, unless register_globals is not set to off and you somehow take out the line that initialises $userID. As a matter of good practice, register_globals should be off.

                            Write a Reply...