php8.5
Home/ Manual/ password / functions/ password_needs_rehash

password_needs_rehash

PHP function Edit on GitHub ✎

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

Checks if the given hash matches the given options

Description

password_needs_rehash(string $hash, string|int|null $algo, array $options = []): bool

This function checks to see if the supplied hash implements the algorithm and options provided. If not, it is assumed that the hash needs to be rehashed.

Parameters

hash

Hash

algo

Algo

options

Options

Return Values

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

Changelog

VersionDescription
7.4.0The algo parameter expects a String now, but still accepts Integers for backward compatibility.

Examples

Usage of password_needs_rehash()

php
<?php

$password = 'rasmuslerdorf';
$hash = '$2y$12$4Umg0rCJwMswRw/l.SwHvuQV01coP0eWmGzd61QH2RvAOMANUBGC.';

$algorithm = PASSWORD_BCRYPT;
// bcrypt's cost parameter can change over time as hardware improves
$options = ['cost' => 13];

// Verify stored hash against plain-text password
if (password_verify($password, $hash)) {
    // Check if either the algorithm or the options have changed
    if (password_needs_rehash($hash, $algorithm, $options)) {
        // If so, create a new hash, and replace the old one
        $newHash = password_hash($password, $algorithm, $options);

        // Update the user record with the $newHash
    }

    // Perform the login.
}
?>

Source: reference/password/functions/password-needs-rehash.xml · from the official PHP manual (php/doc-en)