Page 1 of 2

need help with cookies

Posted: Wed Nov 28, 2012 1:44 pm
by beginner123
in my webiste i am just using sessions to log the users on, so when the browser closes the user gets logged out.

now i want to add cookies but i am not sure how. I created a remember me checkbox in the form so when the user clicks that it should create the cookie.

here is my code for sigining into the website:

Code: Select all

echo '<h3>Sign in</h3><br />';

//first, check if the user is already signed in
if(isset($_SESSION['signed_in']) && $_SESSION['signed_in'] == true)
{
	echo 'You are already signed in, you can <a href="signout.php">sign out</a> if you want.';
}
else
{
	if($_SERVER['REQUEST_METHOD'] != 'POST')
	{
		//the form hasn't been posted yet, display it
		echo '<form method="post" action="">
			Enter Username: <input type="text" name="userName" /><br />
			Enter Password: <input type="password" name="userPassword"><br /><br/>
			<input type="checkbox" name="remember" value="1">Remember Me <br /><br/>
			<input type="submit" value="Sign in" />
		 </form>';
	}
	else
	{
		$errors = array(); // declare the array for the errors
		
		
		
		if(!isset($_POST['userName']))
		{
			$errors[] = 'The username field must not be empty.';
		}
		
		if(!isset($_POST['userPassword']))
		{
			$errors[] = 'The password field must not be empty.';
		}
		
		if(!empty($errors)) 
		{
			echo 'A couple of fields are not filled in correctly<br /><br />';
			echo '<ul>';
			foreach($errors as $key => $value) //check array
			{
				echo '<li>' . $value . '</li>'; //make error list
			}
			echo '</ul>';
		}
		else
		{
			//mysql_real_escape_string is to keep the data save
			//the sha1 function hashes the password
			$sql = "SELECT 
						userID,
						userName,
						userLevel
					FROM
						users
					WHERE
						userName = '" . mysql_real_escape_string($_POST['userName']) . "' 
					AND
						userPassword = '" . sha1($_POST['userPassword']) . "'";
						
			$result = mysql_query($sql);
			if(!$result)
			{
				echo 'Something went wrong while signing in. Please try again later.';
				//echo mysql_error(); 
			}
			else
			{
				//the query returned an empty result so the data was wrong
				if(mysql_num_rows($result) == 0)
				{
					echo 'You have supplied a wrong user/password combination. <a href="signin.php">Please try again</a>.</br>';			
				}
				
				else
				{
					//sign in successful
					$_SESSION['signed_in'] = true;
					
					while($row = mysql_fetch_assoc($result))
					{
						$_SESSION['userID'] 	= $row['userID'];
						$_SESSION['userName'] 	= $row['userName'];
						$_SESSION['userLevel'] = $row['userLevel'];
					//}
					//if($_SESSION['userLevel'] == 1 || $_SESSION['userLevel'] == 0) //can only sign in if they are admin or normal user
					//{
						echo 'Welcome, ' . $_SESSION['userName'] . '. <br /><a href="index.php">Return to home page</a>.<br/>';
						echo '<meta http-equiv="Refresh" content="2;url=index.php" />';
						
					}
				}
	
			}
		}
	}
}
i also have a userbar that is displayed on every page with links to sign in or create an account:

Code: Select all

session_start();
		if(isset($_SESSION['signed_in']) == true)
		{
			echo 'Hello <b>' . ($_SESSION['userName']) . '</b>. <a href="signout.php">Sign out</a>';
		}
		else
		{
			echo '<a href="signin.php">Sign in</a> or <a href="signup.php">create account</a>';
		}

Re: need help with cookies

Posted: Wed Nov 28, 2012 2:13 pm
by Christopher
beginner123 wrote:now i want to add cookies but i am not sure how.
http://php.net/manual/en/features.cookies.php

Re: need help with cookies

Posted: Wed Nov 28, 2012 3:16 pm
by beginner123
sorry but that link doesn't help me

Re: need help with cookies

Posted: Wed Nov 28, 2012 3:16 pm
by Benjamin

Re: need help with cookies

Posted: Wed Nov 28, 2012 3:25 pm
by beginner123
not the kind of cookies i need help with :lol:

Re: need help with cookies

Posted: Wed Nov 28, 2012 6:09 pm
by califdon
It seems you haven't explained what you want to do or what isn't working.

Re: need help with cookies

Posted: Thu Nov 29, 2012 12:54 pm
by beginner123
right now i am just using sessions to log a user in but now i want to add cookies.
I am not sure how to do that since i am using sessions. Do i need to replace the sessions with cookies?

Re: need help with cookies

Posted: Thu Nov 29, 2012 1:13 pm
by califdon
I'm afraid you're still not expressing what you want to do. "I want to add cookies" doesn't mean much of anything. WHY do you want to add cookies? What you must explain is what it is that you are trying to accomplish, rather than just say you want to use some particular technique.

Re: need help with cookies

Posted: Thu Nov 29, 2012 2:24 pm
by beginner123
sorry if i am unclear what i'm trying to do. Since i am only using sessions the user will get logged out if they close down the browser.
I want to add cookies to my website so if the user clicks the remember me checkbox in the sign in form, they will still be signed in when they return to the website.

