这是我的代码:
//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';
}
}
我将我的数据(电子邮件、用户名、密码)保存在数据库中。当我想检查我的密码时,我总是得到否。我该如何解决我的问题?
检查密码时不需要生成新的哈希。只需将信息($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';
}
}
您可以在文档中找到更多信息:此处和此处。