php password_hash 和 password_verify 问题不匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19855715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 20:08:45  来源:igfitidea点击:

php password_hash and password_verify issues no match

phppasswordsphp-password-hash

提问by Daniel

I am trying out a new function from PHP 5.5 called password_hash().

我正在尝试 PHP 5.5 中名为 password_hash() 的新函数。

No matter what i do the $hash and the $password wont match.

无论我做什么,$hash 和 $password 都不会匹配。

$password = "test";

$hash = "y$fXJEsC0zWAR2tDrmlJgSaecbKyiEOK9GDCRKDReYM8gH2bG2mbO4e";



if (password_verify($password, $hash)) {
    echo "Success";
}
else {
    echo "Error";
}

回答by initramfs

The problem with your code is that you are using the double quotation marks "instead of the single quotation marks 'when dealing with your hash.

您的代码的问题在于您在处理哈希时使用双引号"而不是单引号'

When assigning:

赋值时:

$hash = "y$fXJEsC0zWAR2tDrmlJgSaecbKyiEOK9GDCRKDReYM8gH2bG2mbO4e";

It's making php think you have a variable called $2yand another one called $10and finally a third one called $fXJEsC0zWAR2tDrmlJgSaecbKyiEOK9GDCRKDReYM8gH2bG2mbO4e. Which obviously isn't the case.

它让 php 认为你有一个变量叫$2y,另一个叫$10,最后第三个叫$fXJEsC0zWAR2tDrmlJgSaecbKyiEOK9GDCRKDReYM8gH2bG2mbO4e. 显然情况并非如此。

I noticed when turning on error reporting that the error:

我在打开错误报告时注意到错误:

Notice: Undefined variable: fXJEsC0zWAR2tDrmlJgSaecbKyiEOK9GDCRKDReYM8gH2bG2mbO4e

注意:未定义变量:fXJEsC0zWAR2tDrmlJgSaecbKyiEOK9GDCRKDReYM8gH2bG2mbO4e

Was being thrown by PHP.

被 PHP 抛出。

Replace all your double quote marks with single quote marks to fix.

用单引号替换所有双引号以进行修复。

E.g

例如

$hash = 'y$fXJEsC0zWAR2tDrmlJgSaecbKyiEOK9GDCRKDReYM8gH2bG2mbO4e';

Treats the whole hash as a literal string instead of a string with embedded variables.

将整个散列视为文字字符串,而不是带有嵌入变量的字符串。

回答by Antonis Tzilivakis

I had a similar problem with password_verify()..The mistake in my case, it was that i have declared my password field in the database as varchar(30), but the hash is equal or longer to 60 characters..

我有一个与 password_verify() 类似的问题。在我的情况下,我的错误是我在数据库中将我的密码字段声明为 varchar(30),但哈希等于或长于 60 个字符。

回答by Shankar Damodaran

Works fine for me.

对我来说很好用。

<?php

$hash=password_hash("rasmuslerdorf", PASSWORD_DEFAULT);
if (password_verify('rasmuslerdorf', $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}
?>

OUTPUT:

输出:

Password is valid!

密码有效!