4

Following up on this question: Prescribed way to set cookies (from plugin or Twig) the following works great.

craft()->userSession->saveCookie($cookieName, $data, $duration);

I can see Location being set as my cookie in the Application Log but when I try to use {{ craft.request.getCookie('location') }} It returns blank.

What am I missing here?

Edit - Upon closer inspection it doesn't look like saveCookie is working correctly either. I see location from when I was using setFlash but I need the data to persist even if the page is reloaded.

4

You should probably be using something like this:

    $cookie = new HttpCookie($name, $value);
    $cookie->expire = time() + 3600;

    craft()->request->getCookies()->add($cookie->name, $cookie);

Setting whatever properties you want on HttpCookie.

Using UserSessionService->saveCookie is meant mainly for Craft's session identity cookie, so it has some security checks it goes through saving the cookie that craft.request.getCookie('location') is probably failing.

| improve this answer | |
  • 1
    Dear Brad - you're my hero. – Adam McCombs Nov 5 '14 at 19:15
  • Does this work in Craft 3? I'm setting a cookie using js-cookie and it's not returning anything in my twig templates. – biko Aug 8 '18 at 5:42
  • I went for a plugin instead and it's working nicely in Craft 3: github.com/nystudio107/cookies – biko Aug 8 '18 at 6:08
2

I wrote a plugin similar to lj_cookies that accomplishes this for both regular and craft secure cookies: Cookies

https://github.com/nystudio107/cookies

...enjoy.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.