Home > Backend Development > PHP Tutorial > PHP randomly generates unique 8-digit card number (number) and card secret (string)

PHP randomly generates unique 8-digit card number (number) and card secret (string)

藏色散人
Release: 2023-04-07 22:28:01
forward
6552 people have browsed it

1. Generate non-repeating random numbers with customizable length

/**
 * 生成不重复的随机数字
 * @param  int $start  需要生成的数字开始范围
 * @param  int $end    结束范围
 * @param  int $length 需要生成的随机数个数
 * @return number      生成的随机数
 */
function getRandNumber($start=0,$end=9,$length=8){
//初始化变量为0
$connt = 0;
//建一个新数组
$temp = array();
while($connt < $length){
//在一定范围内随机生成一个数放入数组中
$temp[] = mt_rand($start, $end);
//$data = array_unique($temp);
//去除数组中的重复值用了“翻翻法”,就是用array_flip()把数组的key和value交换两次。这种做法比用 array_unique() 快得多。
$data = array_flip(array_flip($temp));
//将数组的数量存入变量count中
$connt = count($data);
}
//为数组赋予新的键名
shuffle($data);
//数组转字符串
$str=implode(",", $data);
//替换掉逗号
$number=str_replace(&#39;,&#39;, &#39;&#39;, $str);
return $number;
}
Copy after login

2. Randomly generate non-repeating 8-digit card password

function makeCardPassword() {
        $code = &#39;ABCDEFGHIJKLMNOPQRSTUVWXYZ&#39;;
        $rand = $code[rand(0,25)]
            .strtoupper(dechex(date(&#39;m&#39;)))
            .date(&#39;d&#39;).substr(time(),-5)
            .substr(microtime(),2,5)
            .sprintf(&#39;%02d&#39;,rand(0,99));
        for(
            $a = md5( $rand, true ),
            $s = &#39;0123456789ABCDEFGHIJKLMNOPQRSTUV&#39;,
            $d = &#39;&#39;,
            $f = 0;
            $f < 8;
            $g = ord( $a[ $f ] ),
            $d .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ],
            $f++
        );
        return  $d;
}
Copy after login

Related recommendations: "PHP Tutorial

The above is the detailed content of PHP randomly generates unique 8-digit card number (number) and card secret (string). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template