Reputation: 2053
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.
Upvotes: 4
Views: 3829
Reputation: 15960
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
Upvotes: 0
Reputation: 22050
Use this - base_convert(mt_rand(0x1D39D3E06400000, 0x41C21CB8E0FFFFFF), 10, 36), but check new value against db.
Upvotes: 2
Reputation: 6867
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
Upvotes: -1