-2

After advice on here for hashing my passwords correctly I am struggling to get the user to login

here is my Login Function

 public function Login($email, $password)
{
        $db = DB();
        $stat = $db->prepare("SELECT user_id FROM users WHERE email=:email AND password=:password");
        $stat->bindParam("email", $email, PDO::PARAM_STR);
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        $stat->bindParam("password", $hashed_password, PDO::PARAM_STR);
        $stat->execute();
        if ($stat->rowCount() > 0) {
            $result = $stat->fetch(PDO::FETCH_OBJ);
            return $result->user_id;
        } else {
            return false;

} }

And here is my login script on index page

if (!empty($_POST['btnLogin'])) {

$email = ($_POST['email']);
$password = ($_POST['password']);
if ($email == "") {
    $login_error_message = 'Email field is required!';
} else if ($password == "") {
    $login_error_message = 'Password field is required!';
} else {
    $user_id = $app->Login($email, $password); 
    if($user_id > 0)
    {
        $_SESSION['user_id'] = $user_id;
        header("Location: frontpage.php");
    }
    else
    {
        $login_error_message = 'Invalid login details!';
    }
}

}

All I am getting is "Invalid Login Details

Can someone help let me know where I am going wrong please

As always thanks in advance for any pointers you can give

Isitabird
  • 71
  • 9
  • select WHERE user only, do the password comparison/verify with password_verify with the result not in the select, password_hash has salting, resulting hash its always different – Lawrence Cherone Aug 27 '20 at 14:05

1 Answers1

0

password_hash() is only used when storing a new password. You want password_verify().

Don't put the password into the where clause like this:

$stat = $db->prepare("SELECT user_id FROM users WHERE email=:email AND password=:password");

Instead, select the user and hashed password string based only on the unique user id:

$stat = $db->prepare("SELECT user_id,password FROM users WHERE email=:email");

Then pull the already-hashed password out of that record, and use that as the second argument:

if (password_verify($passwordTheyTyped, $passwordFromTheDatabase)) {
    // success
} else {
    // fail
}
Martin
  • 22,212
  • 11
  • 70
  • 132
Alex Howansky
  • 50,515
  • 8
  • 78
  • 98