Generating a truly unique order id in PHP?

coderama picture coderama · Sep 8, 2009 · Viewed 19.4k times · Source

I'm considering using this: http://phpgoogle.blogspot.com/2007/08/four-ways-to-generate-unique-id-by-php.html

My idea is to use a mixture between 2 and 3. But my question is that, although the chances are small, is there still a chance that two orders with the same order # can be generated if I substring the result to be only 5 characters long? What about 3? 2? 1? Surely if it's 1, there is a 1/(26 + 10) chance that the id will be the same?

Answer

Aistina picture Aistina · Sep 8, 2009

Assuming your users are authenticated and have a user id:

$unique_id = time() . mt_rand() . $userid;

If the same user requests this page a second time in the same second, there will still be a chance of 1 in mt_getrandmax(), which on my machine returns 2147483647. You can probably live with that?

If your users are not authenticated, you can use a hash of their IP address instead if you'd like.