the web, mobile technology and location based services as I see it
Sometimes, an auto-generated number isn’t enough and what you really need is a unique identifier. Several people have different techniques for generating their unique identifiers. My favorite has been generating a random number and then hashing it through the md5 hash generator. Here’s an example I was once using:
<?php $unique_identifier = md5(rand(100000, 999999)); ?>
The problem with this is that I have given an allowance for only 899,999 possible values. I didn’t realize my error until I started getting mysql integrity check errors for a unique column that stored that value.
I reverted to using a more elegant solution:
<?php $unique_identifier = md5(uniqid(rand(), true)); ?>
The uniqid statement generates a globally unique identifier with a rand() prefix and using much more entropy (true).
Tim Akinbo's Weblog is the personal weblog of Tim Akinbo. Here he discusses issues relating to technology. Special interests include the web, mobile technology and location based services.
5 Responses to When unique isn’t really unique
@digitalcraft
December 14th, 2009 at 7:22 pm
Cool,
and Funny I'm only coming across that function, uinqid, for the first time
When I had to do unique in the past especially on ecommerce payment gateway's transaction reference (like interswitch) or user account activation process, I made use of the a combination of the time (UNIX TIME) and the user's IP to generate a dynamic unique number suffix which I then attached to another hard coded static unique number prefix…
I figured that the unix time and the user's IP and the application static reference will always return a unique combination…crazy eh, but so far it works.
I'll not claim is error proof as such I think the way to go (and lazy way at that) is uiqid, Thanks
austin_web_developer
December 17th, 2009 at 8:52 am
Any particular reason you didn't use a sha-1 hash?
Tim
December 17th, 2009 at 11:51 pm
As long as your unique identifier generator produces values that have a nearly zero probability of collisions, it really doesn't matter how you go about it so I'm happy with whatever works. May be you could show us some code
Looks like your first time here too. Welcome to my blog.
Tim
December 18th, 2009 at 12:09 am
No particular reason actually. Except you intend to store a very large data set, MD5 should do just about well. SHA-1 on the other hand reduces the probability of a collision further but will take more storage space.
Ahmad Mukoshy
February 8th, 2010 at 1:34 am
I've been using uniqid() for months now
#Lolz . I came across it on the php docs web site after hustling with my rand() md5 hash.
Cool stuv… I like this.