It is important to authenticate users especially as it relates to ensuring only authorized users have access to administrative pages (e.g., add, update, or delete) as well as having only registered users view specific pages. This is done by creating pages that allow users to log in through an authentication framework in order to access pages that requires authentication. Other pages are accessible to the public or what is often termed "public facing."
Good demo and tutorial on Login with Session using PDO: http://www.webslesson.info/2016/06/php-login-script-using-pdo-with-session.html
CAUTION: It is best NOT to provide a link to administrative pages to prevent hackers from attempting to hack your site.
Instead, provide a link that the administrative users have to enter manually. This also prevent search engines from
indexing that link. However, you should provide links (login and logout) to other users (members, client login, guests, etc.
The Login page allows a user to enter a username and password that will be checked against a username and password in the database. If there is a match, the user is relocated to the appropriate page. If there is not a match, the user is presented with a message on the same page that states that the username or password was missing or invalid.
The submit button in a form has to be clicked FIRST in order for a form to be processed. So to determine if a form has been submitted, you can check to see if a variable is set in the form. Fortunately, PHP has a method for checking to see if ANY variable is set called isset(). Guess what it does?
if (isset($_POST["aVariable"])
A session variable will be created to pass data from one page to another page AND to restrict access to another page depending if the login is successful or not. If not successful, the user will be redirected to another page. Later, the user be allowed to log out to close the session variable.
The code that will be created will perform the following tasks:
<div data-role="header">
<h1>Employee Directory</h1>
<a href="master_page.php" class="ui-btn ui-icon-home ui-corner-all ui-btn-icon-left">Home</a>
</div>
<div data-role="content">
<h2 class="ui-body ui-body-a ui-corner-all">EMPLOYEE LOGIN</h2><form action="" method="post" data-ajax="false">
<div class="ui-body ui-body-a ui-corner-all">
<label for="username">User Name:</label>
<input type="text" name="username" size="20" placeholder="(e.g., user@example.com)" data-mini="true"/>
<label for="password">Password:</label>
<input type="password" name="password" size="20" data-mini="true"/>
<input type="submit" name="login" value="LOG IN" data-inline="true" data-mini="true"/>
</div>
</form></div>
CODE EXPLANATION:
- It is important to note that the data-ajax="false" attribute is needed in order for the login script to work. AJAX has to be turned off.
Now, it is time to add the some scripts to make the login panel work.
IMPORTANT NOTE: If you are pushed for time, you can just add the required statement at the top of the document and use the PHP login script from the resource folder.
<?php session_start();
require ('db.php');
require ('loginScript.php');
?>
<!doctype html>
<html lang="en">
CODE EXPLANATION:
- The session_start() method is used to start a session variable and it must be the first statement written. - You may see a PHP script written several different ways. There are three basic ways to include PHP script on a page:
1. Use an include directive (e.g., require() or require_only() , include()) to link the PHP script to the page.
2. Write the PHP script DIRECTLY on the page (e.g., <?PHP Script goes here.. ?>).
3. Link to the PHP script via the form's action attribute (e.g., <form action = "myPHPScript.php" method = "POST">).
- All of the above three approaches invoke the PHP Script via a submit button (<input type = "submit"....>).
<div data-role="content">
<h2 class="ui-body ui-body-a ui-corner-all">EMPLOYEE LOGIN</h2>
<?php
if(isset($message))
{
echo $message;
}
?>
<form action="" method="post">
CODE EXPLANATION:
- The isset() method is used to CHECK if the message "is set" and if so display a custom message based on the
$message variable if it exists.
Now, let's create the loginScript.php file that is needed.
TIME SAVER: If you are pushed for time, you can skip the following steps. Simply use the finish loginScript.php file
in the project's resource folder.
<?php
if(isset($_POST["login"]))
{ }
// End of login script
?>
CODE EXPLANATION:
- There will be three "if" statements included in the try code block. This FIRST "if" statement is used to CHECK
to see if the LOG IN button was clicked. If so, execute the code between that curly braces that will be created
in the next step. - The isset() method is used to check if a variable has a value or not have a value so it will return either true or false.
- The $_POST["login"] global variable is based on the submit's button name attribute of the same name:
(e.g., <input type="submit" name="login" value="LOG IN" data-inline="true" data-mini="true"/>).
if(isset($_POST["login"]))
{ if(empty($_POST["username"]) || empty($_POST["password"]))
{
$message = '<p class= "error">Both User Name and Password are required.</p>';
} }
CODE EXPLANATION:
- If the first "if" statement is true (meaning that the LOG IN button was clicked) than execute this SECOND nested "if"
statement which CHECKS to see if either one or both of the login fields (e.g., username and password) were left
EMPTY. If so, display the message "Both username and password are required."
if(isset($_POST["login"]))
{ if(empty($_POST["UserName"]) || empty($_POST["Password"]))
{
$message = '<p class= "error">Both User Name and Password are required</p>';
} else
{
$query = "SELECT * FROM passwords WHERE Email = :UserName AND Password = :Password";
$statement = $connect->prepare($query);
$statement->execute( array( 'UserName' => $_POST["username"], 'Password' => $_POST["password"] ) );
} }
}
CODE EXPLANATION:
- If both the username and password are entered even though they may be invalid, the "else" portion of the SECOND "if"
statement is executed instead which runs the SQL query to retrieve both the username and password from the database.
- The :UserName and :Password are placeholders for the SQL query to avoid SQL Injection. They are replaced with their actual values from an array
(e.g., array( 'UserName' => $_POST["username"], 'Password' => $_POST["password"] )).
- The $statement variable is used to hold a reference to the SQL prepared statement that has the query as an argument (e.g., prepare($query)) that was just created.
- The prepared statement is then executed with values from the array used to populate the SQL placeholders (:username and :password) with their actual values from
the User Name and Password input fields.
<?php // IMPORTANT NOTE: The UserName is mapped to the Email column in the database instead of the UserName column.
if ( isset( $_POST[ "login" ] ) )
{
if ( empty( $_POST[ "username" ] ) || empty( $_POST[ "password" ] ) )
{
$message = '<p class= "error">Both User Name and Password are required</p>';
}
else
{
$query = "SELECT * FROM passwords WHERE Email = :UserName AND Password = :Password";
$statement = $pdo_conn->prepare( $query );
$statement->execute( array( 'UserName' => $_POST[ "username" ], 'Password' => $_POST[ "password" ] ) );
$count = $statement->rowCount();
if ( $count > 0 )
{
$_SESSION["username"] = $_POST['username'];
header( "location:master_page.php" );
}
else
{
$message = '<p class="error">Invalid User Name or Password</p>';
}
}
}
?>
CODE EXPLANATION:
- If the query is executed, a count variable is assigned to the $statement->rowCount(); statement to ascertain its value.
- In this THIRD nested "if/else" statement, CHECK to see if the count is greater than zero (which means that a result was returned from the database
because the username and password were correct.), create a SESSION variable and then redirect to another page. If the count is not greater than zero
(because of an invalid username or password), display the message, "Invalid User Name or Password."
- The rowCount() method will return the number of rows affected by this query.
To prevent a page from being accessed, you have to write code on the page to redirect a user the login page if he or she does not have credential (e.g., login) for that page.
<body>
<div data-role="page" id="home_page" data-ajax="false">
<?php
session_start();
require ("db.php");
<h2 class="ui-body ui-body-a ui-corner-all">EMPLOYEE MASTER PAGE</h2>
<?php
if(isset($_SESSION["username"]))
{
echo '<p><span class="error">Welcome: </span>'.$_SESSION["username"].'</p>';
}
else
{
header("location:index.php");
}
?>