Home >Backend Development >PHP Tutorial >Example of generating random string verification code in PHP
This article mainly introduces the relevant information of using PHP encapsulation function to generate random string verification code. The article gives a detailed introduction The sample code has a certain reference value for everyone. Friends in need can learn together.
Preface
Generally, when we are doing programs, there will definitely be many places where random strings are used, such as for verification codes, and then This function is encapsulated. When using it, you need to set 2 parameters. The principle is to randomly grab strings and splice the strings.
$str The string to be collected in the setting, such as
$str=´jfowef34098094j3204efa234sfg2z23srhftj345xjxjhsrth´;
The string generated in the function will be randomly grabbed from $str
$codeLen sets the random string to be generated, and if it is set to 5, 5 random strings will be generated, such as
$codeLen=´5´;//设置生成的随机数个数
The code is as follows
<?php //mt_rand 获取随机数 mt_rand(min, max); //设置被随机采集的字符串 $str="abcdefghijkmnpqrstuvwxyz0123456789ABCDEFGHIGKLMNPQRSTUVWXYZ"; //设置生成的随机数个数 $codeLen=´5´; function str_rand($str,$codeLen){ $rand=""; for($i=0; $i<$codeLen-1; $i ){ //如:随机数为30 则:$str[30] $rand .= $str[mt_rand(0, strlen($str)-1)]; } return $rand; } $code=str_rand($str,$codeLen); echo $code; ?>
The above is the detailed content of Example of generating random string verification code in PHP. For more information, please follow other related articles on the PHP Chinese website!