I need to generate a string using PHP, it need to be unique and need to be from 4 to 8 characters (the value of a variable).
I thought I can use crc32 hash but I can't decide how many characters, but sure it will be unique. In the other hand only create a "password generator" will generate duplicated string and checking the value in the table for each string will take a while.
How can I do that?
Maybe I can use that :
function unique_id(){ $better_token = md5(uniqid(rand(), true)); $unique_code = substr($better_token, 16); $uniqueid = $unique_code; return $uniqueid; } $id = unique_id();
Changing to :
function unique_id($l = 8){ $better_token = md5(uniqid(rand(), true)); $rem = strlen($better_token)-$l; $unique_code = substr($better_token, 0, -$rem); $uniqueid = $unique_code; return $uniqueid; } echo unique_id(4);
Do you think I'll get unique string each time for a goood while?
Using str_shuffle() Function: The str_shuffle() function is an inbuilt function in PHP and is used to randomly shuffle all the characters of a string passed to the function as a parameter.
The mt_rand() function is a drop-in replacement for the older rand(). It uses a random number generator with known characteristics using the » Mersenne Twister, which will produce random numbers four times faster than what the average libc rand() provides.
In short, I think you'll get a pretty good random value. There's always the chance of a collision but you've done everything you can to get a random value. uniqid() returns a random value based on the current time in microseconds. Specifying rand() (mt_rand() would be better) and the second argument as true to uniqid() should make the value even more unique. Hashing the value using md5() should also make it pretty unique as even a small difference in two random values generated should be magnified by the hashing function. idealmachine is correct in that a longer value is less likely to have a collision than a shorter one.
Your function could also be shorter since md5() will always return a 32 character long string. Try this:
function unique_id($l = 8) { return substr(md5(uniqid(mt_rand(), true)), 0, $l); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With