Home > Article > PHP Framework > Reasons why yii2 cookie cannot be retrieved
Yii2's Cookies are mainly operated through yii\web\Request and yii\web\Response
##Pass \Yii::$app->response->getCookies()->add()Add CookieRead 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 thatWhen 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!