I'm trying to set a cookie using saveCookie(), and I'm puzzled by the UserSessionService's behaviour.

Instead of creating a plain old cookie, Craft actually creates a so-called state cookie, where the cookie name is prefixed with a hash key and the cookie value is also hashed.

Here's the code I'm running to set the cookie:

craft()->userSession->saveCookie('myAwesomeCookieName', $someAwesomeCookieData, 3600)

...and here's what the cookie looks like:

d9c79699028b2f1b123abbcd3e872e5dmyAwesomeCookieName : aa9de09d72cdbda2caac4551870e073d0f7307b3s

Reading over the source code, docs and other SE's on the subject, it's not apparent to me why Craft creates a state cookie instead of a regular (non-hashed) cookie.

Also, as far as I know, the only built-in method available to templates for retrieving a cookie is craft.request.getCookie – which is actually unable to read state cookies, so it all seems a bit odd.

I've currently implemented template variables for retrieving and reading the state cookie in my template (by wrapping the UserSessionService's getStateCookie and getStateCookieValue methods, respectively) but I'd love to know why the hashing happens in the first place, and if I can prevent it without an additional plugin (I'm aware of the LJ Cookies and the Cookie plugin).

1 Answer 1


craft()->userSesssion->saveCookie() is basically a fancy wrapper for craft()->request->getCookies()->add() that (as you've discovered) does some key and value based hashing to ensure that cookie data hasn't been tampered with between requests. Which is especially useful if, for example, cookies are used to maintain user session.

If that's not the behavior you're looking for, you can use PHP's setCookie method (like LJ Cookies and the Cookie plugin do) or you can interact with craft()->request->getCookies()->add() directly outside the context of the UserSesssion service.

  • Thanks Brad – the call to getCookies()->add() is a nice workaround. Commented Feb 24, 2016 at 19:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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