Zf2 - 如何设置cookie [英] Zf2 - How to set cookie
本文介绍了Zf2 - 如何设置cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我发现这个话题 Zend框架2 - 曲奇的概念,而我正在寻找有关在ZF2中设置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();
}
两行输出警告:
Warning: Creating default object from empty value
我想也:
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();
}
它不返回任何错误或警告,一切似乎都确定,但是当我尝试的var_dump($ _ COOKIE),它仍然显示为空。结果
是的,我的浏览器已经实现的cookie。
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);
这篇关于Zf2 - 如何设置cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文