Development

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.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago