PHP密码验证总是返回false

我正在使用 PHP 的密码哈希 API 在我正在构建的网站上哈希和验证我的密码,但是每当我尝试验证我的密码时,它总是返回 false.

I'm using PHP's password hashing API to hash and verify my passwords on a site I'm building, however whenever I try and verify my password it always returns false.

我有一个 User 类,它在将密码插入数据库之前设置密码:

I have a User class which sets the password before they are inserted into the database:

public function set__password($passwd) {
    self::$password = password_hash($passwd, PASSWORD_BCRYPT, array('cost' => 12));
}

如果用户名和电子邮件是唯一的,则插入新用户行 - 检查我的数据库时,我的密码似乎是有效的 BCRYPT 字符串:

If the username and email is unique the new user row is inserted - upon checking my database I have what seems to be a valid BCRYPT string for my password:

$2y$12$lTMEP0wevDEMX0bzStzoyOEzOTIAi3Hyhd3nYjGwzbI

为了验证我的密码,我运行以下脚本:

To verify my password, I run the following script:

$username = $_POST['username'];
$password = $_POST['password'];

$DB = Database::getInstance();

// Get the stored password hash
$res = $DB->run__query('SELECT password FROM users WHERE username = "' . $username . '"');
$hash = $res[0]['password'];


// Do the passwords match?
if(password_verify($password, $hash)) {
    echo 'success';
} else {
    echo 'failed';
}

$hash 属于上面引用的字符串,但是当我随后调用 password_verify($password, $hash) 其中 $password 是从我的输入字段中检索到的纯文本密码,我总是收到一个 false 值.

$hash pertains to the string quoted above, however when I then call password_verify($password, $hash) where $password is the plain-text password retrieved from my input field, I always receive a value of false.

推荐答案

给定的哈希字符串示例有 50 个字符而不是 60 个字符.仔细检查数据库 - CHAR(60) - 和 var_dump($hash).

The given hash string example has 50 characters instead of 60. Double-Check the database - CHAR(60) - and var_dump($hash).

相关文章