Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zf2 - How to set cookie

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.

like image 480
user1409508 Avatar asked Jul 23 '13 09:07

user1409508


1 Answers

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);
like image 173
Adrian Nowicki Avatar answered Oct 21 '22 06:10

Adrian Nowicki