Zf2 - How to set cookie

*爱你&永不变心* 提交于 2019-12-05 21:24:09

问题


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.


回答1:


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);


来源:https://stackoverflow.com/questions/17806525/zf2-how-to-set-cookie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!