password_verify won't work after storing in database

247 views Asked by At

I have been searching and reading for about 50 posts about my problem, but still can't figure out my problem, so I am here.

Problem: password_verify() returns false even if password is correct.

This is how I store password into db(When register and edit profile)

$hashedPassword = password_hash($password, PASSWORD_DEFAULT);

And my latest password_verify() (I have tried many examples, no one works and now I'm sitting here with still not working code)

public function doLogin($username,$password){
    try{

        $stmt = $this->conn->prepare("SELECT id, username, password FROM users WHERE username=:username");
        $stmt->execute(array(':username'=>$username));
        $userRow=$stmt->fetch(PDO::FETCH_ASSOC);

        if (password_verify($password, $userRow['password'])) {
            $_SESSION['user_session'] = $userRow['id'];
            $_SESSION["result"]='You have succesfully logged in your profile!';
            return true;
        }else{
            return false;
        }

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

My database field is 25 characters long. What is wrong here?

1

There are 1 answers

0
Qirel On BEST ANSWER

As per the manual for password_hash()

[...] Therefore, it is recommended to store the result in a database column that can expand beyond 60 characters (255 characters would be a good choice)

That means that password_verify() will silently fail if you have a column that has length of 59 or less. Because MySQL will truncate the the hashed string when you insert the hashed password without saying anything.

The solution is to set your password column to length of 60 or higher - the manual suggests setting it to 255, so just do that.

Any passwords already stored won't have their hashes fixed, so they need to be updated or re-inserted.