Jamie O'Hanlon Jamie O'Hanlon - 7 months ago 79
PHP Question

PHP password_verify not matching hash

So I have two functions for registering and logging in. Registering works fine, the user table is populated, the hash is stored in the user_pass column etc. When logging in, I keep getting the "Wrong Details" error message. It seems the password_verify isn't matching the hash with the inputted password. Can you guys see anything wrong with my code? I'm scratching my head here....

public function register($uname,$umail,$upass)
{
try
{
$new_password = password_hash($upass, PASSWORD_DEFAULT);

$stmt = $this->conn->prepare("INSERT INTO users(user_name,user_email,user_pass)
VALUES(:uname, :umail, :upass)");

$stmt->bindparam(":uname", $uname);
$stmt->bindparam(":umail", $umail);
$stmt->bindparam(":upass", $new_password);

$stmt->execute();

return $stmt;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}


public function doLogin($uname,$umail,$upass)
{
try
{
$stmt = $this->conn->prepare("SELECT user_id, user_name, user_email, user_pass FROM users WHERE user_name=:uname OR user_email=:umail ");
$stmt->execute(array(':uname'=>$uname, ':umail'=>$umail));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1)
{
if(password_verify($upass, $userRow['user_pass']))
{
$_SESSION['user_session'] = $userRow['user_id'];
return true;
}
else
{
return false;
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}

Answer

rowCount() does not return the number of rows in a SELECT statement. There is no need to test to see if the query succeeded, you can move right to testing the password:

public function doLogin($uname,$umail,$upass)
{
    try
    {
        $stmt = $this->conn->prepare("SELECT user_id, user_name, user_email, user_pass FROM users WHERE user_name=:uname OR user_email=:umail ");
        $stmt->execute(array(':uname'=>$uname, ':umail'=>$umail));
        $userRow=$stmt->fetch(PDO::FETCH_ASSOC);

        if(password_verify($upass, $userRow['user_pass']))
        {
            $_SESSION['user_session'] = $userRow['user_id'];
            return true;
        }
        else
        {
            return false;
        }

    }
    catch(PDOException $e)
    {
        echo $e->getMessage();
    }
}
Comments