问题
I am referring to the function in the answer on PHP random string generator (I have removed the default $length param).
So this code uses that function but for some reason if you run this code you will see that the strings appear multiple times in the array! So how if this is truly random can I produce these results? Do I need to amend something to produce really random strings?
function generateRandomString($length) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
$i = 0;
while ($i < 5000){
$r = '';
$r = generateRandomString(8);
$arr[$r][$i] = $r;
$i++;
}
foreach ($arr as $key=>$rand){
if(count($rand) > 1){
echo "$key has ".count($rand).' results<br>';
}
}
Example results:
ASCn2Db1 has 2 results
4ceXoUgh has 2 results
fCdzjEAV has 2 results
QRkXxAUJ has 2 results
回答1:
Random is not unique. Throw a dice and you will get the same number multiple times..
回答2:
I provided an answer to the question you referenced in your question, but it's buried pretty far down under insecure answers and I'm not surprised everyone missed it.
The bug in your code that is causing so many duplicate values is here:
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
The problem is rand(). If you want a high quality PHP random string generator you need to use a better random number generator to power it. You have three good options here:
random_int()(PHP 7+ only)- random_compat, which exposes a compatible interface for
random_int()in PHP 5 projects (5.2+) - RandomLib (PHP 5.3.2+)
TL;DR use random_int(), never rand() or mt_rand().
Even with a secure random number generator, if you have short strings and a sufficiently large sample size, collisions are inevitable due to the birthday problem. Use longer strings and they will be far less frequent.
回答3:
I actually came across PHP: How to generate a random, unique, alphanumeric string? which seemed to answer my question. In short we use openssl_random_pseudo_bytes as a function. When run with 4 characters I got 1x collision but on 5 characters I didn't generate any. So for 8 I should be fine.
回答4:
I remember reading an article about this some time ago and I found it again.
In this article he makes a bitmap showing the random function running on Windows, not being totally random.
I would recommend you to use mt_rand() instead, you can read more about the mt_rand() here
来源:https://stackoverflow.com/questions/31984634/php-random-string-not-actually-random