Re: need help with cookies

Posted: Thu Nov 29, 2012 3:35 pm
by Christopher
So back to: http://php.net/manual/en/features.cookies.php (it's not that much to read and really worth it!)

To set a cookie:

Code: Select all

setcookie("TestCookie", $value);
To read a cookie:

Code: Select all

echo $_COOKIE["TestCookie"];

Re: need help with cookies

Posted: Thu Nov 29, 2012 4:00 pm
by beginner123
but where would i put that in my code? and how do i set the cookie only when the user clicks the remember me checkbox?

Re: need help with cookies

Posted: Thu Nov 29, 2012 4:21 pm
by twinedev
What I am gathering is that they need the cookie to set so that when they come back the site knows their login information they were last logged in as (assuming the cookie hasn't expired and that they didn't do a logout.

Along the lines discussed on this post: http://stackoverflow.com/questions/7214 ... t-practice

-Greg

Re: need help with cookies

Posted: Thu Nov 29, 2012 5:21 pm
by beginner123
yes thank you Greg that is exactly what i am trying go do.
so what should i add to my code to do that?

Re: need help with cookies

Posted: Thu Nov 29, 2012 8:22 pm
by califdon
First, decide what text will be in your cookie and assign that to $value (or whatever name you may give it--I'm using Christopher's example code, above). That might be just the username, or perhaps the most recent login date, or whatever. Then, if you want to only set the cookie when the "remember me" box is checked, you could either set the cookie with Javascript, in the onChecked event, or assuming that the checkbox is part of a form that is going to be received as form data in your process, you could simply check the value of the "remember me" box when you receive that data, then use that to determine your PHP processing. As to when you read the cookie, that all depends on what actions you are going to take depending on whether the user is logged in or not. Probably the most versatile way to do it is to always try to read the cookie with Javascript at the beginning of the script and if it exists, set one or more session variables so that PHP can then determine whatever is dependent on that.

There are endless ways to do all this. That's why just asking "How (or where) do I set a cookie" is meaningless. The answer will be different for every different application.

Re: need help with cookies

Posted: Fri Nov 30, 2012 3:48 pm
by beginner123
ok so i added some code to set a cookie but i am getting the error unidentfied index: rememberme

here is all my code for the sign in page:

Code: Select all

echo '<h3>Sign in</h3><br />';

//first, check if the user is already signed in
if(isset($_SESSION['signed_in']) && $_SESSION['signed_in'] == true)
{
	echo 'You are already signed in, you can <a href="signout.php">sign out</a> if you want.';
}
else
{
	if($_SERVER['REQUEST_METHOD'] != 'POST')
	{
		//the form hasn't been posted yet, display it
		echo '<form method="post" action="">
			Enter Username: <input type="text" name="userName" /><br />
			Enter Password: <input type="password" name="userPassword"><br /><br/>
			<input type="checkbox" name="rememberme">Remember Me <br /><br/>
			<input type="submit" value="Sign in" />
		 </form>';
		 
		 
	}
	else
	{
		$errors = array(); // declare the array for the errors
		
		
		
		if(!isset($_POST['userName']))
		{
			$errors[] = 'The username field must not be empty.';
		}
		
		if(!isset($_POST['userPassword']))
		{
			$errors[] = 'The password field must not be empty.';
		}
		
		if(!empty($errors)) 
		{
			echo 'A couple of fields are not filled in correctly<br /><br />';
			echo '<ul>';
			foreach($errors as $key => $value) //check array
			{
				echo '<li>' . $value . '</li>'; //make error list
			}
			echo '</ul>';
		}
		else
		{
			//mysql_real_escape_string is to keep the data save
			//the sha1 function hashes the password
			$sql = "SELECT 
						userID,
						userName,
						userLevel
					FROM
						users
					WHERE
						userName = '" . mysql_real_escape_string($_POST['userName']) . "' 
					AND
						userPassword = '" . sha1($_POST['userPassword']) . "'";
						
			$result = mysql_query($sql);
			if(!$result)
			{
				echo 'Something went wrong while signing in. Please try again later.';
				//echo mysql_error(); 
			}
			else
			{
				//the query returned an empty result so the data was wrong
				if(mysql_num_rows($result) == 0)
				{
					echo 'You have supplied a wrong user/password combination. <a href="signin.php">Please try again</a>.</br>';			
				}
				
				else
				{
					//sign in successful
					$_SESSION['signed_in'] = true;
					
					while($row = mysql_fetch_assoc($result))
					{
						$_SESSION['userID'] 	= $row['userID'];
						$_SESSION['userName'] 	= $row['userName'];
						$_SESSION['userLevel'] = $row['userLevel'];

						$rememberme = $_POST['rememberme']; //this is where the error is
						
						if($rememberme == "on")
						{
							setcookie("userName",$userName, time() +7200);
						}
						else if($rememberme == "")
						{
							$_SESSION['userName'];
						}

						echo 'Welcome, ' . $_SESSION['userName'] . '. <br /><a href="index.php">Return to home page</a>.<br/>';
						echo '<meta http-equiv="Refresh" content="2;url=index.php" />';
					}
			
				}
		
			}
		}
	}
}