1

Basically, I've just started working with PHP, and am trying to get to grips with the password_hash function. When a user registers I hash their password using:

$hashed_password = password_hash($p, PASSWORD_DEFAULT); 

Then, that hashed password is stored in my database. I then want to retrieve the password for login. So my code is written so that once the form is submitted, the email and password strings are sanitized, it the checks that they're not blank, once that's done, I take the user entered password, and hash it using:

$hash = password_hash($password, PASSWORD_DEFAULT);

Once again. Once this has done I connect to my DB, and try to select the user using:

 $q = "SELECT * FROM users
                    WHERE email='$email' AND password='$hash'";

However. When debugging I've noticed that the user entered string, despite being the same as the string entered when signing up is different when hashed. so I've been echo'ing $hash and getting:

$2y$10$LQ55Q1DUqIgRx/2hgnbrnuQrYvrrBrq4WEFmV8TuxII6rDocaWzt2 

but the exact same string "password" is stored in the db as:

$2y$10$omNPA7cviUm.6asuhJIJ8Or.m9WeHhJMkCqYYijel5g.NflbdVnV.

How do I get it so that when the user enters their password, it hashes the string and matches the one in the DB, so that they can log in? Am I missing something

Cheers

4
  • password_hash is for creating an always-different password hash, while password_verify is for checking. Use just the username for the SQL query. Commented Jan 31, 2015 at 13:44
  • No, you don't hash the entered password to compare against the saved password, because it will be salted with a different salt; you retrieve the user record just using email, and then use password_verify() Commented Jan 31, 2015 at 13:45
  • So I've taken the password out of the query, and am trying to use: while ($row = $r->fetch_array()) { if (password_verify($password, $hash)) { echo"Password verified"; } else { echo"invalid"; } } To verify the password once that query gives a result, but am still getting "invalid". Presume I'm doing this wrong? Commented Jan 31, 2015 at 14:01
  • You need to use password_verify() to test the password entered by the user (exactly as they entered it) against the password retrieved from the database (from $row) Commented Jan 31, 2015 at 14:24

1 Answer 1

2

You'd need something like this:

$hashed_password = mysql_result(mysql_query("SELECT password FROM users WHERE email='$email'"));

$match = password_verify( $password, $hashed_password );
if($match){ 
  echo 'Password is valid';
} else {
  echo 'Password is not valid' ;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.