1
votes

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());
    }
2
What's the problem you encountred ? And what's your question ?blackbishop
i need some code to delete stored cookies by name somthing like remove('cookies_names'); or any other code from my LogoutAction method in the controllerKhalid.sgh
Did you try with Zend\Http\Header\SetCookie ?blackbishop

2 Answers

4
votes

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

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

//.....
}

Hope this helps.