I’m trying to verify my user’s hashed password from my MySQL Database using the password_hash()
and password_verify()
functions. I am trying to do this with prepared PHP statements for added security but with having no luck. Anyone know why?
Here’s the code:
//check if password is linked to username $checkpass = $conn->prepare("SELECT user_password FROM user_details WHERE user_password=?"); $checkpass->bind_param("s", $preppass); $preppass = $password; $getpass = $checkpass->execute(); //get and check result $checkpass->bind_result($getpass); $checkpass->fetch(); if (!password_verify($password, $getpass)) { echo "<script>console.log('Incorrect username or password!')</script>"; return false; exit; } echo "S<script>console.log('Successfully logged in!')</script>"; $conn->close();
and here is the database:
What I’ve tried:
Unable to extract password hash from database with prepared statements
Verify hashed password from database
I would really appreciate some help with this.
Many thanks!
Advertisement
Answer
You have to look up the hashed password using the username, not the password, because you don’t know what the hashed password is. Then you use password_verify()
to check that the entered password matches the hashed password.
$checkpass = $conn->prepare("SELECT user_password FROM user_details WHERE username=?"); $checkpass->bind_param("s", $username); $checkpass->execute(); //get and check result $checkpass->bind_result($getpass); $checkpass->fetch(); if (!password_verify($password, $getpass)) { echo "<script>console.log('Incorrect username or password!')</script>"; return false; exit; } echo "S<script>console.log('Successfully logged in!')</script>"; $conn->close();