I am trying to verify if username
or email
are already taken in a registration form, but I can't understand how to do it, since both are hashed in my database with password_hash()
, how can I compare, users input with the database in pdo? Please explain me the code.
If your emails are hashed with a unique salt per hash, there is no way to test for the existence of any one particular email short of testing the needle against all hashes in the database. E.g.:
foreach ($db->query('SELECT email_hash FROM users') as $user) {
if (password_verify($_POST['email'], $user['email_hash'])) {
$found = true;
break;
}
}
There is no other way, since you cannot recreate the hash without the individual salt, and since you don't know what salt you're looking for you simply have to do them all.
If you're going to hash data that you need to search by in the database at all, at the very least it cannot be salted. But if it's not salted, it offers little protection against the scenario you're trying to defend against. Bottom line: hashing data that you need to query by is pretty pointless.