I've been trying to add a user login system to my site and have the following login page that seems to work fine (in so far as it checks username and password, passes the user through):
index.php
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login Form</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="login.php">
<table width="510" border="0" align="center">
<tr>
<td colspan="2">Login Form</td>
</tr>
<tr>
<td>Email Address:</td>
<td><input type="text" name="email" id="email" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" id="password" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="button" id="button" value="Submit" /></td>
</tr>
<tr>
<td colspa"2"><?php if(isset($_GET['f'])){echo("<h2>Login Failed</h2>");} ?></td>
</tr>
</table>
</form>
</body>
</html>
login.php
<?php
session_start();
$email = $_POST['email'];
$password = $_POST['password'];
include 'includes/db_connect.php';
$conn = new PDO($dsn, $user, $pass);
$query = "SELECT password, salt FROM member WHERE email = :email";
$result = $conn->prepare($query);
$result->bindParam(":email", $email);
$result->execute();
$number_of_rows = $result->rowCount();
if($number_of_rows == 0) // User not found. So, redirect to login_form again.
{
header('Location: index.php?f=1');
}
$userData = $result->fetch(PDO::FETCH_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );
if($hash != $userData['password']) // Incorrect password. So, redirect to login_form again.
{
header('Location: index.php?f=1');
}else{ // Redirect to home page after successful login.
session_regenerate_id();
$_SESSION['email'] = $email;
header('Location: results.php');
}
?>
results.php
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Results</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="assets/css/style.css" />
<?php
//are you logged in?
session_start();
if(isset($_SESSION['email'])){
$email = $_SESSION['email'];
}
if(empty($email)){
echo "You're not an authorized user. Please <a href='./index.php'>login</a>.<br />";
exit();
}
//rest of website
However, I always get the "You're not an authorized user..." error, I've tried putting a var_dump()
and var_export()
for $_SESSION
but get NULL and print_r
produces nothing, as does echo $_SESSION['email']
which would suggest my $_SESSION
global is empty, I have session_start();
at the start of both login.php and results.php so the session should be there and continue.
I have things like WordPress installed on the same server so pretty sure things like $_SESSION
works on the host and PHP is 7.2 so should be up to snuff too.
What dumb mistake am I overlooking?