无法在 Yii2 中获取 cookie 值
Unable to get cookie value in Yii2
我已经使用以下代码在页面上设置了 cookie:
$newCookie= new \yii\web\Cookie();
$newCookie->name='cookie_name';
$newCookie->value='test value';
$newCookie->expire = time() + 60 * 60 * 24 * 180;
$cookie=Yii::$app->getResponse()->getCookies()->add($newCookie);
但是当我在另一个页面上尝试检查是否设置了 cookie 时,我无法获取 cookie
值:
if(Yii::$app->getResponse()->getCookies()->has('cookie_name')){
if(Yii::$app->getResponse()->getCookies()->getValue('cookie_name')){
echo "cookie available";die;
}
}
谁能告诉我我做错了什么???
非常感谢
男.
您应该使用请求组件来读取 cookies :
if(Yii::$app->getRequest()->getCookies()->has('cookie_name')){
}
阅读更多:http://www.yiiframework.com/doc-2.0/guide-runtime-sessions-cookies.html
Both yii\web\Request and yii\web\Response maintain a collection of cookies via the property named cookies. The cookie collection in the former represents the cookies submitted in a request, while the cookie collection in the latter represents the cookies that are to be sent to the user.
我已经使用以下代码在页面上设置了 cookie:
$newCookie= new \yii\web\Cookie();
$newCookie->name='cookie_name';
$newCookie->value='test value';
$newCookie->expire = time() + 60 * 60 * 24 * 180;
$cookie=Yii::$app->getResponse()->getCookies()->add($newCookie);
但是当我在另一个页面上尝试检查是否设置了 cookie 时,我无法获取 cookie 值:
if(Yii::$app->getResponse()->getCookies()->has('cookie_name')){
if(Yii::$app->getResponse()->getCookies()->getValue('cookie_name')){
echo "cookie available";die;
}
}
谁能告诉我我做错了什么???
非常感谢
男.
您应该使用请求组件来读取 cookies :
if(Yii::$app->getRequest()->getCookies()->has('cookie_name')){
}
阅读更多:http://www.yiiframework.com/doc-2.0/guide-runtime-sessions-cookies.html
Both yii\web\Request and yii\web\Response maintain a collection of cookies via the property named cookies. The cookie collection in the former represents the cookies submitted in a request, while the cookie collection in the latter represents the cookies that are to be sent to the user.