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

Related Posts Related Websites
Help sharing and Flatter me ;)

Leave a Reply

Follow me