I am trying to create the PHP $_SESSION equivalent in Craft CMS using Twig. I have searched very long and I can't find how you can create sessions in Twig.

In previous posts I have found that I should edit some PHP controllers for this to work but I have just started using Craft and Twig and have no idea what controllers to edit to let this work.

So if someone has an solution to this can you please explain it like you are explaining it to a 2 year old kid?

Thanks in advance!


Go to https://pluginfactory.io/ to generate a boilerplate Craft plugin.

  • API Version: Craft CMS version 2.5.x
  • PluginName: Twig Session
  • Description: Anything
  • Version: 1.0.0
  • Plugin Author: Anything
  • Author URL: Anything
  • Github Name: Blank
  • Uncheck: Tweet it out
  • Check: Variables
  • Click: Build Plugin

Download twigsession.zip and unzip it. Place the unzipped twigsession folder in your craft/plugins folder. Open craft/plugins/twigsession/variables/TwigSessionVariable.php and change:

public function exampleVariable($optional = null)
    return "And away we go to the Twig template...";


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

And add a new:

public function get($key)
    return craft()->httpSession->get($key)

Go to Settings->Plugins in the control panel. Install the "Twig Session" plugin.

From your front end templates, you can now use craft.twigSession.add('foo', 'bar') and craft.twigSession.get('foo').

  • +1 You basically just wrote this plugin.
    – Lindsey D
    Sep 9 '16 at 20:45
  • wow thanks a lot!
    – Branko
    Sep 13 '16 at 7:42

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.