zend-framework2 - Zend Framework 2 - Cookie 概念

标签 zend-framework2

我已经冲浪了很多。我想使用 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';
}

请记住 CookieSet-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/

相关文章:

zend-framework - 想要在没有文本框的弹出窗口中查看信息

doctrine-orm - 使用 Doctrine 2 的 UniqueEntity

macos - 在 Mac OS X for Zend Framework 2 上为 Apache 2 安装和配置 mod_rewrite

symfony - 使用 for 循环表示 Twig 中的变量

Php mysql插入同一表id的数组键值

php - ZF2 ServiceLocatorAwareInterface getServiceLocator 给我 Zend\Validator\ValidatorPluginManager

php - Zend 框架 2 Rest API : Calls getList() instead of get($id) function

php - ZF2 转发电子邮件 (Zend\Mail\Storage\Message)

security - 如何在 Zend Framework 2 View 中自动转义变量

mysql - ZF2 带有 where 子句的内连接返回空结果