Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unserialize session data in a custom handler

Tags:

php

session

I have used sessionHandlerInterface to save the session in database. Everything works fine. but I want to get all the serialized data from the database like

SELECT data FROM session;

and want them to decode the data when i output those. i have tried using session_decode() which is manipulating $_SESSION array itself which is causing trouble. I just want to get the serialized data and return the decoded data.

This is the sample session data saved in database in data column

fb_422782977793963_code|s:216:"AQAVKa4Q8sOuioW75V9Ls-cDUEizgJDX5ZkRVLArDlroFvvhasdwKvbyzKEwiMVrN7nc5ghMaw0W67jQu5kt_sc_Edm9sABzB5PakdkUpXr52AViTOltPfPBQHM9T-JoGOQ4gasdbssC8Xt93NKFvdV7XRZ7ZYGZqIsu5SFpfFBHK_hNGDdRVbnbe_xUZVP9WI4h0jDy";fb_422782977793963_access_token|s:111:"AAAGAhasdaAKL7hAvXRv6FHUj1Tk24r7j4NqDwWWUzmXDZA2Igsb1pHjuP4jbBRNKfeYzutm0MFmgxuKPg1n0NEbvZAXM3bwoNZBiZCgZDZD";fb_422782977793963_user_id|s:15:"100004835469598";picture|s:61:"http://m-static.ak.fbcdn.net/rsrc.php/v2/yo/r/sdIqmHJn-SK.gif";

It works fine with normal session handling, it reads and writes session to database as it should.

I want to get all the data of active sessions. if i use SELECT data FROM sessions. it returns the above session data(encoded) i want to get the decoded data of it.

like image 695
varuog Avatar asked Oct 05 '22 16:10

varuog


1 Answers

The PHP serialize and unserialize functions can not be used to serialize and unserialize session data. Even if (by default - and only by default) the serialization might look similar, there is an important difference to those two functions that care about a single variable contents only:

Those [sessions] are a list of serialized values with their variable name.

(from: Serialized README)

So you would need to create your own a session_unserialize function that is able to decode the string (e.g. via session_decode) which is returned from your database. Take care that this needs everything in there, e.g. if the session contains serialized objects, the class definitions needs to be loaded.

An exemplary session_unserialize function could look like (adopted from: a session related answer):

function unserialize_session($data) {
    $hasBuffer = isset($_SESSION);
    $hasBuffer && $buffer = $_SESSION;
    session_decode($data);
    $session = $_SESSION;
    $hasBuffer ? $_SESSION = $buffer : unset($_SESSION);
    return $session;
}
like image 69
hakre Avatar answered Oct 10 '22 02:10

hakre