Reputation: 33
I am trying to remove cookies from my controller UserController
for ZfcUser
Module.
When the user logs out, I want to delete all cookies.
For example, I am setting cookies in the view:
setcookie("var", $value);
LogoutAction :
public function logoutAction()
{
$this->zfcUserAuthentication()->getAuthAdapter()->resetAdapters();
$this->zfcUserAuthentication()->getAuthAdapter()->logoutAdapters();
$this->zfcUserAuthentication()->getAuthService()->clearIdentity();
$redirect = $this->params()->fromPost('redirect', $this->params()->fromQuery('redirect', false));
if ($this->getOptions()->getUseRedirectParameterIfPresent() && $redirect) {
return $this->redirect()->toUrl($redirect);
}
return $this->redirect()->toRoute($this->getOptions()->getLogoutRedirectRoute());
}
Upvotes: 1
Views: 3243
Reputation: 32660
Zend Framework 2 permits to store cookies in the HTTP request, so you can access theme in the headers using the Zend\Http\Header\SetCookie class.
Here is an example of setting and removing cookies with this mecanisme :
$cookie = new SetCookie('name', 'value');
$cookie->setExpires(time() + 365 * 60 * 60 * 24);
$headers= $this->getResponse()->getHeaders();
$headers->addHeader($cookie);
Remove a cookie by name : Before removing a cookie, you may check whether it is present in the request or not. This is a simple code to do that :
public function logoutAction()
{
//.....
$cookie= $this->getRequest()->getCookie();
if ($cookie->offsetExists('name')) {
$new_cookie= new SetCookie('name', '');//<---empty value and the same 'name'
$new_cookie->setExpires(-(time() + 365 * 60 * 60 * 24));
$headers->addHeader($new_cookie);
//.....
}
Upvotes: 1
Reputation: 3928
if you want to delete or create a cookie with zend framework 2 classes use the Zend\Http\Header\SetCookie
class and inject the instance into the response header
Create a cookie
// create a cookie
$cookie = new \Zend\Http\Header\SetCookie(
'testcookie',
'testData',
strtotime('+1 Year', time()), // 1 year lifetime
'/'
);
$this->getServiceManager()->get('Response')->getHeaders()->addHeader($cookie);
Delete a cookie
to delete a cookie over zend the same rule apply as delete a cookie over the php setcookie
function - just place the same cookie name with a negative lifetime
and inject it into the response header - just like create a cookie as above
// cookie löschen
$cookie = new \Zend\Http\Header\SetCookie(
'testcookie',
'',
strtotime('-1 Year', time()), // -1 year lifetime (negative from now)
'/'
);
$this->getServiceManager()->get('Response')->getHeaders()->addHeader($cookie);
Upvotes: 4