Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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);
}

But them I'm lost.

  • I need to check if it exists already.
  • If it does, make a new one
  • And repeat
like image 559
Ben Shelock Avatar asked Dec 09 '22 14:12

Ben Shelock


2 Answers

Try this:

function rand_string(){
    $str = substr(md5(microtime()), 0, 5);
    if(exists_in_db($str)) $str = rand_string();
    return $str;
}
like image 82
Jacob Relkin Avatar answered Feb 23 '23 00:02

Jacob Relkin


Just a warning that if you are using this to generate a unique string by adding it to the database once you've determined it's not been used then this is not safe in a concurrent environment.

In the interval between you checking it's not in the database, and adding a record containing it later on another thread could do the same...

If you are using it this way, probably the safest approach is to ensure that the field containing the string has a unique constraint on it and try to add it. If you suceeded in adding it then you know it was unique, if you didn't then it wasn't. And this is safe to do in a multithreaded environment.

If you are simply checking against a static list of strings and do not intend to add the generated string to the database then ignore this post :P

like image 41
jcoder Avatar answered Feb 23 '23 00:02

jcoder