As the title suggests, I am having trouble logging users in, after hashing their passwords in the signup form. I have used PHP's built in password_hash() and password_verify() functions, but its on signin.php, where password_verify() is used that I am having trouble. I know that a parameter to password_verify() is a hash, but how do I use the same hash generated and stored in signup.php, to be able to use in this function?
NOTE: Yes there is more to both of these sets of code! Database connection works, all variables not defined in these bits ARE defined some lines up. signup.php works perfectly and the form data, including the hashed password are successfully stored in my database.
here is the part of signup.php where the hash is implemented:
$hash = password_hash($password, PASSWORD_DEFAULT);
$sql = "INSERT INTO users (id, full_name, email, password, username, sign_up_date, activated) VALUES ('', '$full_name', '$email', '$hash', '$username', '$date', '1')";
and here is the part of signin.php where the (presumably same) hash is needed: $password = mysqli_real_escape_string($_POST['password']);
if (!password_verify($password, $hash)) {
echo 'Invalid password.';
exit;
}
$sql = "SELECT id, email, password FROM users WHERE email = '$email' AND password = '$password' AND activated = '1' LIMIT 1";
$query = mysqli_query($conn, $sql);
EDIT: I figured this out myself a day later, had to retrieve the stored hash from database using "SELECT * FROM...", and then compare that with the entered password with password_verify(). Thanks for the help nonetheless!
I am note sure where exactly the problem is. You stated that you already store the hashed password (with password_hash()
) in your database. So the basic workflow would be:
a) Save the hash of the password given at the registration in your database (not the cleartext password):
$hash = password_hash($_POST['password'], PASSWORD_DEFAULT);
$sql = "INSERT INTO users (id, full_name, email, password, username, sign_up_date, activated) VALUES ('', '$full_name', '$email', '$hash', '$username', '$date', '1')";
b) If a user tries to login you simply get the hash from the database WHERE email = '{$_POST['email']}
and then use the password_verify
function:
if (!password_verify($_POST['login_password'], $hash_from_database)) { exit; }
Does this help?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With