I’ve included a basic CMS in an admin subdirectory following the tutorial and wanted to build a simple login form to control access.
The controller for the CMS works perfectly until the code from Chapter 9 regarding the login form and functions are included. Admin will not load and I’m not even being displayed an error message.
When I modify the code and simply include the login form to check the var being passed with $_POST everything is fine. Correct password using md5 and username as the DB row. It seems to be once I add the login logic I must be doing something incorrect.
I am not sure what error I am currently doing wrong.
Access.php
<?php
function userIsLoggedIn()
{
if (isset($_POST['action']) and $_POST['action'] == 'login')
{
if (!isset($_POST['email']) or $_POST['email'] == '' or
!isset($_POST['password']) or $_POST['password'] == '')
{
$GLOBALS['loginError'] == 'Please fill in both fields';
return FALSE;
}
$password = md5($_POST['password']);
if (databaseContainsUser($_POST['email'], $password))
{
session_start();
$_SESSION['loggedIn'] = TRUE;
$_SESSION['email'] = $_POST['email'];
$_SESSION['password'] = $password;
return TRUE;
}
else
{
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
$GLOBALS['loginError'] =
'The specified email address or password was incorrect';
return FALSE;
}
}
if (isset($_POST['action']) and $_POST['action'] == 'logout')
{
session_start();
unset($_SESSION['loggedIn']);
unset($_SESSION['email']);
unset($_SESSION['password']);
header('Location: ' . $_POST['goto'])
exit();
}
session_start();
if (isset($_SESSION['loggedIn']))
{
return databaseContainsUser($_SESSION['email'],
$_SESSION['password']);
}
}
function databaseContainsUser($email, $password)
{
include $_SERVER['DOCUMENT_ROOT'] . '/include/db.php';
try
{
$sql = 'SELECT COUNT(*) FROM users
WHERE email = :email AND password = :password';
$s = $pdo->prepare($sql);
$s->bindValue(':email', $email);
$s->bindValue(':password', $password);
$s->execute();
}
catch(PDOException $e)
{
$error = 'Error searching for user';
include $_SERVER['DOCUMENT_ROOT'] . '/include/error.html.php';
exit();
}
$row = $s->fetch();
if($row[0] > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
Admin Controller
<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/include/access.php';
if (!userIsLoggedIn())
{
include $_SERVER['DOCUMENT_ROOT'] . '/include/login.html.php';
exit();
}