Jump to content

Need help setting cookies with my sessions


CStrauss

Recommended Posts

I have always used sessions and have a pretty good understanding how they work, now i want to try what i normally see around the web with other sites where they have a login box that has a check box that says remember me. So now i need to figure out the best way to modify my current login script to allow cookies. Here is the codesbasic html form with a check box to let the user be remembered

	<?php		if($_SESSION['login'] != true){	?>		<form action="/login.php" method="post">		<p><label for="1">Username:</label><input type="text" id="1" name="username" /></p>		<p><label for="2">Password:</label><input type="password" id="2" name="password" /></p>		<p>			<input type="hidden" name="req" value="validate" />			<input type="submit" name="submit" value="Go!" /> Remember me!<input type="checkbox" name="cookie" checked="checked" />			</p>		</form>		<p>Not a member yet? <a href="/join.php">Register Here</a></p>	<?php		}else{			echo '<p>Welcome '.$_SESSION['username'].'</p>'.			'<p>To Logout <a href = "logout.php"> click here</a></p>';			}	?>

Here is my actual login script that checks info with database and sets the sessions.

	$validate = @mysql_query("SELECT * FROM members WHERE username='{$_POST['username']}' AND		password = md5('{$_POST['password']}') AND verified = '1'");			if(mysql_num_rows($validate) == 1){		while($row = mysql_fetch_assoc($validate)){			$_SESSION['login'] = true;			$_SESSION['userid'] = $row['id'];			$_SESSION['first_name'] = $row['first_name'];			$_SESSION['last_name'] = $row['last_name'];			$_SESSION['email_address'] = $row['email_name'];			$_SESSION['username'] = $row['username'];						if($row['admin_access'] == 1){				$_SESSION['admin_access'] =true;			}			}		$login_time = mysql_query("UPDATE members SET last_login=now() WHERE id='{$row['id']}'");	}	 header("Location: /index.php");	}else{		myheader(" - Login Failed!");		echo '<p>Login Failed</p>';		echo '<p>If you have already joined our website, you may need to validate '.			 'your email address. Please check your email for instructions.';		footer();	}

Now i was reading another post and it suggest setting the cookies the same as your session variables to keep them synchronized, which makes sense, and then still use the session variables. But i have seen so many examples its really kinda of confused me so I posted my code hoping someone can look over it and show me the best way to do it that way i can see and understand better with my own code and what not and how to implement it all.Also after I got my cookies set after the use has logged in and opted to be "remember" how do i work that in with my session on the condition where it checks the session to see if user is logged in or not?Thanks for any advice in advance sorry if this is a redundent post, I did a search before but like i said I saw so many examples it just confused me a bit more then needed. :)

Link to comment
Share on other sites

You don't need to name your cookies the same as the sessions necessarily. It's not a bad idea to be consistent though. What you want to do to check if someone is logged in is to first check if the cookie is there, and if it is, copy whatever is in the cookie into the session. Then check the session as normal. When you check the session, if they have a cookie, the info will be in the session.Also, make sure that if you make any changes to the session that you also update the cookie if necessary.As far as setting the cookie goes, you will want to have your login form be processed by one of those pages you have probably seen that says something like 'thank you for logging in, you are being redirected'. The purpose of those pages is to set the session and the cookie. If you try setting a cookie and then sending a Location header, sometimes the browser will ignore the cookie header and just redirect. So you need to set the cookie on a page that shows output, like the 'you are being redirected' page, and then use a meta refresh tag to send them where you want them to go after X number of seconds.http://www.seologic.com/faq/meta-refresh-tag.php

Link to comment
Share on other sites

So if I understand you correctly using my code exampel above when they loggin add a section before the session to check for cookies if so then set session. if not set cookies then session in say an else clause correct?I will play around and post back with any success(hopes for) or problems I have thanks for the tip justsomeguy

Link to comment
Share on other sites

Well, I'll show you what I do. I use this code in most of my things.

