Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

Save user / temporary data on $_SESSION

By editor , 18 November, 2015
Question

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

Store data on session.

Example:

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

 

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');


 

Tags

  • Drupal 8
  • Code
  • User
  • Add new comment

Comments1

Plain text

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

Ojcze Nasz (not verified)

10 years 7 months ago

Works :)

In my project I've also added :

$session->delete('mymodule');

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

Great stuff, Drupal 8 rulez !

  • Reply

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer