I'm creating a very basic user login interface for a website I'm working on for a "members" portion of the website. I am using for $_SESSION variables to store information. ['access'] stores a boolean value as to whether or not the user is permitted access, ['invalid'] is true if the username/password don't match (for error handling), ['no_attempt'] is true if the user tries to access a restricted page without being logged in, and ['uri'] stores the URI of the page they tried to access without being logged in.
With how I have coded my pages so far, everything works, except the error message is never displayed when ['no_attempt'] is true. The following are excerpts from my pages:
login.php
session_start();
if(md5($_POST['username']) === '[username hash]' && md5($_POST['password']) === '[password hash]') {
// allow access to members pages
$_SESSION['login']['allow'] = true;
// clear error messages
$_SESSION['login']['invalid'] = false;
$_SESSION['login']['no_attempt'] = false;
// if a url hasn't been stored for redirect, direct to the members home page
if (!isset($_SESSION['login']['redirect']) || empty($_SESSION['login']['redirect'])) $_SESSION['login']['redirect'] = '/members';
header("Location: {$_SESSION['login']['redirect']}");
}
else {
$_SESSION['login']['invalid'] = true;
header('Location: /');
}
The beginning of each restricted page begins with this code:
session_start();
if($_SESSION['login']['allow'] != true) {
$_SESSION['login']['redirect'] = $_SERVER['REQUEST_URI'];
$_SESSION['login']['no_attempt'] = true;
header('Location: /');
}
require ('../assets/includes/site-header.php');
site-header.php
This page is called at the beginning of each page of my website. It has the title, nav bar, and stuff like that. Below is only the Member login part of the sidebar.
if(isset($_SESSION['login']['allow']) && $_SESSION['login']['allow'] == true) {
echo "<li><a href=\"/members\" id=\"members\">Members</a></li>\n";
}
else {
echo "<li>\n";
echo "<div class=\"expandable\">Members <span class=\"show-hide\">+</span></div>\n";
echo "<div class=\"nav-details\">\n";
if (isset($_SESSION['login']['invalid']) && $_SESSION['login']['invalid'] == true) {
echo "<div id=\"login-error\">The username or password you<br />entered was incorrect.</div>\n";
}
elseif (isset($_SESSION['login']['no_attempt']) && $_SESSION['login']['no_attempt'] == true) {
echo "<div id=\"login-error\">You must login before<br />accessing that page.</div>\n";
}
echo "<form method=\"post\" action=\"/members/login.php\" id=\"login-form\">\n";
echo "Username:<br />\n";
echo "<input type=\"text\" name=\"username\" /><br /><br />\n";
echo "Password:<br />\n";
echo "<input type=\"password\" name=\"password\" /><br /><br />\n";
echo "<input type=\"submit\" value=\"Login\" id=\"login-button\" />\n";
echo "</form>\n";
echo "</div>\n";
echo "</li>\n";
}
$_SESSION['login']['invalid'] = false;
$_SESSION['login']['no_attempt'] = false;