When I call session_start()
or session_regenerate_id()
, PHP generates what appears to be a random string for the session ID. What I want to know is, is it just a random sequence of characters, or is it like the uniqid()
function?
Because if it's just random characters, couldn't you theoretically run into a conflict? If User A logged in and then User B logged in and, though highly unlikely, User B generated the same session ID, then User B would end up accessing User A's account.
Even if PHP checks to see if a session with the same ID already exists and, if so, regenerates an ID again... I don't think I want a system that EVER produces the same ID twice, even after garbage collection -- maybe I want to store a table of them and check against them for possible hijacking or whatever.
If it isn't unique, how should I go about enforcing uniqueness? I'd rather implement it using PHP configuration than in every script I make. Nice thing about PHP sessions is not worrying about the technical details behind the scenes.
Community warning: this answer is only relevant for legacy PHP versions. For the current algorithm refer to the answer below
If you want to know how PHP generates a session ID by default check out the source code on Github. It is certainly not random and is based on a hash (default: md5) of these ingredients (see line 310 of code snippet):
If the OS has a random source available then strength of the generated ID for the purpose of being a session ID is high (/dev/urandom and other OS random sources are (usually) cryptographically secure PRNGs). If however it does not then it is satisfactory.
The goal with session identification generation is to:
This is achieved by PHP's approach to session generation.
You cannot absolutely guarantee uniqueness, but the probabilities are so low of hitting the same hash twice that it is, generally speaking, not worth worrying about.