How to use cookies in Zend?
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 wi开发者_运维百科th Zend?
Thanks
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');
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 ;)
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);
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()
.
精彩评论