Nitin Nitin - 3 months ago 35
PHP Question

How easily will uniqid() with more entropy create a duplicate?

This might be an off topic question but i hope someone can answer this question.

Per how many nanoseconds, mili seconds or seconds does uniqid() with more entropy run the risk of creating a duplicate?

With reference to link below, uniqid will collide if two id are created in one milisecond. What about with more entropy?

(My goal is to use a small indexable alphanumeric string as document id at creation that can be created fast with minimum processor power without db interference.)

Answers here dont seem to provide any exact number:
How unique is uniqid?

Tgr Tgr

From the source code, more_entropy adds nine random decimal digits, so you can expect a collision after 37,000 or so calls. (For how a billion turned into 37,000, see the birthday attack.) That of course ignores the fact that these digits are not actually random but generated by an LCG, and the same LCG is probably used in other places in the code, so the actual chance of collision is probably higher (by how much exactly, I have no idea).

Also worth noting that uniqid does not actually guarantee microsecond resolution as some PHP implementations (Windows, specifically) don't have access to a microsecond-precision clock.

In short, if you need a unique ID for anything security-sensitive, or collisions are costly, avoid uniqid. Otherwise, using it with more_entropy is probably fine (although the common pattern is to use uniqid(mt_rand(), true) to add even more extra entropy).