Zf2 - How to set a cookie

I found this Zend Framework 2 - Cookie Concept theme when I was looking for information about setting cookies in ZF2, but it looks like the information included in this theme is missing a date.
I tried the 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 give a warning:

 Warning: Creating default object from empty value 

I also tried:

 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 does not return any errors or warnings, everything looks fine, but when I try var_dump ($ _ COOKIE), it still shows null. Yes, my browser has the ability to enable cookies.

+7
cookies zend-framework2
source share
1 answer

Here is my solution that I am currently using.

 $cookie = new SetCookie('key', 'value', time() + 365 * 60 * 60 * 24); // now + 1 year $headers = $this->getResponse()->getHeaders(); $headers->addHeader($cookie); 
+16
source share

All Articles