Phpass compare with saved hash in database

I have many users in database, which passwords hashed by phpass framework. As phpass returns different results all the time, so how can I select user from database which password = for example “user123”. In case of md5, I can just write

select * from users where password = md5(‘user123’)

but with phpass I can’t do like this

You need to get the password from the database and than match that against what the user typed, i.e.:


$from_database = get_password_from_database($username);
$password = get_password_the_user_typed();

$p = new PasswordHash();
if ($p->CheckPassword($password, $from_database)) {
    echo "Password correct!";
} else {
    echo "Wrong password!";
}

get_password_from_database and get_password_the_user_typed are mock functions and need to be replaced with your own code that actually does what those functions describe :slight_smile:

But in this case if for example I have 10000 users, I need to select them all and compare all passwords? Is there any way to compare in query?. As I see, you have selected user by username, so the only way, first to select by username and then compare?
I can’t just select user which password = user123

Indeed you need to query for the username (e.g. SELECT id, username, password FROM users WHERE username=:username) and then check the password in the code. If usernames are unique (as they should be) that query returns at most 1 user *, so you don’t need to compare it against the passwords of all users; just one.

So if you have 10000 users and one wants log in you just check against one, namely the one with the username they entered. If it exists, of course.

  • You can enforce this by adding LIMIT 1 to your query if you want.

Yes, you are right, thanks.