Skip to content
Advertisement

Generating a truly unique order id in PHP?

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement