Zend Framework 2-如何检查cookie是否存在


Zend Framework 2 - How to check if a cookie exists?

如何检查cookie是否已经存在?

我试过了:

if (!$this->getRequest()->getCookie()->offsetExists('cookiename')) {
    // cookie exists
}

但是当cookie还不存在时,我会得到以下错误:

调用非对象上的成员函数offsetExists()

我想你必须先拿到cookie,然后检查它是否真的在那里。

$cookie = $this->getRequest()->getCookie();
if (empty($cookie) || !$cookie->offsetExists('cookiename')) {
   ...
}

根据官方文档和stackoverflow帖子,您可以检查cookie是否存在,如下所示:

if (!empty($this->getRequest()->getCookie('foo'))) {
    // cookie exists, do your stuff
}