在ZF2重定向上使用cookie

时间:2014-10-24 00:06:34

标签: cookies zend-framework2

我正在尝试在重定向上设置Cookie:

$cookie = new \Zend\Http\Header\SetCookie('success','1');
$response = $this->redirect()->toRoute(..., array('controller' => 'abc', 'action' => 'xyz')));
$response->getHeaders()->addHeader($cookie);
return $response;

在abc控制器的xyz动作中:

$success = $this->getRequest()->getCookie()->success;

但是没有检测到cookie?如何设置cookie并重定向?

1 个答案:

答案 0 :(得分:2)

试试这个:

$cookie = new \Zend\Http\Header\SetCookie('success','1');

//response1
$response = $this->getEvent()->getResponse();
$response->getHeaders()->addHeader($cookie);

//response2
$response = $this->redirect()->toRoute(..., array('controller' => 'abc', 'action' => 'xyz')));

return $response1;

response2response1是同一个对象....请查看Redirect Controller Plugin源代码以了解原因?

我不确定,但我认为您的代码无法正常工作,因为您需要在cookie标题之前设置location标题...

这对我有用,如果它仍然无法为你设置cookie路径:

 $cookie = new \Zend\Http\Header\SetCookie('success', '1', null, '/');