20

In my last project for Drupal 6, I did save the data using code similar to the following one:

$_SESSION['xxx'] = serialize($data);

In Drupal 7, it doesn't work.

How should I save the session data for the anonymous users, in Drupal 7?

5 Answers 5

4

It because drupal save session with key, this mean you should do something like

  $_SESSION['yourkey']['xxx'] = serialize($data);

You can try this.

function lists_session($key, $value = NULL) {
  global $user;

  static $storage;

  // If the user is anonymous, force a session start.
  if(!user->uid) {
    drupal_session_start();
  }

  if ($value) {
    $storage[$key] = $value;
    $_SESSION['lists'][$key] = $value;   // I use 'lists' in case some other module uses 'type' in $_SESSION
  }
  else if (empty($storage[$key]) && isset($_SESSION['lists'][$key])) {
    $storage[$key] = $_SESSION['lists'][$key];
  }
  return $storage[$key];
}

So, to save a variable in Session:

lists_session("xxx", serialize($data));

And to retrieve the value, just use:

$myVar = lists_session("xxx");

and aslo as MOLOT mentions sometimes session not stareted for anonymous users then you should drupal_session_start() manually.

2

According to the docs, that is all you should need to do.

Which means that there is either a bug, or your pages are being cached for anon users so the session data is not being read. I would check your caching settings in the first instance.

2
  • thanks. Perhaps this is a bug. but until I decided to use it session_api Jun 14, 2011 at 9:19
  • @vitaly.batonov can you elaborate on how you used session_api to resolve your issue?
    – lathomas64
    Feb 12, 2013 at 18:11
2

Drupal 7 sometimes does not automatically start sessions for anonymous users. To use sessions for them, you may need to force session started with drupal_session_start to be able to use $_SESSION.

1
  • 1
    Is there a way to tell Drupal, ALWAYS start a session for anonymous users?
    – user11312
    Aug 8, 2013 at 6:14
1

After you saving data by following:

$_SESSION['xxx'] = serialize($data);

Need another function:

drupal_session_start();

Due to the Session table needs a record with id=0, you could manually insert a record with id=0.

0

create a user with uid=0 in users table because drupal always uses that uid for anonymous users

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.