简体   繁体   English

ZF2 setCookie 不起作用

[英]ZF2 setCookie not working

Since a while I am trying to figure out why setting a cookie through ZF2 seems to be so hard?有一段时间我试图弄清楚为什么通过 ZF2 设置 cookie 似乎如此困难? Probably it isn't but I can't figure out why the cookie isn't set.可能不是,但我不知道为什么没有设置 cookie。

Code代码

use Zend\Http\Header\SetCookie;

    $response        = $this->getResponse()->getHeaders();
    $cookiesAccepted = new SetCookie('accepted_cookies', 1, strtotime('+1 Year', time()), '/');
    $cookieTest      = new SetCookie('test_key', 'test_value', strtotime('+1 Year', time()), '/');
    $response        ->addHeader($cookiesAccepted);
    $response        ->addHeader($cookieTest);

Refreshing page.刷新页面。

Testing output by dump通过转储测试输出

Debug::dump($_COOKIE);

Doesn't contain the 'accepted_cookies' or 'test_key' cookie.不包含“accepted_cookies”或“test_key”cookie。

You set cookies in the response object and dumping $_COOKIE will not immediately give you the cookies that you added to your response object.您在响应对象中设置 cookie 并且转储$_COOKIE不会立即为您提供添加到响应对象中的 cookie。

When using cookies in Zend Framework 2 there is no need to interact with the super global directly.在 Zend Framework 2 中使用 cookie 时,无需直接与超级全局交互。 Check also the documentation for reference .另请查看文档以供参考

You could try like this in your next request object:您可以在下一个请求对象中尝试这样:

$accepted_cookies = $this->getRequest()->getHeaders()->get('Cookie')->accepted_cookies;
$test_key = $this->getRequest()->getHeaders()->get('Cookie')->test_key;

Check also this answer for more examples on cookie management.另请查看此答案以获取有关 cookie 管理的更多示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM