Answer the question
In order to leave comments, you need to log in
How to properly store password in Yii2?
Problem:
My User table has a password_hash field.
I am creating a form in which the user can change his email name and password.
By displaying this form, I do not want to show the user the current password (especially its hash).
Therefore, I created two properties in the model
public $password;
public $password_repeat;
function rules(){
return [ ['password_repeat', 'compare', 'compareAttribute' => 'password']];
}
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($user, 'username') ?>
<?= $form->field($user, 'email') ?>
<?= $form->field($user, 'password')->passwordInput() ?>
<?= $form->field($user, 'password_repeat')->passwordInput() ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
$user_id = Yii::$app->getUser()->id;
$user = User::findOne($user_id);
$post = Yii::$app->request->post();
if(isset($post['User']['password'])){
$user->setPassword(Yii::$app->request->post('password'));
unset($post['User']['password']);
unset($post['User']['password_repeat']);
}
if ($user->load($post) && $user->validate()) { .....
Answer the question
In order to leave comments, you need to log in
And why do you need all this:
if(isset($post['User']['password'])){
$user->setPassword(Yii::$app->request->post('password'));
unset($post['User']['password']);
unset($post['User']['password_repeat']);
}
// validates if the value of "password" attribute equals to that of "password_repeat"
['password', 'compare'],
this should be enough
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question