Previous Page

Let user stay logged in by letting them create a "Remember me" cookie



Click on the following link to try it out. Try me!



You can insert the following code above the html portion of your new .php document

<?php 

session_name('bcbLogin');
// use before setting cookie params

session_set_cookie_params(2*7*24*60*60);
// Making the cookie live for 2 weeks

session_start(); // start the session

/*+++++++++++++++++++++++++++++++++++++++++++++++ CONNECT TO YOUR DATABASE HERE! +++++++++++++++++++++++++++++++++++++++++*/

connect here

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/





if($_SESSION['id'] && !isset($_COOKIE['Remember']) && !$_SESSION['rememberMe'])
{
	/* If you are logged in, but you don't have the Remember cookie (browser restart)
	   and you have not checked the rememberMe checkbox:                             */

	$_SESSION = array();
	session_destroy();
	
	// Destroy the session
}

/*===========================================================================================================================*/

if(isset($_GET['logoff'])) /* will log the user off and destroy the session */
{
	$_SESSION = array();
	session_destroy();
	
	header("Location: php_login_with_cookie.php"); /* same page as we're on now */
	exit;
}

/*===========================================================================================================================*/

if($_POST['submit']=='Login')
{	// Checking whether the Login form has been submitted
	
	$error = array();
	// Will hold our errors
	
	
	if(!$_POST['username'] || !$_POST['password'])
		$error[] = 'All the fields must be filled in!';
	
	if(!count($error))
	{
		$_POST['username'] = mysql_real_escape_string($_POST['username']);
		$_POST['password'] = mysql_real_escape_string($_POST['password']);
		$_POST['rememberMe'] = (int)$_POST['rememberMe'];		
		// Escaping all input data

		$row = mysql_fetch_assoc(mysql_query("SELECT id,username FROM user_login WHERE username ='{$_POST['username']}'
											  AND password='".md5($_POST['password'])."'"));/* password stored as md5 encryption
											  												   in database                      */

		if($row['username'])
		{
			// If everything is OK login			
			$_SESSION['username']=$row['username'];
			$_SESSION['id'] = $row['id'];
			$_SESSION['rememberMe'] = $_POST['rememberMe'];
			$_SESSION['message']['success'] = 'You are logged in!';/* you could have this say Welcome Back! or whatever you want */			
			// Store some data in the session
			
			setcookie('Remember',$_POST['rememberMe']); /* remembers you wanted to stay logged in, if you checked the
														   Remember Me checkbox in the form                             */
		}		
		else $error[]='Username and/or Password incorrect!';
	}
	
	if(count($error))
	{
		$_SESSION['message']['error'] = implode('<br />',$error);
	}

	header("Location: php_login_with_cookie.php"); /* same page as we're on now */
	exit;
}
/*===========================================================================================================================*/
if (isset($_SESSION['id'])) /* if logged in display the Log off */
{
	  $logout_button = '<div ><a href="?logoff">Log off</a></div>';	
}
else
{
	$logout_button = "";	
}
?>

Below is the html portion....However, it also contains some php for output. Place the php code from above at the very top of your new page and this html below that. This one page accepts the user input and processes it, too.


<!DOCTYPE html >
<head>
<title>Login including cookie set</title>
</head>

<body>
<p>Test by using the following credentials:<br/>
Username: username<br />
Password: password<br /><br />
Try out the "Remember me" by logging on with it checked, and not checked. <br/><br />
Close your browser and bring this page back up to see if you are still logged in.<br /><br /> </p><hr />

                  <?php	
				  
						echo $logout_button;				  
				  		
						if(!$_SESSION['id']):	 /* if not logged in, no $_SESSION['ID'] will exist	  */
						{
							if($_SESSION['message']['error'])// if there WERE errors, this will output them, then destroy the variable
							{
								echo '<div  style="color:red; font-size:1.4em; padding:15px;">'.$_SESSION['message']['error'].'</div>';
								unset($_SESSION['message']['error']);
							}
						}
				   ?>
                  
					<h1>Login</h1> <!-- display this if not logged in -->
                     
                                      
                  <?php			
						else: /* if logged in, echo the session variable for success. */
						{							
								echo  '<div  style="color:green;  font-size:1.4em; padding:15px;">'.$_SESSION['message']['success'].'</div>';															
						}
						
						 endif;			
				  ?>
              
 <!-- Login Form -->
<form  action="" method="post">
               
					<label  for="username">Username:</label>
					<input  type="text" name="username" id="username" value="" size="23" />
					<label  for="password">Password:</label>
					<input  type="password" name="password" id="password" size="23" /><br /><br />
	            	<label><input name="rememberMe" id="rememberMe" type="checkbox" checked="checked" value="1" />  Remember me</label>
        			<br /><br />
					<input type="submit" name="submit" value="Login" />
</form>
            	
</body>
</html>