password_verify doesn't verify hash

caelin picture caelin · Nov 3, 2014 · Viewed 20.8k times · Source

I hash my inserted passwords via password_hash. I verify them by using password_verify.

However when I insert a hashed password in my database and I try to verify it, both outputs always differ from eachother.

my pages are as following,

main_login.php (form):

<?php include 'header.php';?>
<body>
<form role="form" method="post" action="login.php">
  <div class="form-group">
    <label for="usrname">Username:</label>
    <input type="text" class="form-control" name="usrname" placeholder="Enter username">
  </div>
  <div class="form-group">
    <label for="passwrd">Password:</label>
  </div>
    <input type="password" class="form-control" name="passwrd" placeholder="Enter password">
    <br>
  <input type="checkbox">Remember Me
  <br>
  <br>
  <button type="submit" class="btn btn-default">Submit</button>
</form>
</body>
</html>

login.php (handler):

<?php
include 'vars.php';
include 'header.php';
$sql="SELECT * FROM members WHERE usrname='$usrname'";
$result=mysqli_query($con,$sql);
$count=mysqli_num_rows($result);
$row=mysqli_fetch_row($result);
$verify=password_verify($hash,$row[2]);
if($verify){
    $_SESSION["usrname"]=$usrname;
    echo "Correct";
}
else {
    echo "user: " . $usrname. "<br>";
    echo "pass: " . $hash. "<br>";
    echo "db: " . $row[2]."<br>";
    echo "Wrong Username or Password";
}
?>

vars.php:

<?php
$h='localhost';$u='caelin';$p='****';$d='ombouwnh';
$con=mysqli_connect($h,$u,$p,$d);
$usrname=$_POST['usrname'];
$passwrd=$_POST['passwrd'];
$hash=password_hash($passwrd, PASSWORD_DEFAULT);
?>

when i try to login using username 'caca' and password 'caca' I get a different output for both, everytime i retry. I can't find this particular problem on stackoverflow.

TIA

PS. If you need more details, ask for them

Answer

HitMeWithYourBestShot picture HitMeWithYourBestShot · Nov 3, 2014

The function password_verify(); takes two parameters; a non-hashed input, and a stored hash to compare it to. It hashes the non-hashed input automatically to compared it to the stored version. So your initial code was re-hashing an already hashed password. Should look like this:

$verify=password_verify($_POST['passwrd'],$row[2]);

if($verify){
    $_SESSION["usrname"]=$usrname;
    echo "Correct";
}
else {
    echo "user: " . $usrname. "<br>";
    echo "pass: " . $hash. "<br>";
    echo "db: " . $row[2]."<br>";
    echo "Wrong Username or Password";
}