PHP注册码/序列号生成实例程序
昨天开发一个产品要求由网站总后台生成一个注册码/序列号,然后我们以573-225-374-118这种格式生成,并且不重复在数据库是唯一的,下面我把我找到的与自己写的都记录一下。
原理,就是生成mt_rand随机种子来生成,然后利用相关函数进行读取操作.
例1代码如下:
<?php
/**
* 序列号生成器
*/
function snMaker($pre = '') {
$date = date('Ymd');
$rand = rand(1000000, 9999999);
$time = mb_substr(time() , 5, 5, 'utf-8');
$serialNumber = $pre . $date . $time . $rand;
// echo strlen($serialNumber).'<br />';
return $serialNumber;
}
echo snMaker();
/**
* 将一个字符串的一部分替换成某一特定字符
* @param str or int $str 需要处理的字符串
* @param str or int $to 将替换成什么字符串
* @param int $start 保留前几个字符
* @param int $end 保留后几个字符
*/
function hideString($str = 'hello', $to = '*', $start = 1, $end = 0) {
$lenth = strlen($str) - $start - $end;
$lenth = ($lenth < 0) ? 0 : $lenth;
$to = str_repeat($to, $lenth);
$str = substr_replace($str, $to, $start, $lenth);
return $str;
}
echo hideString();
?>例2,生成注册码/序列号,以下为引用的内容,代码如下:
<?php
/* 配置 */
$key_sum = 1500; //CD-Key最大数量,防止重复值
$key_total = 1000; //最终需要的CD-Key数量
$limiter = "-"; //CD-Key每组数字之间的连接符
$save_file = "./cd_key.txt"; //保存CD-Key文件
$num_file = "./number.txt"; //序列数字文件
$file = file($num_file); //打开序列数文件
$start_num = 0; //最小随机数
$end_num = count($file); //最大随机数
/* 生成随机数字串 */
$cdkey = array();
for ($i = 0; $i < $key_sum; $i++) {
$key_str = $file[rand_num($start_num, $end_num) ] . $limiter . $file[rand_num($start_num, $end_num) ] . $limiter . $file[rand_num($start_num, $end_num) ] . $limiter . $file[rand_num($start_num, $end_num) ];
$cdkey[] = str_replace("rn", "", $key_str);
}
/* 过滤重复串并且提取最终需要的CD-Key数量 */
$cdkey = array_unique($cdkey);
$key_result = array();
for ($i = 0; $i < $key_total; $i++) {
$key_result[] = $cdkey[$i];
}
/* 把最终的CD-Key写入文件 */
$fp = fopen($save_file, "w+") or die("Open $save_file failed");
fwrite($fp, implode("rn", $key_result)) or die("Write $save_file failed");
unset($cdkey);
unset($$key_result);
fclose($fp);
echo "Create $key_total key succeed!";
/* 随机函数 */
function rand_num($start, $end) {
return mt_rand($start, $end);
}
?>执行上面的程序就会生成cd_key.txt文件,里面包含了类似下面的验证码,以下为引用的内容:
573-225-374-118,691-553-280-280,969-594-607-211,251-575-776-563,280-289-739-533...
这样,就完整的达到了我们的目的,你也可以把以上随机串保存到数据库里,方便调用,灵活设置以上变量,你能够生成16位、20位的验证码,如果你有兴趣,也可以写类似 XDF8F-ADE89-D0J5C-4RTFG之类的验证码
本文链接:http://www.phprm.com/develop/fs1430.html
收藏随意^^请保留教程地址.