dav
dav

Reputation: 9267

can session id be the same for different sessions at the same moment of time php

I use session id and microtime() to generate unique strings(I am aware of uuid, but need to do in this way): is it possible to have duplicates in here ? Mainly, is there a possibility that 2 or more session ids can match at the same moment of time - calculated in microseconds ? considering that the website's traffic is a few million during the day (if it matters of course).

Thanks

Upvotes: 0

Views: 3676

Answers (2)

brianmearns
brianmearns

Reputation: 9967

If session IDs were duplicated at the same time, it would mean that two (or more) of your visitors are sharing a session. Remember that the session ID is the only way PHP has to decide which session to load, so having duplicate IDs defeats the purpose of sessions and is a huge security problem. I'm not saying it's not possible, you would need to know exactly how PHP generates session IDs in order to know that. But it's most likely highly improbable.

The manual only seems to briefly touch on this. While it's not exactly a hard guarantee, it does state here:

A visitor accessing your web site is assigned a unique id, the so-called session id

Note that you can specify you own session IDs by passing an argument to the session_id function, so you could come up with your own session ID and use some method to ensure that it is unique. For instance, you could store a pool of recently used session IDs, or use a one-to-one function of a counter which you can manually increment every time you create a new session.

As a final note, I don't think microtime() is guaranteed to be accurate to one microsecond, meaning it may not actually change every microsecond. To be safe, I would assume that it only changes once per second, and then make sure that no session ID is reused within one second. Using either of the methods described above, this is fairly easy. If you're keeping a pool of recent session IDs, just make sure they are not removed from the pool sooner than one second after they were last used. If you're using a counter, just make sure it does not reset or roll over within one second. Of course, in either case, you also want to make sure a session ID isn't reused if another session is still using it, but that's not strictly related to your question.

Upvotes: 0

verv
verv

Reputation: 686

The session ID is extremely unlikely to have a collision. Adding microtime should make it safe. If you want to be really safe and also protect yourself from having the strings be guessable, you could include the user's IP address as well as a hard-coded private key in your code, and then do a quick md5 hash on the whole thing. Use the hash as your string. Using uniqid() might be better but, sounds like you can't do that for some reason.

Upvotes: 1

Related Questions