Generating a unique Key
I need a unique Key to use to identify an object.
I use this in PHP:
$key = md5(uniqid(mt_rand(), false));
This should be unique, but can you believe that will never be repeated? I don’t trust it…
Just check it in your DB just in case:
function generateKey(){//Generate a unique key do{ $key = md5(uniqid(mt_rand(), false)); } while(validateKeyn($key)); return $key; } function validateKey($key){//check the DB $query = "SELECT theKey FROM Table WHERE theKey ='".trim($key)."' LIMIT 1"; $result=mysql_query($query); if (mysql_num_rows($result)) return true; else return false; }
Also imagine you need to create a kind of serial number, you can use this interesting function from corner:
// Generate Guid function NewGuid() { $s = strtoupper(md5(uniqid(rand(),true))); $guidText = substr($s,0,8) . '-' . substr($s,8,4) . '-' . substr($s,12,4). '-' . substr($s,16,4). '-' . substr($s,20); return $guidText; } // End Generate Guid $Guid = NewGuid();
This will return something like: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX style unique id, (8 letters)-(4 letters)-(4 letters)-(4 letters)-(12 letters)
Update: I just found that is “a unique” instead of “an unique” xD
Actually, according to that website, it’s ‘a unique’ :D.
In anycase, thanks for that post. As I understande it, uniqid is based on the date, so should offer a unique ID.
Something that uses the php microsecond like:
$id=md5(date(ru).mt_rand());
Should generate a unique ID, unless someone registers in the same microsecond (almost improbable) and mt_rand coincidentally is the same (much more probable).
I love your blog! Thanks for the great insight.
thanks!!