I have an echo after each header redirect. But it does not pop up. So when the user enters an invalid login detail no message pops up. What am I doing wrong? I tried a JavaScript method as well but did not manage to fix the issue. Is it something to do with my nested ifs maybe?
<?php
session_start();
#first if
if (isset($_POST['submit'])) {
include 'dbh.inc.php';
$uid = mysqli_real_escape_string( $conn , $_POST['uid'] );
$pwd = mysqli_real_escape_string( $conn , $_POST['pwd'] );
//Error handlers
//Check if this input are empty
#second if
if (empty($uid) || empty($pwd)) {
header("Location: ../index.php?login=empty");
exit();
}/*second else*/ else {
$sql = "SELECT * FROM users WHERE user_uid='$uid' OR user_email='$uid'";
$result = mysqli_query($conn,$sql);
$resultCheck = mysqli_num_rows($result);
#third if
if ($resultCheck < 1) {
header("Location: ../index.php?login=error");
echo "Login error";
exit();
}/*third else*/ else {
#forth if
if ($row = mysqli_fetch_assoc($result)) {
//de-hashing the password
$hashedPwdCheck = password_verify($pwd , $row['user_pwd']);
#fifth if
if ($hashedPwdCheck == false) {
header("Location: ../index.php?login=error");
echo "Login error";
exit();
} /*fifth else*/ elseif ($hashedPwdCheck == true) {
//Log in the user here
$_SESSION['u_id'] = $row['user_id'];
$_SESSION['u_first'] = $row['user_first'];
$_SESSION['u_last'] = $row['user_last'];
$_SESSION['u_email'] = $row['user_email'];
$_SESSION['u_uid'] = $row['user_uid'];
$uid = $_SESSION['u_id'];
header("Location: ../index.php?login=success");
echo "Login error";
exit();
}
}
}
}
}/*first else*/ else {
header("Location: ../index.php?login=error");
echo "Login error";
exit();
}
?>
If you use location
headers you can never display messages - the browser ignores the rest of the request and does the redirect immediately, because the HTTP code is changed to 302.
Even if you could show a message, it would not be a good experience for the user, as it would only display for a fraction of a second and then the redirect would happen and the page would be overwritten. You should show the error message on the landing page (index.php?login=error).