Topic 11 Homework Marking Guide
Topic 11 Homework Marking Guide
Consider a login application that checks a user's name and password, which are provided upon
login, with variable names 'user' and 'password'. If the username and password are recognized
in the database, the application starts a session and sets a session variable called 'user' for the
login name of the user accessing the system, then redirects the user to file called 'home.php'.
Otherwise, it redirects the user back to the login page, 'login.htm'.
Assumptions:
The allowable usernames, passwords exist in a mysql database called “login” with table
called “users”.
The users table has four fields, namely, username, password, fname and lname.
Task:
a) Develop the login interface using HTML5. Ensure that a check for an existing session is
made. If it is found to be existing, then redirect the user to home.php. [6 Marks]
<?php
//open login page if session is not set otherwise redirect to the homepage
session_start();
if (isset($_SESSION['user'])){
header('location: home.php');
}else{
?>
<!doctype html>
<html>
<head>
<title>Login Form</title>
</head>
<body>
</body>
</html>
<?php
}
?>
b) Develop the appropriate PHP scripts and the database that will implement the login process
described in the case. Be sure to include some message in the home.php showing the full
name (FName & LName) of the user that has successfully logged in. [10 Marks]
The code for the script that processes the form data and the login process should be as follows:
<?php
//establish connection to the database server
$connect = mysqli_connect("localhost","root","");
if(!$connect){
echo "Connection to the database engine failed";
}
//receive login data from the login form then store in variables
$user=$_POST['username'];
$pass=md5($_POST['password']);
//start a session then redirect to the homepage otherwise redirect back to the login page for invalid
credentials
$count = mysqli_num_rows($results);
if($count ==1){
session_start();
$_SESSION['user']=$name;
header('location: home.php');
}else{
header('location: login.php');
}
<?php
//check if session is set then read the session variables otherwise redirect back to login page
session_start();
if (!isset($_SESSION['user'])){
header('location: login.php');
}else{
echo "You are logged in as " . $_SESSION['user']
. " with session id " . session_id() . "<br />";
}
echo "<a href=logout.php>Logout</a>";
?>
c) Incorporate a logout mechanism that destroys sessions and redirects users to the login
page. Let the link to the logout script be provided in the home.php page. [4 Marks]
<?php
//gather all session variables in an array
session_start();
$_SESSION = array();