PHP Session ID uniqueness (for use in a cookie)
I'm writing a user system where users will log in using Twitter's API, then I'll store the information in a database along with a few extra pieces that I have the user put in. I want the user to be able to come back after logging in and not have to log in again. I decided that I'd get all the relevant information about the user, save it to the database, then save the session ID and user ID to another table. Finally, I'd set a cookie on the user's computer containing the same session ID so that throughout their browsing they would stay logged in. Then if they closed the browser and revisited the site later, I would read that cookie, get the compare it with the sessions table, get the User ID, and reconstruct the session (updating the sessions table with the new session ID).
My question is, how random is the session ID? Is there a possibility that a user might get the same session ID that a user that hasn't visited the site in a week (so the cookie would still be active) had assigned to them? If this happens, then the server might mistake the new user for the old one. I really would like to avoid using the IP address because people might visit the site from a mobile browser where the IP can change at any time.
Any ideas on this? I just want to ensure that user A and user B, separated by any amount of time, won开发者_StackOverflow社区't get the same session ID.
Append current time in microsecond to the unique id...
session_id() + microtime();
So not only would the session_ids have to be the same, it would have to happen on the same microsecond... making the vanishingly unlikely just about impossible. The only way to guarantee it 100% is to check this random value against all existing session ids and re-roll it if it already exists.
Although the probability of having two active sessions with identical identifiers at the same time is vanishingly low (depending on the hash function), you could add an additional (pseudo-) unique value to that session ID to get a value with both characteristics.
You could use uniqid
that fulfills the latter:
uniqid(session_id(), true)
uniqid
’s value is based on microtime
with an additional pseudo-random number from lcg_value
and an additional source for more entropy that all together guarantees unique values.
The PHP Session ID is an MD5 hash, which makes it 128 bits in length. That's something like 340,000,000,000,000,000,000,000,000,000,000,000,000 different possibilities. The odds of two people getting the same one are pretty remote.
If you want to guarantee uniqueness, put something in their cookie based on sequential numbers.
精彩评论