0

I created registration form with hashed password and now I am not really sure how to fetch the hashed password and be able to login.

Registration.php

    $hash = password_hash($password, PASSWORD_BCRYPT);
    $insert = $con->query("INSERT INTO Client (firstName, lastName, email, password, keyVerification) VALUES 
    ('$firstName', '$lastName', '$email', '$hash', '$keyVerification')");

Login.php

 $email = $con->real_escape_string($_POST['email']);
    $password = $con->real_escape_string($_POST['password']);
    $hash = password_hash($password, PASSWORD_BCRYPT);

    $result = $con->query("SELECT * FROM Client WHERE email = '$email' AND password = '$hash' LIMIT 1");

Unfortunately this way doesn't work when I want to login with registered email and password - I am just getting error I set up of incorrect password or email. I believe I am making the mistake with hashed password. Where my logic failed ?

  • 1
    You should use [`password_verify()`](https://www.php.net/password_verify) to check if the passwords match. – Syscall Nov 24 '20 at 11:53
  • Please read also https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php to – Syscall Nov 24 '20 at 11:55
  • 1
    **Pro tip** for php programmers. The documentation at php.net shows a right column with a list of information related to the page you're viewing. So, if you're viewing [password_hash()](https://www.php.net/manual/en/function.password-hash.php) you can see a link to password_verify() at the right. It's important to look around the docs when you use a function, and the list at the right makes it easy. – O. Jones Nov 24 '20 at 11:58

2 Answers2

1

You get a new seed whenever you call password_hash so you can't compare the output of it with the previous output, even when the input is the same.

Search the database to find the hashed password for the email address given.

Then compare the submitted password to the known hash using password_verify.

if (password_verify($_POST['password'], $hash_from_database)) {

Asides:

$password = $con->real_escape_string($_POST['password']);
$hash = password_hash($password, PASSWORD_BCRYPT);

Don't escape the password to make it suitable for inserting into SQL and then hash the escaped password.

Escape what you want to put into the database, which is the hashed password.

… but don't use real_escape_string in the first place. Use placeholders.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

You should try with the password_verify ( string $password , string $hash ) : bool function, as the hash function will generate new hashes for the same password string each time.

Read more here: https://www.php.net/manual/en/function.password-verify.php

Juzles
  • 19
  • 6