Unserialize PHP session data

2019-06-24 04:19发布

问题:

I'm using CodeIgniter 3.x with database session driver and i want to access data cloumn that BLOB type. Here my blob data:

__ci_last_regenerate|i:1435420891;identity|s:13:"john@doe.com ";username|s:13:"johndoe";email|s:13:"john@doe.com ";user_id|s:1:"5";old_last_login|s:10:"1435412865";

I tried with unserialize($string) but didnt work!

unserialize(): Error at offset 0

How can i access blob data element? For ex: $user['email']

回答1:

There's no straight-forward way to do that ... You could use session_decode(), but it requires that you already have an active session, so that it can put the decoded data into $_SESSION.

I must tell you however, if you want to do that - you're doing it wrong. You should never access another user's session. If there's some data that's tied to a session that's not explicit to the user who owns the session, you should just add another field to the sessions table and save it in there.



回答2:

I got the solution here

So I have used session decode http://php.net/session_decode

session_decode('__ci_last_regenerate|i:1446535049;ci_UserID|s:1:"2";ci_UserName|s:24:"example@xyz.com";logged_in|b:1;');

So session decode stored all the encrypted data in normal php session.

Which I can access using:

echo $_SESSION['ci_UserID'];


回答3:

As Narf says there is no easy way to do this.

ykay;s solution presupposes that you are using the current built in session handler. That can be changed at any time by the application, and there are no guarantees that PHP will keep this format.

Your solution trashes the current session and replaces it with the stored data (but at least it will use the "current" serialization method).

The serialization function and the read/write operations for session_ functions can be overridden at runtime. As long as you read back data encoded using the same mechanism as you use for decoding your mechanism will work - but it is a bad approach for long term storage of data or for use in a context where you cannot guarantee consistency of the PHP installations reading the data.

The right way to fix the problem of reading session data outside of a user's session is to use the serialize/unserialize format:

ini_set("session.serialize_handler", 'php_serialize');

Then use unserialize() to read the data.