ZF2 setCookie not working
Since a while I am trying to figure out why setting a cookie through ZF2 seems to be so hard? Probably it isn't but I can't figure out why the cookie isn't set.
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);
Testing output by dump
Doesn't contain the 'accepted_cookies' or '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.
When using cookies in Zend Framework 2 there is no need to interact with the super global directly. 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.