Home >php教程 >php手册 >使用PHP生成1000个随机注册码

使用PHP生成1000个随机注册码

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-21 08:59:291047browse

  一般程序中都需要用到注册码,为了防止盗版,如果把生成的注册码保存到数据库里,并且通过软件在客户端访问服务器来匹配客户端输入的验证码是否正确,这是一种好的解决盗版的方案。

  下面描述的代码就是使用PHP生成数字验证码,类似于:152-562-986-230 这样的,为了保证验证码不被猜中,我们采用比较复杂的12位数字,那么可能性就有:999999999999 这么多,那么重复的几率就很小。

  我们下面的的程序就演示了身成1000个随机的注册码的例子。包括两个程序,一个程序用来生成从 100到999的序列数字并且保存到文件里,第二个程序是从文件中提取随机数对应行的数字生成验证码串,然后身成1000个随机串,最后保存在文件里。

  程序一:生成序列数字

/**
 * File: 生成4位的数字
 * Author: heiyeluren
 * Create: 2005-9-5 22:26
 */

 /* 配置 */
 $start_num = 100;
 $end_num = 999;
 $save_file = "./number.txt";

 //生成从1000到9999的数字序列
 for ($i=$start_num; $i {
     $nums[] = $i;
 }

//把上面生成的数字序列写入文件
$fp = fopen($save_file, "w")  or die("Open $save_file failed");
fwrite($fp, implode("\r\n", $nums)) or die("Write $save_file failed");
unset($nums);
fclose($fp);

echo "Create $save_file succeed!";

?>

  执行上面的代码,就会在当前程序目录生成一个 number.txt文件,里面保存了类似下面的数字:

100
101
102
103
104
105
106...


  程序二:生成验证码


/**
 * File: 生成CD-Key程序
 * Author: heiyeluren
 * Create: 2005-9-5 22:26
 */

 /* 配置 */
 $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_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("\r\n", "", $key_str);
 }

 /* 过滤重复串并且提取最终需要的CD-Key数量 */
 $cdkey = array_unique($cdkey);
 $key_result = array();
 for ($i=0; $i {
     $key_result[] = $cdkey[$i];
 }

 /* 把最终的CD-Key写入文件 */
 $fp = fopen($save_file, "w+") or die("Open $save_file failed");
 fwrite($fp, implode("\r\n", $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之类的验证码,呵呵发挥下想象力。



Statement:
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