password_verify 功能不工作

password_verify function not working

嘿,我在使用 password_verify 函数时遇到了问题。 注册正在工作,但出于某种奇怪的原因,当我尝试使用它进行登录时,它只是说不正确。

这是我的代码(请不要评判,我对一切都还很陌生。

$username = $_POST['username'];
$password = $_POST['password'];
$SQLSelect = $odb -> prepare("SELECT * FROM `users` WHERE `username` = :username");
$SQLSelect -> execute(array(':username' => $_POST['username']));
while ($show = $SQLSelect -> fetch(PDO::FETCH_ASSOC))
{
$passwordHash = $show['password'];
}
$date = strtotime('-1 hour', time());
$attempts=$odb->query("SELECT COUNT(*) FROM `loginlogs` WHERE `ip` = '$ip' AND `username` LIKE '%failed' AND `date` BETWEEN '$date' AND UNIX_TIMESTAMP()")->fetchColumn(0);

//Check fields
if (empty($username) || empty($password) || !ctype_alnum($username) || strlen($username) < 4 || strlen($username) > 15)
{
die(error('Please fill in all fields.'));
}

//Check login details
echo $passwordHash;
$SQLCheckLogin = $odb -> prepare("SELECT COUNT(*) FROM `users` WHERE `username` = :username AND `password` = :password");
$SQLCheckLogin -> execute(array(':username' => $username, ':password' => password_verify($password, $passwordHash)));
$countLogin = $SQLCheckLogin -> fetchColumn(0);
if (!($countLogin == 1))
{
$SQL = $odb -> prepare("INSERT INTO `loginlogs` VALUES(:username, :ip, UNIX_TIMESTAMP(), 'XX')");
$SQL -> execute(array(':username' => $username." - failed",':ip' => $ip));
die(error('Username or password are invalid.'));

有人知道为什么这不起作用吗?我仔细检查了所有内容,应该没问题,echo $passwordHash 只是我检查我是否能够获得正常工作的密码。 :/

password_verify($password, $passwordHash) 这个 returns 一个布尔值。您应该做的是使用它来验证密码是否与哈希匹配。删除所有这些:

$SQLCheckLogin = $odb -> prepare("SELECT COUNT(*) FROM `users` WHERE `username` = :username AND `password` = :password");
$SQLCheckLogin -> execute(array(':username' => $username, ':password' => password_verify($password, $passwordHash)));
$countLogin = $SQLCheckLogin -> fetchColumn(0);
if (!($countLogin == 1))

只需这样做:

if (!password_verify($password, $passwordHash)) {
    // ...
    die(error('Username or password are invalid.'));
}