Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Session $data Into An Array?

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

test|a:1:{s:3:"foo";s:3:"bar";}session|a:2:{s:10:"isLoggedIn";b:1;s:8:"clientId";s:5:"12345 ";}

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

array
(
    '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.

like image 719
ryanzec Avatar asked Dec 09 '11 13:12

ryanzec


People also ask

Can a session variable be an array?

The $_SESSION variable is also referred to as a session array, because you can declare a session “variable” to be an array.

Can I store an array in session?

Yes, PHP supports arrays as session variables.

How do you destroy a session?

Destroying a PHP Session A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If you want to destroy a single session variable then you can use unset() function to unset a session variable.


2 Answers

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 )
    {
        if(isset($a[$i+1]))
        {
                $variables[$a[$i]] = unserialize( $a[$i+1] );
        }
    }
    return( $variables );
}
like image 110
mishu Avatar answered Oct 17 '22 09:10

mishu


Try session_decode

like image 3
Markel Mairs Avatar answered Oct 17 '22 09:10

Markel Mairs