A. Rossi A. Rossi - 2 years ago 79
PHP Question

Check if username (Hashed) or email(Hashed) alredy exist with pdo

i am trying to verify if username or email are alredy 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, i am new in php... Thanks, in advice for your time, best regards

Answer Source

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;

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download