Create random string, check if it exists, if it does create a new one

Ben*_*ock 3 php recursion

I want to generate a random string of about 5 characters long. I can create it ok, but I'm having trouble checking if it exists in an array (or database in real situation) and creating a new one if it does.

I use a function like this to generate the string:

function rand_string(){
    return substr(md5(microtime()), 0, 5);
}
Run Code Online (Sandbox Code Playgroud)

But them I'm lost.

  • I need to check if it exists already.
  • If it does, make a new one
  • And repeat

Jac*_*kin 6

试试这个:

function rand_string(){
    $str = substr(md5(microtime()), 0, 5);
    if(exists_in_db($str)) $str = rand_string();
    return $str;
}
Run Code Online (Sandbox Code Playgroud)

  • 有关冲突很可能的更多信息,请参阅http://en.wikipedia.org/wiki/Birthday_attack对于5个字符,您有50%的可能性,每个新的ID都会发生冲突,只有大约1000行数据库.在大约2000行的情况下,75%的碰撞几率并不多...... (2认同)

jco*_*der 5

只是一个警告,如果您使用它来生成一个唯一的字符串,一旦您确定它未被使用就将其添加到数据库中,那么这在并发环境中是不安全的。

在检查它不在数据库中的间隔内,稍后在另一个线程上添加包含它的记录可以做同样的事情......

如果您以这种方式使用它,可能最安全的方法是确保包含字符串的字段对其具有唯一约束并尝试添加它。如果您成功添加了它,那么您就知道它是独一无二的,如果您没有添加,那么它就不是。这在多线程环境中是安全的。

如果您只是检查静态字符串列表并且不打算将生成的字符串添加到数据库中,请忽略此帖子:P