session_decode

(PHP 4, PHP 5)

session_decode -- Decodes session data from a string

Description

bool session_decode ( string data )

session_decode() decodes the session data in data, setting variables stored in the session.

See also session_encode().


add a note add a note User Contributed Notes
leon dot pegg at gmail dot com
23-Aug-2006 11:14
i have found this to be a better way to restore session data while keeping your current session.

function decode_session($session_string){
   $current_session = session_encode();
   foreach ($_SESSION as $key => $value){
       unset($_SESSION[$key]);
   }
   session_decode($session_string);
   $restored_session = $_SESSION;
   foreach ($_SESSION as $key => $value){
       unset($_SESSION[$key]);
   }
   session_decode($current_session);
   return $restored_session;
}

enjoy
xueron at gmail dot com
16-Jul-2006 12:30
a perl reg:

$s = session_encoded_value;
%res = $s =~ /([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\|([^\|]*[\;\}])/g;
nero321 at zmail dot sk
27-Jan-2006 09:01
Another solution for decoding session string to "$_SESSION"-like array:

<?php

// returns decoded string as arrays of variables
//  or false on error (when session_decode returns false)
function DecodeSession($sess_string)
{
  
// save current session data
   //  and flush $_SESSION array
  
$old = $_SESSION;
  
$_SESSION = array();

  
// try to decode passed string
  
$ret = session_decode($sess_string);
   if (!
$ret) {
      
// if passed string is not session data,
       //  retrieve saved (old) session data
       //  and return false
      
$_SESSION = array();
      
$_SESSION = $old;

       return
false;
   }

  
// save decoded session data to sess_array
   //  and flush $_SESSION array
  
$sess_array = $_SESSION;
  
$_SESSION = array();

  
// restore old session data
  
$_SESSION = $old;

  
// return decoded session data
  
return $sess_array;
}

?>

Example of use:

<?php

$sarr
= DecodeSession($sess_str);
print_r($sarr);

?>

But I have not tested performance.
erwinmoller at xs4all dot nl
18-Oct-2005 10:25
The regExp-method describe earlier doesn't work under all conditions.

If I feed this:
voornaam|s:8:"Ai|;\'\"";achternaam|s:6:"werrwe";leeftijd|i:44;

I get this:
array(4) {
  ["voornaam"]=>
  bool(false)
  ["Ai"]=>
  bool(false)
  ["achternaam"]=>
  string(6) "werrwe"
  ["leeftijd"]=>
  int(44)
}

while I expected:
array(3) {
  ["voornaam"]=>
  string(8) "Ai|;\'\""
  ["achternaam"]=>
  string(6) "werrwe"
  ["leeftijd"]=>
  int(44)
}

I think the | is messing things up. :-/
bmorel at ssi dot fr
24-Aug-2005 03:54
Here is a function that returns decoded session data, that seems to work in every cases, even when strings contain reserved chars :

<?php
define
('PS_DELIMITER', '|');
define('PS_UNDEF_MARKER', '!');

function
session_real_decode($str)
{
  
$str = (string)$str;

  
$endptr = strlen($str);
  
$p = 0;

  
$serialized = '';
  
$items = 0;
  
$level = 0;

   while (
$p < $endptr) {
      
$q = $p;
       while (
$str[$q] != PS_DELIMITER)
           if (++
$q >= $endptr) break 2;

       if (
$str[$p] == PS_UNDEF_MARKER) {
          
$p++;
          
$has_value = false;
       } else {
          
$has_value = true;
       }
      
      
$name = substr($str, $p, $q - $p);
      
$q++;

      
$serialized .= 's:' . strlen($name) . ':"' . $name . '";';
      
       if (
$has_value) {
           for (;;) {
              
$p = $q;
               switch (
$str[$q]) {
                   case
'N': /* null */
                  
case 'b': /* boolean */
                  
case 'i': /* integer */
                  
case 'd': /* decimal */
                      
do $q++;
                       while ( (
$q < $endptr) && ($str[$q] != ';') );
                      
$q++;
                      
$serialized .= substr($str, $p, $q - $p);
                       if (
$level == 0) break 2;
                       break;
                   case
'R': /* reference  */
                      
$q+= 2;
                       for (
$id = ''; ($q < $endptr) && ($str[$q] != ';'); $q++) $id .= $str[$q];
                      
$q++;
                      
$serialized .= 'R:' . ($id + 1) . ';'; /* increment pointer because of outer array */
                      
if ($level == 0) break 2;
                       break;
                   case
's': /* string */
                      
$q+=2;
                       for (
$length=''; ($q < $endptr) && ($str[$q] != ':'); $q++) $length .= $str[$q];
                      
$q+=2;
                      
$q+= (int)$length + 2;
                      
$serialized .= substr($str, $p, $q - $p);
                       if (
$level == 0) break 2;
                       break;
                   case
'a': /* array */
                  
case 'O': /* object */
                      
do $q++;
                       while ( (
$q < $endptr) && ($str[$q] != '{') );
                      
$q++;
                      
$level++;
                      
$serialized .= substr($str, $p, $q - $p);
                       break;
                   case
'}': /* end of array|object */
                      
$q++;
                      
$serialized .= substr($str, $p, $q - $p);
                       if (--
$level == 0) break 2;
                       break;
                   default:
                       return
false;
               }
           }
       } else {
          
$serialized .= 'N;';
          
$q+= 2;
       }
      
$items++;
      
$p = $q;
   }
   return @
unserialize( 'a:' . $items . ':{' . $serialized . '}' );
}
?>

Please let met know if you find any bug.
brett at brettbrewer dot com
30-Jul-2005 02:25
I have made a minor change to fabrizio's (et all) version of the unserializesession function because it was choking on underscores in my variable names.  Here is the correct version which should account for ALL possible PHP variable names:

function unserializesession($data) {
   $vars=preg_split(
             '/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\|/',
             $data,-1,PREG_SPLIT_NO_EMPTY |               
             PREG_SPLIT_DELIM_CAPTURE
             );
   for($i=0; $vars[$i]; $i++) {
       $result[$vars[$i++]]=unserialize($vars[$i]);   
   }
   return $result;
}

Please note that I had to split the preg_split function call above into 4 lines due to the limitations of this forum. This version changes the regex used to find variable names so that it complies with the specs for  variable names as specified in the PHP manual at http://us3.php.net/manual/en/language.variables.php. I just took the regex directly from the PHP manual pages where they give the regex equivalent for a valid variable name as:

[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

Anyway, this seems to work great for me now, even on gigantic strings of encoded session data.
vesely at tana dot it
26-May-2005 06:25
When using this function to manage sessions, it is MUCH
better to have register_globals turned off. Then one can
examine the session content given its id.

<?php
   $fname
= session_save_path() . "/sess_" . $the_sid;
   if (
session_decode(file_get_contents($fname)))
   {
    
$vars = $_SESSION;
    
$_SESSION = array();

    
// examine $vars...
  
}
?>

Depending on PHP version, you may need to have a dummy
session started for the code above to work. I reset the
$_SESSION immediately in order to avoid writing the
dummy session: that's needed while testing the code!
fabrizio dot messina at gmail dot com
16-May-2005 09:40
this function _really_ split and decode session data:

function unserializesession($data) {
   $vars=preg_split('/([a-zA-Z0-9]+)\|/',$data,-1,PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
   for($i=0; $vars[$i]; $i++) {
       $result[$vars[$i++]]=unserialize($vars[$i]);     
   }
   return $result;
}

the difference from previously posted 'unserializesession' function is the regular expression inside function preg_split ('[a-zA-Z0-9]+' vs  '[a-z,A-Z]+' )
Sasha Rudenko
16-May-2005 03:25
Here is fixed function which was described here

function unserializesession($data) {
   $vars=preg_split('/([a-z_,A-Z_]+)\|/',$data,-1,PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
   for($i=0; $vars[$i]; $i++) {
       $result[$vars[$i++]]=unserialize($vars[$i]);
   }
   return $result;
}

I've just fix regexp, it doesn't handle names with _ (underline) sign.
But anyway, thanks for author, this function was very useful for me :)
luc at lucje dot nl
30-Sep-2004 04:39
This function decodes sessiondata:

function unserializesession($data) {
   $vars=preg_split('/([a-z,A-Z]+)\|/',$data,-1,PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
   for($i=0; $vars[$i]; $i++) {
       $result[$vars[$i++]]=unserialize($vars[$i]);
   }
   return $result;
}

(there was a line left from previous code in my earlier post!)
luc at lucje dot removethisforspamplease dot nl
30-Sep-2004 03:37
I also wanted to read stores PHP sessions.
Here's my code:

function unserializesession($data) {
   $vars=preg_split('/([a-z,A-Z]+)\|/',$data,-1,PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
   for($i=0; $vars[$i]; $i++) {
       $result[$vars[$i++]]=unserialize($vars[$i]);
   }
   return $result;
}

// this is just for the example
$session='/tmp/sess_'.$PHPSESSID;
// Why isn't there a sfile() function that returns a file as a string?
$h=fopen($session,'r');
$data=fread($h,filesize($h));
fclose($h);

$data=unserializesession($data);

Voila. It does the trick for me :-)
sco at postmaster dot co dot uk
04-Jun-2004 10:52
If you're trying to access your session data from outside the regular php session functions, you might want to use WDDX as your serializer, as opposed to the normal php serializer. When your data is serialized as XML, obviously it's easy to unserialize as you please.

WDDX seems to be a little slower, and the text string it creates is much bigger than that created by the normal php serializer, but it provides the functionality with minimal hassle.

Donal
forum at orthanc dot co dot nz
02-Apr-2004 04:26
Becarful using this if you are trying to switch out of an existing session rather than load one into a clean slate.

session_decode doesn't destroy the existing session data, it will over write it if there is a session variable of the same name, but if the names don't clash the existing session variables will hang around.

I have yet to find a better solution than

session_destroy()
session_start()
session_decode(....);

-----------------------------------------
To explain what I'm talking about

<?
   session_start
();
  
$a = 5;
  
session_register('a');
  
session_decode("<session that doesn't have a as a session variable>");
   print (
session_is_registered('a') ? $a : 'Not Registered' );
?>

The above code will print '5' as $a hasn't been destroyed or even unregistered by the session_decode
njail
13-Dec-2003 04:28
<?PHP
// Get Session Content
$varsess = Array('SESSION');
for (
$i = 0; $i < sizeof($varsess); $i++)
{
  if (
is_array(${"_{$varsess[$i]}"}))
  {
   foreach (${
"_{$varsess[$i]}"} as $var=>$val)
   {
   $
$var = $val;
  
// print "Var :".$var." -- Value :".$val."\n<br>";
  
}
  }
  unset(${
"_{$varsess[$i]}"});
}
?>
petej*shaman_ca
21-Aug-2003 04:44
Seems like there was a change in the behavior of this function somewhere between 4.1.2 and 4.3.3.  In 4.1.2 session_decode() didn't care whether the session was started, and would just decode the string into the _SESSION array.  In my 4.3.3 install, session_decode() wouldn't work unless I explicitly started the session with session_start().