PHP 8.1.28 Released!


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

password_needs_rehashПроверяет, что указанный хеш соответствует заданным опциям


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

Проверяет, что указанный хеш соответствует заданным опциям и заданному алгоритму. Если нет, то можно сделать вывод о том, что хеш надо пересоздать.

Список параметров


Хеш, который создаёт функция password_hash().


Константа алгоритма хеширования пароля, который будет использовать функция.


Ассоциативный массив с опциями. За документацией по поддерживаемым опциям для каждого алгоритма обратитесь к разделу Константы алгоритмов хеширования паролей.

Возвращаемые значения

Возвращает true, если пароль должен быть перехеширован с использованием алгоритма algo и опций options, или false, если нет.

Список изменений

Версия Описание
7.4.0 Параметр algo теперь ожидает строку (string), но всё ещё принимает число (int) для обратной совместимости.


Пример #1 Пример использования password_needs_rehash()


= 'rasmuslerdorf';
$hash = '$2y$10$YCFsG6elYca568hBi2pZ0.3LDL5wjgxct1N8w/oLR/jfHsiQwCqTS';

$algorithm = PASSWORD_BCRYPT;
// Значение bcrypt-стоимости может измениться по мере роста производительности оборудования
$options = ['cost' => 12];

// Сравниваем сохранённый хеш с открытым паролем
if (password_verify($password, $hash)) {
// Проверяем, не изменился ли алгоритм или параметры
if (password_needs_rehash($hash, $algorithm, $options)) {
// Если были изменения, перехешируем и заменяем старый хеш новым
$newHash = password_hash($password, $algorithm, $options);

// Обновляем запись пользователя новым $newHash

// Авторизуем пользователя

add a note

User Contributed Notes 4 notes

php dot net at muer dot nl
9 years ago
This function cannot check if a string is a MD5 or SHA1 hash. It can only tell you if a password, hashed using the password_hash function, needs to be put through the hashing function again to keep up to date with the new defaults.

The only time you can use this function is when your user logs in and you have already checked by means of password_verify that the password entered is actually correct. At that point, if password_needs_rehash returns true, you can put the plain text password through the password_hash function.
geekasylum at google mail
5 years ago
This function can indeed be used to assist in transparently updating legacy passwords (those not using the password_hash() function - eg: perhaps something using MD5 or SHA1)

In legacy sites, when authenticating a user (during login) first check the password using password_verify(). If that fails it may simply be because the user's password hash was created long ago by a legacy or home-brew password algorithm.

You can then re-check the password against the site's legacy password algorithm. If that fails too, then the login fails, since the supplied password did not authenticate against either the new, or the old password tests.

If any one of those two test was successfull, you know that the password is good so you would then call password_needs_rehash() on the stored hash, and it will properly indicate if the password hash needs to be re-computed, either because it's an unrecognised (legacy) hash or it's a modern hash created by password_hash(), which may just need its cost index updated.

Simply store the recomputed hash in the database and you now have a password_verify() compatible password for that user and the second test can be skipped in future logins (but still check if it needs rehashing).
admin at torntech dot com
9 years ago
Some other use-cases for the password_needs_rehash function is when you have specified using the PASSWORD_DEFAULT algorithm for password_hash.
As mentioned on the Password Hashing Predefined Constants and password_hash pages, the algorithm used by PASSWORD_DEFAULT is subject to change as different versions of PHP are released.
Additionally password_needs_rehash would be used if you have changed the optional cost or static salt (DO NOT USE A STATIC SALT) requirements of your password_hash options.

Full example:


= [
'options' => ['cost' => 11],
'hash' => null

$password = 'rasmuslerdorf';

//stored hash of password
$oldHash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

//verify stored hash against plain-text password
if (true === password_verify($password, $oldHash)) {
//verify legacy password to new password_hash options
if (true === password_needs_rehash($oldHash, $new['algo'], $new['options'])) {
//rehash/store plain-text password using new hash
$newHash = password_hash($password, $new['algo'], $new['options']);

The above example will output something similar to:
Daniel Hejduk
2 years ago
Password need rehash also when its too strong. For example
= '123';
$hash = password_hash($a, PASSWORD_BCRYPT, ['cost'=>16]);
var_export(password_needs_rehash($hash, PASSWORD_BCRYPT, ['cost'=>15])); //True
To Top