Reputation: 1934
I want to compare my password and my hash password with password_verify()
but always returns true
.Why is that happening?
Here is the code:
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$myusername = mysqli_real_escape_string($db,$_POST['username']);
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$hash = password_hash($mypassword, PASSWORD_DEFAULT);
$ourdb = "SELECT handle FROM qa_users WHERE handle = '$myusername' and passhash = '$mypassword'";
$ourresult = mysqli_query($db,$ourdb);
$ourrow = mysqli_fetch_array($ourresult,MYSQLI_ASSOC);
$ouractive = $ourrow['active'];
$ourcount = mysqli_num_rows($ourresult);
if(password_verify($mypassword, $hash)){
echo "hashed";
}
Upvotes: 0
Views: 279
Reputation: 26450
What you're currently doing is hash the password (which you escaped first; you should never escape passwords as that changes the hash), then match/verify it against the value you just hashed, without using the hash from the database - so it will always match. It's the equivalent of setting a variable $a = 'foo';
, then checking if ($a == 'foo')
- the check will always return true.
Instead, fetch the hashed value from the database based on the username, and use that as the second argument to password_hash()
.
Also,
password_verify()
query()
method and using real_escape_string()
) - see How can I prevent SQL injection in PHP?if($_SERVER["REQUEST_METHOD"] == "POST") {
$stmt = $db->prepare("SELECT passhash FROM qa_users WHERE handle = ?");
$stmt->bind_param("s", $_POST['username']);
$stmt->execute();
$stmt->bind_result($hash);
$stmt->fetch();
if (password_verify($_POST['password'], $hash)) {
echo "Valid login";
} else {
echo "Invalid login";
}
$stmt->close();
}
Upvotes: 8