PHP password hashing and verifying

Password hashing is to prevent easy password exploiting by not storing password in plaintext. Instead you store a hash and verify this against the login attempt. Imagine if a database got compromised and all the passwords where simply in plaint text (Hunter123) rather than a hash ($2y$10$LO2OFtEQ71fCSLnq3NTGlOsJTcFoEiwnbVNNBXUPup3anqih1AaSe).

PHP password hashing and verifying involves using password_hash and password_verify. The below method uses the default algorithm for hashing (PASSWORD_DEFAULT).

$password = 'thisisNOTastrongpassword';//$_POST value normally
$password_hash = password_hash($password, PASSWORD_DEFAULT);

$password_hash would get stored in a database however you can see the password hash with:

echo $password_hash;//$2y$10$ylmpIaGuLfDOJCdmM0f4oOfbZxsBU22LI/2DzHnLs0Y3fkRQvYCpi

To verify that the password is correct you would fetch the hash from the database and with the users posted password (upon login attempt) run:

if(password_verify($password, $password_hash)) {
    //x
    //the password is right, it matches the hash
    echo 'correct';
} else {
    //y
    //password does NOT match the hash
}

If there is a match (password_verify is true) with the password and hash from the database run x otherwise run other y.

It is so simple to verify and store passwords safetly that it’s no excuse for plaintext password storage in web dev.