I am trying to make a login page using PDO prepared statement. My sample code for login.php is as follows:
<?php
session_start();
if(isset($_SESSION['user']))
{
header("location:admin.php");
exit;
}
include('../php/config.php');
$uname = hash('sha512', $_POST['lgnID']);
$pass = hash('sha512', $_POST['password']);
$stmt = $db->prepare("SELECT * FROM admin WHERE uname= ?");
$stmt->execute([$uname]);
// this will fetch first record from query or false if record does not exist
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result) {
if ($pass == $result['password']) {
$_SESSION['user'] = $uname;
$_SESSION['pass'] = $pass;
$_SESSION['loggedin']= 1;
header("location:admin.php");
exit;
} else {
echo "Login ID and Password did not Match";
}
} else {
echo "Admin login ID doesn't exist";
}
?>
But the problem is after I put valid credentials while login, I am not redirected to admin.php page which I am supposed to do. Is there anything wrong in the code?
Your first line of code in the first post seems to have a space before the opening PHP tag - have you removed that as per the post by @rpkamp ? It might not be obvious that itâs been removed, but if the browser has received that space, you wonât be able to do a header redirect, youâll get a âheaders already sentâ error.
Slightly separately, hashing passwords in that way doesnât seem to be the preferred way now - you should read up on password_hash() and password_verify() functions.
In this code
while($r=$sql->fetch()){
$p=$r['password'];
}
will you be allowing more than one row with the same username? If not, thereâs no need for a while() loop, just call fetch() once.
OK, can we see the code as it is now? And are you sure that youâre using the correct values for the comparison? Do you really store the username in hashed form as well as the password, just noticed @rpkamp asked above?
The point above is a good one - which of the header redirects are you expecting it to be doing that it is not? If itâs the first one, then you do need that exit; line as @ahundiak mentioned above, so it doesnât execute the rest of the code.
How far through your code does it get? Add some echo statements so you can track where itâs going and (more to the point) where it stops. Can you show the HTML for the form too?
I have changed my code a bit. Now I have confirmed that The password is being matched but after that header part is not working. Please check my edited post.