简体   繁体   中英

ZF2 setCookie not working

Since a while I am trying to figure out why setting a cookie through ZF2 seems to be so hard? Probably it isn't but I can't figure out why the cookie isn't set.

Code

use Zend\Http\Header\SetCookie;

    $response        = $this->getResponse()->getHeaders();
    $cookiesAccepted = new SetCookie('accepted_cookies', 1, strtotime('+1 Year', time()), '/');
    $cookieTest      = new SetCookie('test_key', 'test_value', strtotime('+1 Year', time()), '/');
    $response        ->addHeader($cookiesAccepted);
    $response        ->addHeader($cookieTest);

Refreshing page.

Testing output by dump

Debug::dump($_COOKIE);

Doesn't contain the 'accepted_cookies' or 'test_key' cookie.

You set cookies in the response object and dumping $_COOKIE will not immediately give you the cookies that you added to your response object.

When using cookies in Zend Framework 2 there is no need to interact with the super global directly. Check also the documentation for reference .

You could try like this in your next request object:

$accepted_cookies = $this->getRequest()->getHeaders()->get('Cookie')->accepted_cookies;
$test_key = $this->getRequest()->getHeaders()->get('Cookie')->test_key;

Check also this answer for more examples on cookie management.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM