©
Ce document utilise Manuel du site Web PHP chinois Libérer
(PHP 5 >= 5.5.0)
password_verify — Verifies that a password matches a hash
$password
, string $hash
)Verifies that the given hash matches the given password.
Note that password_hash() returns the algorithm, cost and salt as part of the returned hash. Therefore, all information that's needed to verify the hash is included in it. This allows the verify function to verify the hash without needing separate storage for the salt or algorithm information.
This function is safe against timing attacks.
password
用户的密码。
hash
一个由 password_hash() 创建的散列值。
Returns TRUE
if the password and hash match, or FALSE
otherwise.
Example #1 password_verify() example
<?php
// See the password_hash() example to see where this came from.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq' ;
if ( password_verify ( 'rasmuslerdorf' , $hash )) {
echo 'Password is valid!' ;
} else {
echo 'Invalid password.' ;
}
?>
以上例程会输出:
Password is valid!
[#1] Anonymous [2014-05-29 01:40:33]
If you get incorrect false responses from password_verify when manually including the hash variable (eg. for testing) and you know it should be correct, make sure you are enclosing the hash variable in single quotes (') and not double quotes (").
PHP parses anything that starts with a $ inside double quotes as a variable:
<?php
// this will result in 'Invalid Password' as the hash is parsed into 3 variables of
// $2y, $07 and $BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq
// due to it being enclosed inside double quotes
$hash = "$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq";
// this will result in 'Password is valid' as variables are not parsed inside single quotes
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';
if (password_verify('rasmuslerdorf', $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
?>
[#2] suit at rebell dot at [2013-10-18 19:18:19]
As Vasil Toshkov stated, password_verify() can be used to verify a password created by crypt() or password_hash()
That is because passwords created by password_hash() also use the C crypt sheme
If you want to verify older plain MD5-Hashes you just need to prefix them with $1$
See https://en.wikipedia.org/wiki/Crypt_(C) for more information.
[#3] Vasil Toshkov [2013-10-12 21:16:22]
This function can be used to verify hashes created with other functions like crypt(). For example:
<?php
$hash = '$1$toHVx1uW$KIvW9yGZZSU/1YOidHeqJ/';
if (password_verify('rasmuslerdorf', $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
// Output: Password is valid!
?>