Home > Article > Backend Development > How can php randomly generate verification codes?
This article will introduce to you how to randomly generate verification codes in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
<?php /* * 方法类 * */ class functions { /** * PHP随机生成验证码函数 * * @param array * @return mixed */ function randCode($params = []) { $num = $params['num'] ?? 4; //验证码个数 $isLetter = $params['isLetter'] ? $params['isLetter'] : 1; //1是纯数字 2是字母和数字的组合 if($isLetter==1){ for($i=1;$i<=$num;$i++){ $codeMin.=0; $codeMax.=9; } return rand($codeMin,$codeMax); } if($isLetter==2){ //如果想调整权重,自己可以根据需求修改$codeArr这个一位数组 $codeArr = ['1','2','3','4','5','6','7','8','9','0','a','b','c','d','e','f','g','h','i', 'j','k','l','m','n','o','p','q','e','s','t','u','v','w','x','y','z', '1','2','3','4','5','6','7','8','9','0']; $codeKeys = array_rand($codeArr,$num); shuffle($codeKeys); foreach ($codeKeys as $codeValue){ $codeStr .= $codeArr[$codeValue]; } return $codeStr; } } } //测试生成验证码方法 $re = (new functions())->randCode([ 'num' => 6, //需要的个数 'isLetter' => 2, //1是纯数字 2是数字加字符串 ]); print_r($re);
The test results are as follows
Recommended learning: php video tutorial
The above is the detailed content of How can php randomly generate verification codes?. For more information, please follow other related articles on the PHP Chinese website!