Stashing stuff in $_SESSION in your form's _submit handler in Drupal

Today I was trying to figure out why in the name of all that good in the world why I couldn't use $_SESSION in my form's _submit handler.

As it turns out, I actually CAN put stuff into $_SESSION, it's just that when you want to pull something OUT of $_SESSION later, that's not where it is.

Instead, it's on the $user object in Drupal, in $user->session. After some studying, it seems this is a pipe-delimited and semi-colon delimited list of variable names and their serialized values.

Here's a function to pull stuff off of $user->session:

<?php
/**
* private function to return whether or not the person wants auto-play
*
* @return
*   either "yes" or "no" or "" (empty string)
*   yes - if the person has set their session var to autoplay
*   no - if they have set their session var to NOT autoplay
*   (empty string) - if they have not set their session var
*/
function _get_autoplay_from_session() {
 
$swftools_user_autoplay = '';
  global
$user;
 
 
$the_session = $user->session;
 
$the_session = explode('|', $the_session);
 
$swftools_user_autoplay = '';
  for (
$i = 0; $i < count($the_session); $i+=2) {
    if (
$the_session[$i] == 'swftools_user_autoplay') {
     
$swftools_user_autoplay = unserialize($the_session[++$i]);
      break;
    }
  }
 
  return
$swftools_user_autoplay;
}
?>

You'll notice that this pulls out a particular variable, but it can be easily modified and/or genericized to have you pass in the variable you're looking for.

You may want to check out

You may want to check out these handy functions:

http://api.drupal.org/api/drupal/includes--session.inc/6

Especially sess_write() and sess_read(); they do what you need.

As it turns out, I actually

As it turns out, I actually CAN put stuff into $_SESSION, it's just that when you want to pull something OUT of $_SESSION later, that's not where it is.

Drupal is very good content

Drupal is very good content management system. All my websites are done with drupal !

Great blog. This post is very

Great blog. This post is very nice. Drupal is very good content management system.Thanks for sharing this post.