Authentication with Session Control - Exercise

Contact Us or call 1-877-932-8228
Authentication with Session Control - Exercise

Authentication with Session Control

Duration: 30 to 40 minutes.

In this exercise, you will create a login form that allows a user to log in to a site, rather than just a page on the site. You will also modify several other pages so that their content changes based on whether or not the user is logged in.

  1. Open Sessions/Exercises/index.php in your editor. This file has been completed for you. Note the following:
    • At the top of the document, we start a session with session_start().
    • We've added an outer if condition to the body to check if EmployeeID already exists in the $_SESSION array. If it does, this means the user has already logged in.
      if (array_key_exists('EmployeeID',$_SESSION))
      {
      	echo '<div align="center">
      			Logged in as ' .
      			$_SESSION['FirstName'] . ' ' . 
      			$_SESSION['LastName'] .
      			'</div>';
      }
      else
      {
      	if (array_key_exists('LoggingIn',$_POST))
      	{
      		require 'Includes/Login.php';
      	}
      	if (!array_key_exists('LoggingIn',$_POST))
      	{
      		require 'Includes/LoginForm.php';
      	}
      	if (strlen($msg) > 0)
      	{
      		echo "<div align='center'>$msg</div>";
      	}
      }
  2. Open Sessions/Exercises/Includes/Login.php in your editor. Modify the code, so that when the user logs in, she is remembered for the duration of her visit. You should remember her first name, last name and employee id.
  3. Sessions/Exercises/Includes/Footer.php has been changed to include a "Log out" link, which points to Sessions/Exercises/Logout.php. Open Sessions/Exercises/Logout.php in your editor. Add code to log the user out (i.e, delete all session variables and kill the session).
  4. Open Sessions/Exercises/OtherPage.php in your editor. Notice that it includes Includes/LoginCheck.php.
  5. Open Sessions/Exercises/Includes/LoginCheck.php in your editor. You will see that it currently contains code to redirect the page to index.php. Modify this script so that it only redirects to index.php if the user is not logged in.

Challenge

Write code so that the user can indicate that she would like to be remembered between visits. If she chooses to be remembered, she should not have to log in again for a week. You will need to modify index.php, Includes/LoginForm.php, Includes/Login.php and Includes/Logout.php. You may also find it useful to create a new include file (e.g, CookieCheck.php) to hold the code that checks for the cookie.

Solution:

Sessions/Solutions/Includes/Login.php
<?php
	$dbEntries = $_POST;
	foreach ($dbEntries as &$entry)
	{
		$entry = dbString($entry);
	}
	
	@$db = new mysqli('localhost','root','pwdpwd','Northwind');
	if (mysqli_connect_errno())
	{
		echo 'Cannot connect to database: ' . mysqli_connect_error();
	}
	else
	{
		$query = "SELECT EmployeeID, FirstName, LastName 
					FROM Employees
					WHERE Email = '" . $dbEntries['Email'] . 
					"' AND Password = '" . $dbEntries['Password'] . "'";
		$result = $db->query($query);
		
		if ($result->num_rows)
		{
			$row = $result->fetch_assoc();
			$msg = 'Logged in as ' .
				$row['FirstName'] . ' ' . $row['LastName'];
			$_SESSION['FirstName'] = $row['FirstName'];
			$_SESSION['LastName'] = $row['LastName'];
			$_SESSION['EmployeeID'] = $row['EmployeeID'];
		}
		else
		{
			$msg = 'Login Failed';
			unset($_POST['LoggingIn']);
			$dbEntries = $_POST;
		}
	}
?>

Solution:

Sessions/Solutions/Logout.php
<?php
	session_start();
	session_unset();
	session_destroy();
	
	header('Location: index.php');
?>

Solution:

Sessions/Solutions/Includes/LoginCheck.php
<?php
	session_start();
	if (!array_key_exists('EmployeeID',$_SESSION))
	{
		header('Location: index.php');
	}
?>

Challenge Solution:

Sessions/Solutions/index-challenge.php
<?php
	session_start();
	require 'Includes/CookieCheck.php';
	require 'Includes/fnFormPresentation.php';
	require 'Includes/fnStrings.php';
	$errors = array();
	$dbEntries = array(	'Email'=>',
						'Password'=>');
?>
---- C O D E   O M I T T E D ----

Challenge Solution:

Sessions/Solutions/Includes/LoginForm-challenge.php
<h1 align="center">Log in</h1>
<form method="post" action="index-challenge.php">
<input type="hidden" name="LoggingIn" value="true">
<table align="center">
	<?php
		echo textEntry('Email','Email',$dbEntries,$errors,25);
		echo pwEntry('Password','Password',$errors,10,false);
	?>
	<tr>
		<td colspan="2">
			<input type="checkbox" name="Remember"> Remember me
		</td>
	</tr>
	<tr>
		<td colspan="2" align="right">
			<input type="submit" value="Login">
		</td>
	</tr>
</table>
</form>

Challenge Solution:

Sessions/Solutions/Includes/Login-challenge.php
---- C O D E   O M I T T E D ----
		if ($result->num_rows)
		{
			$row = $result->fetch_assoc();
			$msg = 'Logged in as ' .
				$row['FirstName'] . ' ' . $row['LastName'];
			$_SESSION['FirstName'] = $row['FirstName'];
			$_SESSION['LastName'] = $row['LastName'];
			$_SESSION['EmployeeID'] = $row['EmployeeID'];
			if ( isset($_POST['Remember']) )
			{
				setcookie('eid', 
							$row['EmployeeID'],
							time()+60*60*24*7);
			}
		}
---- C O D E   O M I T T E D ----

?>

Challenge Solution:

Sessions/Solutions/Logout-challenge.php
<?php
	session_start();
	session_unset();
	session_destroy();
	setcookie('eid',',time()-1);
	
	header('Location: index-challenge.php');
?>

Challenge Solution:

Sessions/Solutions/Includes/CookieCheck.php
<?php
	if ( isset($_COOKIE['eid']) )
	{
		@$db = new mysqli('localhost','root','pwdpwd','Northwind');
		if (mysqli_connect_errno())
		{
		        echo 'Cannot connect to database: ' . mysqli_connect_error();
		}
               else
		{
			$query='SELECT FirstName,LastName,EmployeeID
					FROM Employees
					WHERE EmployeeID=' . $_COOKIE['eid'];
			
			$result = $db->query($query);
			if ( $row=$result->fetch_assoc() )
			{
				$_SESSION['FirstName']=$row['FirstName'];
				$_SESSION['LastName']=$row['LastName'];
				$_SESSION['EmployeeID']=$row['EmployeeID'];
			}
		}
	}
?>
Next