这是我的代码:
//save user in DB
$email='user1@email.com';
$username='user1';
$password='user1';
echo 'No hashed password='.$password.'<br>';
$user= new User();
$user->email=$email;
$user->username=$username;
$user->password=Yii::$app->getSecurity()->generatePasswordHash($password);
echo 'Hashed password='.$user->password;
echo '<br>';
$user->save();
//check user
$password2 ='user1';
$password2=Yii::$app->getSecurity()->generatePasswordHash($password2); //do hash
echo 'Hashed password2='.$password2;
$check_user=User::find()->where(['email' => $email])->one();
if($check_user) { //if user found
if (Yii::$app->getSecurity()->validatePassword($password2, $check_user->password)) {
echo 'Yes';
} else {
echo 'No';
}
}
我将数据(电子邮件,用户名,密码)保存在数据库中。当我想查看我的密码时,我总是得到否。 我怎样才能解决我的问题?
答案 0 :(得分:1)
检查密码时,您不需要生成新哈希。只需将信息($password2
)与您保存的哈希值($check_user->password
)进行比较。
//check user
$password2 ='user1';
echo 'password2 = ' . $password2 . '<br />';
$check_user=User::find()->where(['email' => $email])->one();
if($check_user) //if user found
{
if (Yii::$app->getSecurity()->validatePassword($password2, $check_user->password)) {
echo 'Yes';
} else {
echo 'No';
}
}