Menü schliessen
Created: July 15th 2018
Categories: Common Web Development
Author: Marcus Fleuti

Best way to store user passwords and verify them

Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

Recently we were working on a project that required user management and we looked for the best solution to handle passwords. One that would be easy to use and as safe as possible… What we came across are two PHP functions named password_hash() and password_verify().
Password hash creation example:

$input = 'some_password123';
$algorithm = PASSWORD_BCRYPT;
$options = [
    'cost' => 12
];
// list of $algorithms and $options can be found here: http://php.net/manual/en/password.constants.php
$hash = password_hash($input, $algorithm, $options);
echo $hash; // $2y$12$J6gJIPz/kFKVEUX0qbq4wur.y7sjTEBPHyJ2MOrEZc4/NQpLR9Hv.

Created hash can be used for verification when needed. Example:

$hash = '$2y$12$J6gJIPz/kFKVEUX0qbq4wur.y7sjTEBPHyJ2MOrEZc4/NQpLR9Hv.'; //value stored in the database (taken from previous example...)
$faulty_password = '123456';// wrong password  
$correct_password = 'some_password123'; // correct password
// Faulty password  check - case where user enters wrong password
If(password_verify($faulty_password, $hash)){
    echo 'Password 1 is correct';
}
else{
    echo 'Password 1 is incorrect!'; //This check will end here
}
// Correct password check - case where user enters correct password
If(password_verify($correct_password, $hash)){
    echo 'Password 2 is correct!'; // While this check would end here..
}
else{
    echo 'Password 2 is incorrect!';
}

More information can be found on following links:
http://php.net/manual/en/function.password-hash.php
http://php.net/manual/en/function.password-verify.php