0

I'm trying to start a session for anonymous users (using Drupal 8.2.2), so I can use the private temp store, but the session does not persist. This is what happens with anon users:

// $session is the Drupal `session` service (Symfony Session component)
$session->start();
var_dump($session->isStarted()); // always FALSE
var_dump($session->getId()); // changes from request to request

With an authenticated user, isStarted() returns TRUE, and the session ID remains the same.

How can I start a session for anonymous users that will enable private temp store?

2
  • The reason the ID changes is simple. Drupal always starts a session, you don't have to do that, but it doesn't persist the session unless there is actually data that needs to be persisted. So until you do, you have a new session ID on every request.
    – Berdir
    Commented Dec 7, 2016 at 19:00
  • I was trying to persist data through the PrivateTempStore, but the session wasn't persisted for anon users. Setting the session data directly as 4k4 suggested worked.
    – Tim
    Commented Dec 8, 2016 at 8:01

1 Answer 1

2

It's not necessary to use a private temp store for anonymous user if you don't have a lot of data. And for anonymous it's not so easy to implement this.

To store data for anonymous users you can simply use the php $_SESSION variable.

$_SESSION['my_module']['data'] = 'My Data';

Drupal will take care of starting and saving the session.

Edit:

OK, to make this official, you should use the request object. See https://www.drupal.org/node/2380327. But drupal core and contrib code still uses the $_SESSION variable. This should be OK at least for D8.

In both cases you have not to handle the session yourself. Drupal will load the session if there is one present when it begins with the request. And drupal will start a new session and saves it at the end of the request, if there is newly added session data.

2
  • Works, but doesn't somehow feel "official". :)
    – Tim
    Commented Dec 7, 2016 at 10:15
  • 1
    OK, I've added the official version.
    – 4uk4
    Commented Dec 7, 2016 at 10:35

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.