How to use cookies in Zend?

2019-03-18 06:30发布

问题:

How I use Zend_Http_Cookie to set and read cookies?

I trie to set cookie like this:

$cookie = new Zend_Http_Cookie('TestCookie','TestValue','localhost.com') but no cookie is generated. Also how I read cookies with Zend?

Thanks

回答1:

As far as i know is there not "setCookie" Class in Zend Framework. Simply use "plain" php:

setcookie('cookieName', 'value', 'lifetime', 'path', 'domain');

To read an cookie, you can use Zend_Controller_Request_Http(); as Example:

  $request = new Zend_Controller_Request_Http();
  $myCookie = $request->getCookie('cookieName');


回答2:

For Zend 1.12, there is a way to set cookies for the response object.

The link to the portion in the manual is included below. I've also attached their examples in case the page ever disappears.

http://framework.zend.com/manual/1.12/en/zend.controller.response.html#zend.controller.response.headers.setcookie

$this->getResponse()->setRawHeader(new Zend_Http_Header_SetCookie(
    'foo', 'bar', NULL, '/', 'example.com', false, true
));

or

$cookie = new Zend_Http_Header_SetCookie();
$cookie->setName('foo')
       ->setValue('bar')
       ->setDomain('example.com')
           ->setPath('/')
       ->setHttponly(true);
$this->getResponse()->setRawHeader($cookie);

It is important to use Zend's objects and classes so that you don't run into issues when creating Tests ;)



回答3:

From Zend's github issue about multiple cookies:

$setCookieHeader = new Zend_Http_Header_SetCookie('othername1', 'othervalue1');
$appendCookie = new Zend_Http_Header_SetCookie('othername2', 'othervalue2');
$headerLine = $setCookieHeader->toStringMultipleHeaders(array($appendCookie));

$this->getResponse()->setRawHeader($headerLine);


回答4:

Looking at the docs for Cookie and remembering from past experience there isn't a way of telling a cookie object to be sent along with a Response.

I suggest just using setcookie().