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


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) {

  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.


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.

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

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
    Is there a way to tell Drupal, ALWAYS start a session for anonymous users?
    – user11312
    Commented Aug 8, 2013 at 6:14

After you saving data by following:

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

Need another function:


Due to the Session table needs a record with id=0, you could manually insert a record with id=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.