Home  >  Article  >  Backend Development  >  What should I do if YII2 automatic login cookies always expire?

What should I do if YII2 automatic login cookies always expire?

小云云
小云云Original
2018-02-10 13:30:291461browse

I recently worked on the automatic login function of Yii2 and found that even if the automatic login configuration function of Yii2 is turned on, after closing the browser, it is still in a non-login state when opening the browser again. , there is basically no same situation when searching for information online. This article mainly introduces to you the solution to the problem that the YII2 automatic login cookie always fails. I hope it will be useful to everyone.

Preface

Query the login source code:

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);
}

Print the cookie variable and found that there is no problem with the content. There is no problem in copying the code to other controllers for execution.

Looking at the browser, the sessionID set by Yii2 is also normal, that is, the cookie setting is not successful here.

Since there is no problem with the system and the browser, then there is a problem with the transmission process.

Later I finally discovered: It turns out that after calling the $model->login() login method, I directly output the json data to the browser, and there is an exit method behind it, which directly prevents the controller from continuing to execute.

So, the execution of yii2 ends at exit, resulting in the header information not being transmitted to the browser. So the browser does not receive the command from PHP to set the cookie at all.

Summary

For Yii2 login or controllers that need to set cookies, never exit or die, use if else to judge directly, and do not interrupt execution.

Related recommendations:

Single sign-on cookie analysis and implementation in PHP

Example of php simulated login to save login cookie information

php curl login cookie value access example

The above is the detailed content of What should I do if YII2 automatic login cookies always expire?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn