Symfony2: How to save a session attribute as a custom field in a database using custom PdoSessionStorage?

I have a custom class extending PdoSessionStorage, but I don’t know how to catch attributes from the session in order to save them as independent fields in the database.

Another possibility is to not serialize session data in the sessionWrite ($ if, $ data) method of my custom PdoSessionStorage class. But I don’t know how not to initialize the $ data string to get only the data I want.

I tried this:

unserialize($data); 

and this will throw an error:

Fatal error: throw an "ErrorException" exception with the message "Note: unserialize () [function.unserialize]: error with an offset of 0 out 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} is thrown in /myserver/myapp/vendor/symfony/src/Symfony/Component/HttpKernel/Debug/ErrorHandler.php on page oce 65

Can anybody help me?

+4
source share
2 answers

I found him!

My CustomPdoSessionStorage Class extends NativeSessionStorage , which manages the $_SESSION (read, write, etc.).

So, from my class, I can use $this->read('userId') and store it in my DB.

So thank you very much @hakre

+1
source

Here you are using the wrong function. unserialize is for serialized values, but not for sessions. Even those two are close to each other, they are different.

Instead, you can search for session_decode . Make sure that it does not serialize in the $_SESSION , so you can wrap it:

 function unserialize_session($data) { $hasBuffer = isset($_SESSION); $hasBuffer && $buffer = $_SESSION; session_decode($data); $session = $_SESSION; $hasBuffer ? $_SESSION = $buffer : unset($_SESSION); return $session; } 

This copy of session_encode works similarly.

See also: How to Non-Serialize Session Data in a Custom Handler

+2
source

Source: https://habr.com/ru/post/1440041/


All Articles