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?

Silas
  • 33
  • 8

1 Answers1

1

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();
}
edigu
  • 9,878
  • 5
  • 57
  • 80
  • I debugged the code today and I found the problem, the headers had already be sent. ZF3 is showing a "deprecated" warning, forcing the headers to be sent. I resolved the deprecated issues and the cookies are working now, but what can I do to buffering the content to not send headers with warnings messages? – Silas Dec 28 '16 at 15:28
  • You have to eliminate deprecation notices. Just dig carefully the messages and fix the reason. You don't need use output buffering. When deprecation messages are gone, session related problems probably will disappear. – edigu Dec 29 '16 at 18:57