7

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.

4
  • What does the session save handler function look like? Commented Dec 9, 2011 at 13:53
  • Please properly serialize the string, don't use some custom function. Commented Dec 9, 2011 at 13:54
  • If this is the original string, then it's no wonder unserialize fails. It's malformed. Don't use malformed inputs. Commented Dec 9, 2011 at 14:02
  • How does the write function look like? Commented Dec 9, 2011 at 14:06

2 Answers 2

8

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 );
}
Sign up to request clarification or add additional context in comments.

4 Comments

I'm sure this won't work if there are pipe characters already in the session data.
Thank you so much for this. As for |s. I replace pipes before the session encode process or it fails to save properly. After decoding I replace the replacement.
You saved me friend (y)
After 5 hours of searching finally this one worked , thank you very much
3

Try session_decode

2 Comments

ok, well that does what I want for the write however is there a way to convert an array into a valid session string for the read (note that I am wanted to store the session as an array in mongodb to be able to better debug session data if I need to)
There is some good examples here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.