How add cookie using Zend Framework 3?

1.7k views Asked by At

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?

1

There are 1 answers

2
edigu On BEST ANSWER

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