Home  >  Article  >  PHP Framework  >  Reasons why yii2 cookie cannot be retrieved

Reasons why yii2 cookie cannot be retrieved

(*-*)浩
(*-*)浩Original
2019-11-05 11:55:483144browse

Yii2's Cookies are mainly operated through yii\web\Request and yii\web\Response

Reasons why yii2 cookie cannot be retrieved

##Pass \Yii::$app->response->getCookies()->add()Add Cookie

Read Cookie through \Yii::$app->request->cookies. ( Recommended learning:

yii tutorial)

Cookies created in js default to the method Yii::$app->request->cookies- >Get('abc') cannot obtain it, but it can be obtained by using $_COOKIE['abc']. This is due to the following reasons.

Looking at line 1218 in E:\myYiiDemo\vendor\yiisoft\yii2\web\Request.php, it is not difficult to see that

When using the method in yii2 to obtain the cookie, it will be read Use the string in cookieValidationKey to decrypt (it will also be used to encrypt the cookie when storing it).

Since js does not encrypt the cookie, it cannot be decrypted here, and naturally the cookie cannot be obtained.

The solution can be to set enableCookieValidation to false. The specific operations are as follows:

Yii::$app->request->enableCookieValidation = false;
Yii::$app->request->cookies->get('abc');

Warm reminder:

Remember to restore it after use (Yii::$app->request->enableCookieValidation = true;), otherwise it may affect the following logic.

The above is the detailed content of Reasons why yii2 cookie cannot be retrieved. 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
Previous article:How to use yii2 aftersaveNext article:How to use yii2 aftersave