I found this topic Zend Framework 2 - Cookie Concept while I was searching for info about setting cookie in ZF2, but seems like information included in that topic are out of date.
I have tried following code:
public function indexAction()
{
$request = $this->getRequest()->getHeaders()->get('Set-Cookie')->foo = 'bar;
$response = $this->getResponse()->getCookie()->baz = 'test';
var_dump($_COOKIE);
...
return new ViewModel();
}
Both lines output warning:
Warning: Creating default object from empty value
I tried also:
public function indexAction()
{
$cookie = new SetCookie('test', 'value', 60*60*24); // Zend\Http\Header\SetCookie instance
$header = new Cookie(); // Zend\Http\Cookies instance
$header->addCookie($cookie);
...
return new ViewModel();
}
It doesn't return any error or warning, everything seems to be ok, but when I try var_dump($_COOKIE) it still shows null.
Yes, my browser has enable cookie.
Here is my solution which I'm currently using.
$cookie = new SetCookie('key', 'value', time() + 365 * 60 * 60 * 24); // now + 1 year
$headers = $this->getResponse()->getHeaders();
$headers->addHeader($cookie);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With