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


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


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.

  • 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 Jun 4 '12 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 Jun 4 '12 at 12:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.