I've got a unique ID generator in my project and I've created this based on Scott's answer in here do you think it's possible for me to get duplicates with this?
$bytes = random_bytes(15);
$int = time() * random_int(100,999);
echo substr('OPT_' . bin2hex($bytes) . $int , 0, 50);
// Output: OPT_b2aad7ca373f363e2bcfbf5ab3e8ce553027068680
Just changed it with this if anyone is wondering,
public function generateUniqueKey(){
return strtoupper('OPT' . sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
) );
}
// Output: OPTEF49BAAB-A14C-484E-B475-EA8CD02DBF1F
Check out Rob's answer, he explained it perfectly.
My Answer:
It is highly unlikely that you will get collisions or duplicates with the second code snippet you provided. The use of `mt_rand()` and the UUID format ensures that the generated keys will be unique in most practical scenarios. However, it is not completely impossible to get duplicates due to the random nature of the generation process. If you require absolute uniqueness, you may want to consider storing generated keys in a database and checking for duplicates before using them.
Rate this post
5 of 5 based on 4796 votesComments