PHP Function Reference

PHP password_needs_rehash() Function



The PHP password_needs_rehash() function is used to check if the given hash implements the algorithm and options provided. If not, it is assumed that the hash needs to be rehashed.

Syntax

password_needs_rehash(hash, algo, options)

Parameters

hash Required. Specify a hash created by password_hash().
algo Required. Specify a password algorithm constant denoting the algorithm to use when hashing the password.
options Optional. Specify an associative array containing options. See the password algorithm constants for documentation on the supported options for each algorithm.

Return Value

Returns true if the hash should be rehashed to match the given algo and options, or false otherwise.

Example: password_needs_rehash() example

The example below shows the usage of password_needs_rehash() function.

<?php
$password = 'myPassword';
$hash = "$2y$10$.SCsHZ4KA04AFwoRj6XOS.6iKtQzsO.ydxo6gOVbauASPEoV6cm4a";

//the cost parameter can change 
//over time as hardware improves
$options = array('cost' => 11);

//verifying stored hash against plain-text password
if(password_verify($password, $hash)) {
  //check if a newer hashing algorithm 
  //is available or the cost has changed
  if(password_needs_rehash($hash, PASSWORD_DEFAULT, $options)) {
    //if so, create a new hash, 
    //and replace the old one
    $newHash = password_hash($password, PASSWORD_DEFAULT, $options);
  }
  //log user in
}

//displaying $hash and $newHash
//for illustration purpose
echo $hash;
echo "\n";
echo $newHash;
?>

The output of the above code will be:

$2y$10$.SCsHZ4KA04AFwoRj6XOS.6iKtQzsO.ydxo6gOVbauASPEoV6cm4a
$2y$11$2WqyJXTttAT2JOTDECchz.DfqvpNdu5l6ICnl2rumXRsO9kUwX8Xa

❮ PHP Password Hashing Reference