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.

2 Answers 2

12

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.

3
  • Brad - How would you grab the key in a twig template? Commented Nov 5, 2014 at 4:28
  • We don't expose a HttpSessionVariable class where you'd be able to access that. Hit us up at [email protected] if you think you have a valid use-case where you think that'd be necessary from a template.
    – Brad Bell
    Commented Nov 5, 2014 at 5:29
  • Gotcha. I actually got what I needed from setFlash instead of httpSession. Thanks. Commented Nov 5, 2014 at 5:35
13

And for those needing this for Craft 3...

Set (previously called 'add'):

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

Get

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

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.