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?Roddy– Roddy2011-06-28 09:16:55 +00:00Commented Jun 28, 2011 at 9:16
-
What have you tried to resolve the problem? Where are you stuck?Nico Haase– Nico Haase2022-09-13 08:56:42 +00:00Commented Sep 13, 2022 at 8:56
Add a comment
|
3 Answers
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
Zach Rattner
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.Alfred
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..
Zach Rattner
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.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
Zach Rattner
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.Balanivash
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 :)