I want to save some session data. I use this to set session variable:

$_SESSION['my_variable'] = XYZ;

This works for logged-in user but not for anonymous user. For anonymous user, the $_SESSION item I set does not seem to persist.

How can I make my session variable stick around for anonymous user?

Comments

mattyoung’s picture

Ok, it's because of form cache. For anonymous user, my form constructor is not called the second time so no code is executed. $_SESSION is working fine.

So I have a different problem: how to work with cached form for anonymous user?

Say I have three checkboxes initially:

[ ] A
[ ] B
[ ] C

Then the anonymous user check the boxes and submit:

[x] A
[x] B
[x] C

If I go back to the form, I'll get the cached version with all the checkboxes cleared instead of all checked:

[ ] A
[ ] B
[ ] C

really what I want is this:

[x] A
[x] B
[x] C

Anonymous’s picture

with drupal 6 FAPI I got it to work like this

$form['a_b_c'] = array(
'#type' => 'checkboxes',
...
'#default_value'=> isset($form_state['storage']['a_b_c']) ? $form_state['storage']['a_b_c'] : array(),
);

mattyoung’s picture

The problem is with anonymous user and form value. Not how to set '#default_value'. As I said in the previous message, anonymous user is served with the cached version of the page so the form constructor is not call when they visit the page again. You can verify this by:

  1. turn on page caching
  2. make a page with a form that anonymous user can view and submit
  3. browse the page as anonymous user
  4. Put some value in the form and submit, the page will come back with the set values
  5. now refresh the page and the values are gone, whatever the form values for that anonymous user are forgotten

The comment module solve this problem with cookie and javascript and that's what I ended up doing.

mwskuzzy’s picture

The cache_exclude module allows you to specify specific nodes/pages which will not be cached and all session variables for those specified pages will be saved for both anonymous and authenticated users.

Hope this helps.
Rosso

mdlamar’s picture

I see a solution in this thread. Check it out.

http://drupal.org/node/403168

Cheers,
Milo