################################################################################ standard session variable array:#   this is where all standard session variables are declared.#   the variable name is pushed onto the SESSION_VAR_NAMES array, and then#	a variable is declared with each variable name and corresponding#	session value.###############################################################################  $SESSION_VAR_NAMES = array();  array_push($SESSION_VAR_NAMES, 'USER_LOGIN_ID');  array_push($SESSION_VAR_NAMES, 'USER_LOGIN_PW');############################################################################################################################################################### this retrieves the session variables for use in a page.###############################################################################  for ($i = 0; $i < count($SESSION_VAR_NAMES); $i++)  {	  global $$SESSION_VAR_NAMES[$i];	if (!empty($_SESSION[$SESSION_VAR_NAMES[$i]]))	  $$SESSION_VAR_NAMES[$i] = $_SESSION[$SESSION_VAR_NAMES[$i]];	else	  $$SESSION_VAR_NAMES[$i] = "";  }############################################################################################################################################################### check for uid/pw in cookie.###############################################################################  if (!empty($_COOKIE[$COOKIE_NAME . "UID"]))	$USER_LOGIN_ID = $_COOKIE[$COOKIE_NAME . "UID"];  if (!empty($_COOKIE[$COOKIE_NAME . "UPW"]))	$USER_LOGIN_PW = $_COOKIE[$COOKIE_NAME . "UPW"];###############################################################################

So let me explain a little how it works. At the top, there is a global session variable array that stores all of my session variable names. I create global variables to hold things in the session, so I'm defining the variable names in the array.The second section loops through that array and declares the global variable and then sets whatever is in the $_SESSION array to it. So, for example, since I have a string called USER_LOGIN_ID in the array, the second section will delcare a global variable called $USER_LOGIN_ID, and then assign it the value that is in $_SESSION['USER_LOGIN_ID'] if it is there, or "" if it is not.The third section checks in the $_COOKIE array and copies the value of the cookie (if it is set) into the global variable. The reason I have the third part just laid out instead of in the loop above is because I didn't want my global variable name (USER_LOGIN_ID) to be the cookie name, I wanted to add a prefix to the cookie name. So I have a global variable somewhere else called $COOKIE_NAME and I put that on it before. So if I set $COOKIE_NAME to "just_some_login_system_" or something, then this:if (!empty($_COOKIE[$COOKIE_NAME . "UID"]))Will check for a cookie called "just_some_login_system_UID", and save the value in the global variable. Then I have my authentication function check the $USER_LOGIN_ID and $USER_LOGIN_PW variables against the database.Since I'm not using $_SESSION directly in my other pages, if I make any change to $USER_LOGIN_ID or $USER_LOGIN_PW on a page then I call this function to copy everything back into the session:

################################################################################ write session#   this function copies ALL session variables back into the session.###############################################################################function write_session(){  global $SESSION_VAR_NAMES;  for ($i = 0; $i < count($SESSION_VAR_NAMES); $i++)  {	  global $$SESSION_VAR_NAMES[$i];	$_SESSION[($SESSION_VAR_NAMES[$i])] = $$SESSION_VAR_NAMES[$i];  }  session_write_close();}###############################################################################

Since this closes the session, it should be called only once per page. This code doesn't update the cookie also though, I just make an explicit call to setcookie when I want to do that.

Link to comment
Share on other sites

thanks alot justsomeguy, that was very good explination, gives me a better visual to play around with. I didnt get much chance to play with it the last few days was out at the football game all day yesterday but anyways, I got a lot of free time today so im going to sit down and experiment with my cookies :) When I come up with something on my own I will post back and show the world what I have accomplished anyways thanks again.

Link to comment
Share on other sites

Okay I tried to go back to basics to get an idea how to make cookies and sessions play nicely together and trying to follow your advice it seems i messed something up here is what I did just made some basic code pages to try to get them to work together.here is my form

<!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>Untitled Document</title></head><body><form action="validate.php" method="post"><p><label>Username</label><input type="text" name="username" /></p><p><label>Password</label><input type="password" name="password" /></p><p><label>Set Cookie</label><input type="checkbox" name="cookie" value="yes" /></p><p><input type="submit" value="Go!" name="submit" /></p></form></body></html>

