zend-framework2zfcuser

remove cookies from Zf2 Controller


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

Solution

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