我已经冲浪了很多。我想使用 COOKIE 分配和检索一个值。我在 ZF2 怎么办?我看到了很多在 cookie 中赋值的例子。请解释如何从 cookie 中检索值。
最佳答案
HTTP 中的 cookie(参见 RFC 2109 只是存储在请求中的一些东西,并在每次发出请求时发送。响应可以添加其他参数以额外存储到已经存在的 cookie 中。
所以cookie检索是通过Request
完成的, 要更新 cookie,您可以使用 Response
.根据 RFC 2109,您分别使用 Cookie
标题和 Set-Cookie
标题。因此,您可以通过以下方式直接访问这些 header
$this->getRequest()->getHeaders()->get('Cookie')->foo = 'bar';
或通过以下方式设置 cookie:
$this->getResponse()->getHeaders()->get('Set-Cookie')->foo = 'bar';
不过事情变得更容易了,因为在请求和响应中有一个代理可以直接访问 cookie:
public function fooAction()
{
$param = $this->getRequest()->getCookie()->bar;
$this->getResponse()->getCookie()->baz = 'bat';
}
请记住
Cookie
和 Set-Cookie
header 实现 ArrayObject
目的。要检查请求中是否存在 cookie,您可以使用 offsetExists
:if ($cookie->offsetExists('foo')) {
$param = $cookie->offsetGet('foo');
}
/更新:
如果你想修改cookie的属性,你也在这里修改
Set-Cookie
标题。看看at the class on Github对于所有可用的方法。一个小总结:
$cookie = $this->getResponse()->getCookie();
$cookie->foo = 'bar';
$cookie->baz = 'bat';
$this->setDomain('www.example.com');
$this->setExpires(time()+60*60*24*30);
关于zend-framework2 - Zend Framework 2 - Cookie 概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14263446/