Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding PHP session id

Tags:

php

session

I'm creating my own SessionHandler class implementing SessionHandlerInterface.

According to the manual I have to implement 5 methods: close(), destroy($session_id), gc($maxlifetime), open($save_path, $session_id), read($session_id) and write($session_id, $session_data).

The manual even offers a sample implementation and it's quite straight forward. The only problem I have is PHP session ids are always of the form:

hpuhqm4ppmdfaat5s1qmt5s397

but I'd like to change that for a more standarized uuidv5.

Since the $session_id is a parameter passed to all the methods, the only way I can think of doing that is by overriding the already generated session id using session_id($uuidv5) on the open($save_path, $session_id) method implementation, and that doesn't seem right.

Is there a cleaner way to do it?

like image 432
NotGaeL Avatar asked Jun 28 '26 17:06

NotGaeL


1 Answers

Is there a cleaner way to do it?

Change the underlying PHP session ID creation function. It uses hashes and by default is configurable (read more at session.hash_function PHP ini directive or session.save_handler), however if the existing configuration options don't match your uuidv5 needs, you need to add it to PHP's core code or via a PHP extension.


Further information as you moaned in the comment about that it would be "overkill" to write a PHP extension:

The userland PHP session save handler interface does not contain the core session save handlers s_create_sid method which is actually what you're looking for. This makes things hard in userland because that functionality is just not intended to be done in userland.

As session ID creation is subject to security and PHP core developers have already learned in the past that it was easy to do mistakes here, they even trust less others esp. those using the language, to easily change sessions ID generation here (my speculation as otherwise the function could have been exported to the userland session save handler).

However you can create UUIDs your own for being used with session IDs by then just hashing them in the configured manner as session IDs.

You could then keep the non-hashed value that is of the UUID form as a session variable.

If you actually need the UUID on the front-end, then I'd tend to say (if even this is possible to say in an SO answer) what you do is fishy and I would double check your motivations. Because technically only some ID is necessary, there should be no format requirements so I don't see any reason to not re-use the existing session IDs.

like image 152
hakre Avatar answered Jul 01 '26 08:07

hakre