here is the page the form sends you to to validate information (my database info left out for obvious reasons) :)

		// Database connection here$validate = @mysql_query("SELECT * FROM members WHERE username='{$_POST['username']}' AND			password = md5('{$_POST['password']}')");			if(mysql_num_rows($validate) == 1){		while($row = mysql_fetch_assoc($validate)){			// if cookies 			if($_POST['cookie'] == "yes"){				setcookie("username",$row['username'],time(5));				$_SESSION['username'] = $_COOKIE['username'];			}else{				$_SESSION['username']=$row['username'];			}		}		header("Location: /test/results.php");	}else{		echo "Wrong username and password!";	}?>

Then if user info is correct goes to this page to show results

	<?phpsession_start();session_name('2am-designs');header("Cache-control: private"); // Fix for IE?><!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>Untitled Document</title></head><body><?php	if(isset($_COOKIE['username'])){		echo "Cookie User name is set to ".$_COOKIE['username']."<br />";		echo "Session is set to ".$_SESSION['username']."<br />";	}else{		echo "Cookie is not set but Session is set to ".$_SESSION['username'];	}?></body></html>

Now what it seems to be doing is the opposite on the last page if i have the check box to set a cookie it shows the else statement on the last page omitting the $_SESSION['username']. just showing the string text.And If I check the check box to not set the cookie it shows the if statement showing the first line of echo correctly but not showing the $_SESSION['username'] value.Now I did something wrong here perhaps its the checkbox value messing things up or maybe Im doing this whole thing wrong. Can you see something wrong?

Link to comment
Share on other sites

