如何用2位数字和4个字母创建6位OTP


How to create 6 digit OTP with 2 digits and 4 alphabets?

我有一个脚本,生成6个字符的一次性密码(OTP)。

下面是代码:-
$seed = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ'.'0123456789'); // and any other characters
shuffle($seed); // probably optional since array_is randomized; this may be redundant
$rand = '';
foreach (array_rand($seed, 6) as $k) 
    $rand .= $seed[$k];
$feedID = $rand;

现在,由于洗牌过程,目前6个都可以是数字,6个都可以是字母。我想要最小和最大2个强制数字。

我该怎么做呢?

我的看法是:

// Create a string of all alpha characters and randomly shuffle them
$alpha   = str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
// Create a string of all numeric characters and randomly shuffle them
$numeric = str_shuffle('0123456789');
// Grab the 4 first alpha characters + the 2 first numeric characters
$code = substr($alpha, 0, 4) . substr($numeric, 0, 2);
// Shuffle the code to get the alpha and numeric in random positions
$code = str_shuffle($code);

如果你想让任何字符出现一次以上的可能性,改变前两行(快速和肮脏):

// Let's repeat this string 4 times before shuffle, since we need 4 characters
$alpha   = str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 4));
// Let's repeat this string 2 times before shuffle, since we need 2 numeric characters
$numeric = str_shuffle(str_repeat('0123456789', 2));

不是说这是最好的方法,但它很简单,没有循环和/或数组。:)

多一个选项

并不是说这是最好的方法,但它很简单,循环和数组。;)

foreach ([4 => range('A', 'Z'), 2 => range(0, 9)] as $n => $chars) {
    for ($i=0; $i < $n; $i++) {
        $otp[] = $chars[array_rand($chars)];
    }
}
shuffle($otp);
$otp = implode('', $otp);
 $seed = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
 $seed2= str_split('0123456789');
 $rand = [];
 for($i=mt_rand(1,2);$i<=2;$i++){
   shuffle($seed2);
   $rand[]=$seed2[0];     
 }
 while(count($rand)!=6){
  shuffle($seed);
  $rand[]=$seed[0];
 }
 shuffle($rand);
 print $feedID = implode('',$rand);

您也可以使用random()来生成num +字母的字符串。链接

function generateRandomString($length = 10) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

希望对你有所帮助

    function generateRandomString($length = 10,$char_len=4,$numbre_len=2) {
    $characters = '0123456789';
    $characters2='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
  $charactersLength2 = strlen($characters);
    $randomString = '';
    for ($i = 0; $i <$char_len ; $i++) {
        $randomString .= $characters2[rand(0, $charactersLength2 - 1)];
    }
  for ($i = 0; $i <$numbre_len ; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
   $shuffled = str_shuffle($randomString);
    return $shuffled;
}

 $length=7;
$char_len=6;
$numbre_len=1;
echo generateRandomString($length,$char_len,$numbre_len);

这个函数可以帮助生成你想要的动态随机otp