How to use cookies in Zend?

2019-03-18 05:48发布

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

4条回答
\"骚年 ilove
2楼-- · 2019-03-18 06:30

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');
查看更多
贼婆χ
3楼-- · 2019-03-18 06:34

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 ;)

查看更多
做自己的国王
4楼-- · 2019-03-18 06:36

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);
查看更多
淡お忘
5楼-- · 2019-03-18 06:44

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().

查看更多
登录 后发表回答