Recently did YII2 automatic login function, found that even if the YII2 automatic login configuration feature is turned on, when the browser is closed, the browser is opened again or is not logged in. , the information on the Internet is basically not the same situation. This article mainly introduces to you about the YII2 automatic login cookie always fails the solution, hope to be useful to everyone.
Objective
Query Login Source:
protected function Sendidentitycookie ($identity, $duration) {$cookie = new cookie ($this->identitycookie); $cookie- >value = Json_encode ([ $identity->getid (), $identity->getauthkey (), $duration,], Json_ unescaped_slashes | Json_unescaped_unicode); $cookie->expire = time () + $duration; Yii:: $app->getresponse ()->getcookies ()->add ($cookie);}
The print cookie variable found nothing wrong with the content. Copying code to other controller execution is also no problem.
Viewing the browser, YII2 settings SessionID is also normal, that is, the cookie is only set here is not successful.
Since, the system is not a problem, the browser is not a problem, then the transmission process is problematic.
Finally found that: the original after calling the $model->login () login method, I directly output JSON data to the browser, and in the back of the exit method, directly prevent the controller to continue execution.
Therefore, the yii2 execution to exit is finished, resulting in header headers are not transmitted to the browser. Therefore, the browser does not receive a PHP settings Cookie command.
Summarize
YII2 Login or the controller that needs to set the cookie, do not exit or die, directly use if else to judge, do not interrupt execution.