I am trying to create a 'confirmation code' for every user account created on my website and storing it in the db along with their personal information. As you can see in the example below, I tried to generate a random string factoring in the time variable, however, the string is unneccessarily long.
I would like the string to be shorter than the one produced by md5
I was wondering if there is a relatively easy way to generate 10 digit (max) alphanumeric string that has an extremely low collision rate?
What I tried:
md5(mt_rand(10000,99999).time() . 'example@domain.com');
Output:
0dd6854dba19e70cfda0ab91595e0376
PHP provides the openssl_random_pseudo_bytes
function that can be made to securely do what you want.
Do something like:
bin2hex(openssl_random_pseudo_bytes(5))
The above will give you something like e9d196aa14
, for example.
Alternatively, just take the first 10 chars of your existing MD5 string.
This will generate you any random output string from Aa-Zz
and 0-9
characters.
function genString($length) {
$lowercase = "qwertyuiopasdfghjklzxcvbnm";
$uppercase = "ASDFGHJKLZXCVBNMQWERTYUIOP";
$numbers = "1234567890";
$specialcharacters = "{}[];:,./<>?_+~!@#";
$randomCode = "";
mt_srand(crc32(microtime()));
$max = strlen($lowercase) - 1;
for ($x = 0; $x < abs($length/3); $x++) {
$randomCode .= $lowercase{mt_rand(0, $max)};
}
$max = strlen($uppercase) - 1;
for ($x = 0; $x < abs($length/3); $x++) {
$randomCode .= $uppercase{mt_rand(0, $max)};
}
$max = strlen($specialcharacters) - 1;
for ($x = 0; $x < abs($length/3); $x++) {
$randomCode .= $specialcharacters{mt_rand(0, $max)};
}
$max = strlen($numbers) - 1;
for ($x = 0; $x < abs($length/3); $x++) {
$randomCode .= $numbers{mt_rand(0, $max)};
}
return str_shuffle($randomCode);
}
Usage
$str = genString(10);
I think the best way is
$random = substr(number_format(time() * rand(),0,'',''),0,10); // you can increase the digits by changing 10 to desired digit
Please check it out
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.