Home » Php » php – Converting Session $data Into An Array?

php – Converting Session $data Into An Array?

Posted by: admin July 12, 2020 Leave a comment


In the write function for a session save handler $data is passed in a format like this:


Is there a way to convert that into the proper array which would be:

    'test' => array
        'foo' => 'bar'
    'session' => array
        'isLoggedIn' => true
        'clientId' => '12345'

I tried passing that into unserialize but I get an error of:

unserialize() [function.unserialize]: Error at offset 0 of 95 bytes

and it just return false.

How to&Answers:

Try session_decode


about the other answer. the description for session_decode is “session_decode() decodes the session data in data, setting variables stored in the session. ” that doesn’t sound like it does what you need.. and also it will always return bool after parsing a string.

on the other hand, if the string you provided as an example had a mistake, the space after “12345” (and it looks like a mistake because in front of it you can see that the following value should be a string with the length 5) you can use this function:

function unserialize_session_data( $serialized_string ) 
    $variables = array();
    $a = preg_split( "/(\w+)\|/", $serialized_string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE );

    for( $i = 0; $i<count($a); $i = $i+2 )
                $variables[$a[$i]] = unserialize( $a[$i+1] );
    return( $variables );