2

This is how the user session is stored in Drupal 7:

batches|a:46:{i:13;b:1;i:14;b:1;i:15;b:1;i:16;b:1;i:17;b:1;i:18;b:1;i:19;b:1;i:20;b:1;i:21;b:1;i:22;b:1;i:23;b:1;i:24;b:1;i:25;b:1;i:26;b:1;i:27;b:1;i:28;b:1;i:29;b:1;i:30;b:1;i:31;b:1;i:32;b:1;i:33;b:1;i:34;b:1;i:35;b:1;i:36;b:1;i:37;b:1;i:38;b:1;i:39;b:1;i:40;b:1;i:41;b:1;i:42;b:1;i:43;b:1;i:44;b:1;i:45;b:1;i:46;b:1;i:47;b:1;i:48;b:1;i:49;b:1;i:50;b:1;i:51;b:1;i:52;b:1;i:53;b:1;i:54;b:1;i:55;b:1;i:56;b:1;i:57;b:1;i:58;b:1;}updates_remaining|a:0:{}dblog_overview_filter|a:2:{s:4:"type";a:0:{}s:8:"severity";a:1:{i:2;s:1:"2";}}

How do I convert it to a PHP array? unserialize() does not work.

1 Answer 1

3

That's a session encoded string (different from a PHP serialized string). There's no built-in way to decode it directly into a variable, so you'll have to use a custom function.

Here's one nicked from the docs page for session_decode().

function unserializesession( $data ) {
  if(strlen( $data) == 0) {
    return array();
  }

  // match all the session keys and offsets
  preg_match_all('/(^|;|\})([a-zA-Z0-9_]+)\|/i', $data, $matchesarray, PREG_OFFSET_CAPTURE);

  $returnArray = array();

  $lastOffset = null;
  $currentKey = '';
  foreach ( $matchesarray[2] as $value ) {
    $offset = $value[1];
    if(!is_null( $lastOffset)) {
      $valueText = substr($data, $lastOffset, $offset - $lastOffset );
      $returnArray[$currentKey] = unserialize($valueText);
    }
    $currentKey = $value[0];

    $lastOffset = $offset + strlen( $currentKey )+1;
  }

  $valueText = substr($data, $lastOffset );
  $returnArray[$currentKey] = unserialize($valueText);

  return $returnArray;
}

It works well with the example in your question, returning a nested array of values.

2
  • 1
    Hint: If you session data doesn't look like that, but more like base64 (alphanumeric glibberish), it is probably because you have the suhohin php extension enabled and configured to do session data encryption. And unless you know a lot about encryption and C, you can probably give up that data, the encryption key is dynamic based on the installation path and configurably even the user agent. I haven't been able to decrypt that information on a site where we had that problem.
    – Berdir
    Commented Jun 4, 2012 at 12:34
  • 1
    Conclusion: If you have data that is assigned to anonoymous users, don't throw it in $_SESSION but instead add it in a table and reference the session id (see drupal.org/project/session_api). Then it will be much easier to do something with that information at a later point.
    – Berdir
    Commented Jun 4, 2012 at 12:35

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.