Search code examples
phpcookieszend-framework3zf3

How add cookie using Zend Framework 3?


I need send a cookie to browser using Zend Framework 3.

My code follows below, but it doesn't work:

$cookie = new Zend\Http\Header\SetCookie('CookieKey', $val, $time, '/', '');
$response->getHeaders()->addHeader($cookie);

How is the right way to put cookies to work?


Solution

  • You're setting the cookie path to '/' and using an empty domain '' when creating a new SetCookie instance. Passing an empty string as domain may lead problems.

    The second detail is you need to pass a time in the future as third (expires) argument. Are you sure you have given a time in the future?

    Take a look following example, it sets a cookie on my ZF3 app without any problems:

    namespace MyApp\Action;
    
    use Zend\Http\Header\SetCookie; 
    
    public function indexAction()
    {
        $cookie = new SetCookie('bar', 'baz', time()+7200);
        $this->getResponse()->getHeaders()->addHeader($cookie);
        return new ViewModel();
    }