Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to store and verify a password

Short answer

On registration store the hash in the database, not the password itself:

<?php
 
$hash = password_hash('secret-password', PASSWORD_DEFAULT);
 
echo strlen($hash) >= 60 ? 'hash created' : 'error';

Output:

hash created

Checking on login

password_verify() compares the entered password with the hash from the database:

<?php
 
$hash = password_hash('secret-password', PASSWORD_DEFAULT);
 
var_dump(password_verify('secret-password', $hash));
var_dump(password_verify('wrong', $hash));

Output:

bool(true)
bool(false)

Rehashing

The default algorithm changes over time. After a successful login check whether the hash needs recomputing:

<?php
 
$hash = password_hash('secret-password', PASSWORD_DEFAULT);
 
var_dump(password_needs_rehash($hash, PASSWORD_DEFAULT));

Output:

bool(false)

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.