问题
I have a custom class extending PdoSessionStorage, but I don't know how to catch attributes from the session to save them as independent fields in the database.
Other posibility is to unserialize session data in sessionWrite($if, $data) method of my custom PdoSessionStorage Class. But I don't know how to unserialize the $data string to get only data I want to.
I tried this:
unserialize($data);
and this throw me the follow error:
Fatal error: Uncaught exception 'ErrorException' with message 'Notice: unserialize() [function.unserialize]: Error at offset 0 of 82 bytes in /myserver/myapp/src/app/myBundle/myCustomPdoSessionStorage.php line 220' in /myserver/myapp/vendor/symfony/src/Symfony/Component/HttpKernel/Debug/ErrorHandler.php:65 Stack trace: #0 [internal function]: Symfony\Component\HttpKernel\Debug\ErrorHandler->handle(8, 'unserialize() [...', '/Applications/M...', 220, Array) #1 /myserver/myapp/src/app/myBundle/myCustomPdoSessionStorage.php(220): unserialize('_symfony2|a:3:{...') #2 [internal function]: app/myBundle/myCustomPdoSessionStorage->sessionWrite('72b823b39d316dd...', '_symfony2|a:3:{...') #3 {main} thrown in /myserver/myapp/vendor/symfony/src/Symfony/Component/HttpKernel/Debug/ErrorHandler.php on line 65
Can anyone help me please?
回答1:
You are using the wrong function here. unserialize
is for serialized values, but not for sessions. Even those two are close to each other, they are different.
You might be looking for the session_decode function instead. Take care it unserializes into the $_SESSION
superglobal so you might want to wrap it:
function unserialize_session($data) {
$hasBuffer = isset($_SESSION);
$hasBuffer && $buffer = $_SESSION;
session_decode($data);
$session = $_SESSION;
$hasBuffer ? $_SESSION = $buffer : unset($_SESSION);
return $session;
}
The counterpart is session_encode which works similarly.
See also: How to unserialize session data in a custom handler
回答2:
I've found it!
My CustomPdoSessionStorage
Class extends the NativeSessionStorage
, which manages the $_SESSION
array (read, write, etc...).
So, from my class I can use $this->read('userId')
and store it on my DB.
So thanks a lot @hakre
来源:https://stackoverflow.com/questions/12914744/symfony2-how-to-save-a-session-attribute-as-a-custom-field-on-db-with-a-custom