There are some problems here:

		while($row = mysql_fetch_assoc($validate)){			// if cookies 			if($_POST['cookie'] == "yes"){				setcookie("username",$row['username'],time(5));				$_SESSION['username'] = $_COOKIE['username'];			}else{				$_SESSION['username']=$row['username'];			}		}		header("Location: /test/results.php");

The first problem is that you set the cookie on one line, and then the next line you try to read from it. That won't work, because of how cookies are sent. When the browser makes a request to the server, it sends all of the cookies at that point. So, the only cookies you have available to you are cookies that the browser already sent, any new cookies you set will not be available on the same page. So you are probably setting the session variable equal to "", since the cookie is not set.The other problem is that you are setting the cookie and then redirecting using a header. This doesn't work very well for all browsers, some browsers see the redirect header and ignore everything else, including the cookie. The best thing to do to solve both of these problems is to have your form submit to a page that says "thank you, you are being redirected" where you can set the cookie, and then use a meta refresh tag like I linked to above to send the user to whichever page you want. When they get to that next page, the cookie will have already been set and you will have access to it.

Link to comment
Share on other sites

The best thing to do to solve both of these problems is to have your form submit to a page that says "thank you, you are being redirected" where you can set the cookie, and then use a meta refresh tag like I linked to above to send the user to whichever page you want. When they get to that next page, the cookie will have already been set and you will have access to it.
Okay bear with me im still trying to figure this out, im a little confused by your solution so to see if im understanding it correctly when they submit the form create a page that says thank you being redirected and on that page set the cookies then use the meta refresh tag to send them to another page. That part I think i got so then on the next page do i copy my cookie variables into my session variables or do I copy my session variables on the same page im setting the cookies.(This assuming the user name and password have been checked against the database). Is this what you meant?
Link to comment
Share on other sites

Okay after a few days of playing around with all this trying to make something easy for me to follow and understand I almost got.First I tested loging in with out choosing to set cookies and it works fine.Then I login in with cookies and it stores my cookies and sessions correctly.But when I close the browser and open it something goes wrong. My cookie info is still there but the session variables I need do not get stored so I will post all my work up to this point and hopefully someone can tell me what I need to change to make session varables be stored when someone returns to the site.my index page.

session_start();session_name('2am-designs');header("Cache-control: private"); // Fix for IEinclude $_SERVER['DOCUMENT_ROOT'].'/inc/database.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>Untitled Document</title></head><body><?php 	if(isset($_COOKIE['login'])){		$username = $_COOKIE['username'];		$password = $_COOKIE['password'];		$validate = @mysql_query("SELECT * FROM members WHERE username='$username' AND					password = md5('$password')");		if(mysql_num_rows($validate) == 1){			while($row = mysql_fetch_assoc($validate)){				$_SESSION['login'] = true;				$_SESSION['username'] = $row['username'];			} // End While		}// End If		echo "Session username is set to ".$_SESSION['username']."<br />";		echo "Session Login in set to = ".$_SESSION['login']."<br />";		echo "Cookie Username = ".$_COOKIE['username']."<br />";		echo "Cookie Password = ".$_COOKIE['password']."<br />";		echo "Cookie Login Value = ".$_COOKIE['login']."<br />";		echo '<a href="/test/destroy.php">Destroy</a>';			}elseif(isset($_SESSION['login'])){		echo "Session username is set to ".$_SESSION['username']."<br />";		echo "Session Login in set to = ".$_SESSION['login']."<br />";		echo "Cookie Username = ".$_COOKIE['username']."<br />";		echo "Cookie Password = ".$_COOKIE['password']."<br />";		echo "Cookie Login Value = ".$_COOKIE['login']."<br />";		echo '<a href="/test/destroy.php">Destroy</a>';			}else{		?><form action="validate.php" method="post"><p><label>Username</label><input type="text" name="username" /></p><p><label>Password</label><input type="password" name="password" /></p><p><label>Set Cookie</label><input type="checkbox" name="remember" /></p><p><input type="submit" value="Go!" name="submit" /></p></form><?php } // End Else ?></body></html>

My Logic: if cookies where set it logs in user and and sets the session variables. In this case im outputting my variables to see they are there.(im paranode I know).If they dont have cookies set (the elseif) is checking to see if the member is logged on and displaying information that can only be seen if they are logged on. Meaning if they have been on surfing my site their info is there.And finally if they are not logged on to the site show them a form.**NOTE All ALL THE DESTROY LINK DOES IS DESTROY MY SESSIONS AND VARIABLES FOR TESTING PURPOSES.**Now here is my vaidation if they are logging on to the site for the first time or if they did not set cookies from a previous visit.

<?phpsession_start();session_name('2am-designs');header("Cache-control: private"); // Fix for IEinclude $_SERVER['DOCUMENT_ROOT'].'/inc/database.php';$validate = @mysql_query("SELECT * FROM members WHERE username='{$_POST['username']}' AND			password = md5('{$_POST['password']}')");		if(mysql_num_rows($validate) == 1){			while($row = mysql_fetch_assoc($validate)){				if(isset($_POST['remember'])){				setcookie("login",true,time()+60*60*24*100,"/");								setcookie("username",$row['username'],time()+60*60*24*100,"/");				setcookie("password",$row['password'],time()+60*60*24*100,"/");				$_SESSION['login'] = true;				$_SESSION['username']=$row['username'];					}else{					$_SESSION['login'] = true;					$_SESSION['username'] = $row['username'];				}			}// End While			echo '<meta http-equiv="Refresh" content="4;url=http://localhost/test/index.php">';			}else{			echo "Invalid Login Information";		}?>

This should be self explanitory it first checks the username and password from the form and if they have the remember me feature checked it sets the cookies. If not just sets some session variables then takes them back to the index page where it displays all my varaibles I have set.Now all this code is working fine until I close my browser and reopen when testing my remember me feature again the cookie variables are display but i can not get my sessions to be set on return visits. I have come up with nothing with every thought possible is to why this is happening which means to me its something so simple that i need a fresh pair of eyes to point it out to me. So if anyone has an explination to what i need to fix please let me know. thanks

Link to comment
Share on other sites

The only thing I can think of is that this query is not returning anything:

		$validate = @mysql_query("SELECT * FROM members WHERE username='$username' AND					password = md5('$password')");		if(mysql_num_rows($validate) == 1){			while($row = mysql_fetch_assoc($validate)){				$_SESSION['login'] = true;				$_SESSION['username'] = $row['username'];			} // End While		}// End If

Print out the query and check the database yourself to make sure the right username/password combo is there. It looks like you might be using md5 an extra time and changing the password. The password you store in the cookie should be the md5 hash, so you should be able to check that against the database without using md5 again.

Link to comment
Share on other sites

Thanks justsomeguy that seemed to be it the md5 hash. Things seem to be working for now. Thanks for all your help now i got something new to play with and add to my php tool box. Now im just going to test and try to break it in everyway possible. Call me sick but thats the fun part to me after I write some code is trying everything possible to break it and get errors and what not. anyways thanks again.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...