4

I have an ID column in a table which stores the row ID number (auto increment), For example 1, 2, 3. I want to generated a random and unique string which could contain only numbers, alphabets and dash (-) and underscore (_). The length of string should be 4-6, and it should be unique. Can someone help me how to generate? thanks.

2
  • possible duplicate of How to create a random string using PHP? Commented Jun 28, 2011 at 9:16
  • What have you tried to resolve the problem? Where are you stuck? Commented Sep 13, 2022 at 8:56

3 Answers 3

2

Use this - base_convert(mt_rand(0x1D39D3E06400000, 0x41C21CB8E0FFFFFF), 10, 36), but check new value against db.

Sign up to request clarification or add additional context in comments.

Comments

0
function random_gen($length)
{
  $random= "";
  srand((double)microtime()*1000000);
  $char_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  $char_list .= "abcdefghijklmnopqrstuvwxyz";
  $char_list .= "1234567890-_";
  // Add the special characters to $char_list if needed

  for($i = 0; $i < $length; $i++)
  {
    $random .= substr($char_list,(rand()%(strlen($char_list))), 1);
  }
  return $random;
}

$random_string = random_gen(6); //This will return a random 6 character string

Above function will generate the unique string

3 Comments

See my comment to the previous answer. You don't want to call strlen there, and you still have to guarantee uniqueness. This function only leverages probabilistic unlikeliness.
My question is if this always generates an unique number of you try this long enough. Okay not more than the total number of permutations..
It is still possible (albeit unlikely) that this function will return the same value twice. You should check the database with a SELECT statement to make sure the string is unique.
-1

Try this

function genRandomString($length) {
   $characters = ’0123456789abcdefghijklmnopqrstuvwxyz-_’;
   $string = ”;    
   for ($p = 0; $p < $length; $p++) {
      $string .= $characters[mt_rand(0, strlen($characters))];
    }
   return $string;
}

Call the function with the length you want

2 Comments

You're not going to want to call strlen every time you iterate over the for loop, since it's not going to change inside the loop. I'd recommend setting a variable to the output of strlen, and then use that inside the loop. Also, if you call this function inside of a do { ... } while (keyExists($String)); block, you can guarantee uniqueness. The keyExists function would have to do a SELECT statement to see if any rows exist with the given string.
ya.. strlen is going to be the same and a variable can be used for it. To guarantee uniqueness, storing and checking the db is absolutely necessary. Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.