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?
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityIt 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.
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.
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
.
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.
create a user with uid=0 in users table because drupal always uses that uid for anonymous users