YII2 Implementing the Change Password function
Main difficulties:
1. Password encryption
YII2 The result of password encryption is different, that is, with the same initial password at different times to obtain the encryption results are different, so we can not use the usual method to verify that the password is correct (after encrypting the password and the password in the database to compare). YII2 has its own encryption and password verification process.
Encryption $hash = Yii:: $app->getsecurity ()->generatepasswordhash (' 123456 ');
Verify YII:: $app->getsecurity ()->validatepassword (' 123456 ', $hash), returns TRUE or False
2. Return to Information processing
Yii:: $app->session->setflash (' contact ', ' old password error ');//Set Flash
return $this->goback (); Page Jump
Yii:: $app->session->getflash (' contact '); Get Flash
PublicfunctionActionpassword () {$model=NewPasswordform; $request= YII::$app-request; if($request-isPost) { $p=$request->post (' Passwordform '); $id= YII::$app->user->ID; $admin= Admin::findidentity ($id); $password=$admin-password; if(Yii::$app->getsecurity ()->validatepassword ($p[' Password '],$password)){ if($p[' pass1 '] = =$p[' Pass2 ']){ $newPass= Yii::$app->getsecurity ()->generatepasswordhash ($p[' Pass1 ']); $connection= \yii::$app-DB; $r=$connection->createcommand ()->update (' admin ', [' password ' + =$newPass], ' id= '.$id),execute (); if($r) {Yii::$app->user->logout (); return$this-GoHome (); }Else{ return$this-GoBack (); } } }Else{Yii::$app->session->setflash (' contact ', ' Old password error '); return$this->redirect (Array(' Site/password ')); } }Else{ return$this->render (' Password ', [' model ' =$model]); } }
Code optimization: The main optimization details are as follows
1. Move the main logic code in the controller into the model
2. Optimize database operation
In the controller:
Public function Actionpassword () { $model=new passwordform; $request = YII::$app,request; if ($request$model->load (Yii::$app$model-ChangePassword () ) { Yii::$app->user->logout (); return $this-GoHome (); } Else { return$this->render (' Password ', [' model ' = +$model] ); } }
In the Model:
PublicfunctionChangePassword () {$id= YII::$app->user->ID; $admin= Admin::findidentity ($id); $password=$admin-password; if(Yii::$app->getsecurity ()->validatepassword ($this->password,$password)){ if($this->pass1 = =$this-pass2) { $newPass= Yii::$app->getsecurity ()->generatepasswordhash ($this-Pass1); $admin->password =$newPass; if($admin-Save ()) { returntrue; }Else{ returnfalse; } }Else{Yii::$app->session->setflash (' contact ', ' two Times New password not equal '); returnfalse; } }Else{Yii::$app->session->setflash (' contact ', ' Old password error '); returnfalse; } }
The above describes the YII framework to implement password modification, including the aspects of the content, I hope that the PHP tutorial interested in a friend helpful.