8

Is there any way to save a variable in the Craft session inside a controller?

I'm running a cron job and I need to store a variable as a session for every run to see if a condition matches.

11

Craft's HttpSessionService is a thin wrapper for PHP's global $_SESSION variable.

You can use:

craft()->httpSession->add($key, $value)

and:

craft()->httpSession->get($key)

to save and retrieve values from it.

  • Brad - How would you grab the key in a twig template? – Adam McCombs Nov 5 '14 at 4:28
  • We don't expose a HttpSessionVariable class where you'd be able to access that. Hit us up at support@buildwithcraft.com if you think you have a valid use-case where you think that'd be necessary from a template. – Brad Bell Nov 5 '14 at 5:29
  • Gotcha. I actually got what I needed from setFlash instead of httpSession. Thanks. – Adam McCombs Nov 5 '14 at 5:35
8

And for those needing this for Craft 3...

Set (previously add):

Craft::$app->getSession()->set($key, $value);

Get

Craft::$app->getSession()->get($key);

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.