Forum Moderators: coopster
Yes, it should be.
>> What are the chances of landing on a number twice?
Depends on the range of numbers you are selecting from :)
So if you md5 the result of uniqid then you take something with an incredibly high chance (as nothing is guaranteed) of being unique and hash it with something that is known to have collisions...so you have actually just decreased the chance of a unique number.
From the user comments section of the manual.
<?php
$better_token = uniqid(md5(rand()), true);
?>
substr(md5(uniqid(rand(),1)), rand(0,21), 10);
If you want to be really random then you could use something like:
function randomizer($length) { // $length = 9 if you want a 32 character string
$str = '';
$prefix = '';
for ($i=0;$i<$length;$i++) {
$prefix.= chr(mt_rand(33,126)); // viable ascii characters, could use 32 if you want to include a space
}
$str.= uniqid($prefix, true);
return $str;
}
By calling substr against the result it would be possible to reduce the length of the 'random' string, however this will reduce the effectiveness of the randomness.
As if you have to pick a single random letter from the ascii alphabet then you have 93 options. If you have to pick a 2 character string then you square the number of options. So the longer the string the harder it will be to guess that string, as there are many more options.
However you probably noticed that the heart of the function is uniqid, so it would be a lot easier just not to bother with a random prefix and allow uniqid to do the work of producing a 13 or 23 character string.
You can then add a prefix if you choose to, maybe for the reason noted in the manual.
As unless you are trying to use this function as part of an encryption algorithm then randomness if not really a problem.
I assume that you are not just using an ID for loggin in. I assume that a password of some description is also required. So if I know an ID I still have to know the password. Uniqid is just a much better option for ID's than an auto increment number, however a 'random' ID is not enough security to verify the identity of a user, you need something else, like a password.