Custom serialize_handler for custom php SessionHandler (DB storage)

In the process of using third-party session management (django) in php, I need to have custom serialization functions in order to correctly encode / decode it, to match the storage of django session data. Currently it seems that setting ini session.serialize_handler can be either php or wddx.

Is there a way to configure a custom serialize_handler as a class?

I would like to have something like this:

class CustomSessionSerializer { public static function serialize($data){ // Serializes raw data } public static function unserialize($sdata){ // Deserializes serialized data } } 

and use it in my custom SessionHandler.

igbinary project on github seems to add a custom serialize_handler as a php extension. I am curious if custom serialization cannot happen anywhere other than extension C.

+6
source share
3 answers

I ran into this problem and there is a solution for this.

The idea is that although you can easily change session.serializer_handler from PHP, you can clear the contents of $ _SESSION before starting the serializer.
Using a class to administer a session (for example, Zend \ Session \ SessionManager) in which the register_shutdown_function function is register_shutdown_function , which returns a save_handler copy of the contents of $ _SESSION , and then $ _SESSION empty.

So, the serializer works, but on an empty line, and custom serialization is done on your custom save_handler .

+2
source

You can use session_set_save_handler () to use your own session processing functions

In PHP 5.4, you can use SessionHandlerInterface .

By default, you will get already serialized data, so you will have to uneserialize it and use your own serialization procedures.

0
source

It may seem like it works, but it does what you need. Serialization is applied when your custom session handler receives $_SESSION superglobal, and you need to return it from the read handler as serialized. But you can store the session like any serialization or format or whatever.

Example

 class SessionHandler { public function __construct() { session_set_save_handler( array($this, 'open') ,array($this, 'close') ,array($this, 'read') ,array($this, 'write') ,array($this, 'destroy') ,array($this, 'gc') ); } public function open($savePath, $sessionName) { return true; } public function close() { return true; } public function read($id) { $data = CustomStorage::fetchSessionData($id); return serialize( CustomSerialization::unserialize($data); ); } public function write($id, $serializedData) { CustomStorage::writeSessionData( $id ,CustomSerialization::serialize(unserialize($serializedData)) ); return true; } //gc and destroy } 

Although this is not very pretty and with little overhead, you only need to control the serialization during storage, so it should do the trick.

Hope this helps!

0
source

All Articles