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

时间:2016-08-30 12:57:02

标签: php shuffle

我有一个生成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个必填数字。

我该怎么做?

5 个答案:

答案 0 :(得分: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));

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

答案 1 :(得分:1)

还有一个选择。

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

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);

答案 2 :(得分:0)

button

答案 3 :(得分:0)

你也可以使用random()来用num +字母来创建字符串。LINK

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

答案 4 :(得分:0)

希望这能帮到你

    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。