Save user / temporary data on $_SESSION | Drupal 8

Save user / temporary data on $_SESSION

Submitted by editor on Wed, 11/18/2015 - 12:44

How to set and get data using $_SESSION on Drupal 8?

Store data on session.


$session = new \Symfony\Component\HttpFoundation\Session\Session();
$session->set('var_name', $session->get('var_name',0) + 1);


This is similar to :
$_SESSION['mymodule']['test'] = "Just for Test";  
$data = $_SESSION['mymodule']['test'];


To save data on configuration database.

To set data:
    $session = \Drupal::service('user.private_tempstore')->get('mymodule');
    $session->set('test', "Just for Test");

To get data:
    $session = \Drupal::service('user.private_tempstore')->get('mymodule');
    $data = $session->get('test');



Ojcze Nasz (not verified)

Thu, 04/07/2016 - 16:01

In my project I've also added :


to destroy that data after being retrieved to prevent being reused.

Great stuff, Drupal 8 rulez !

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.