Home  >  Article  >  Backend Development  >  PHP encapsulation function to generate random string verification code

PHP encapsulation function to generate random string verification code

高洛峰
高洛峰Original
2017-02-03 15:44:331383browse

Preface

Generally speaking, when we are making programs, we will definitely use random strings in many places, such as for verification codes. Then we encapsulate this function and set it when using it. 2 parameters, the principle is to randomly grab strings and splice the strings

$str settings to be collected strings, such as

$str=´jfowef34098094j3204efa234sfg2z23srhftj345xjxjhsrth´;

The string generated in the function will be randomly grabbed from $str

$codeLen sets the random string to be generated, set it to 5, and then generate 5 random strings, 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;
 
?>

Summary

The above is the complete method of generating random strings, except where the verification code can be used It can also be used in other places. I hope the content of this article can bring some help to everyone's study or work. If you have any questions, you can leave a message to communicate.

For more articles related to the PHP encapsulation function to generate random string verification codes, please pay attention to the PHP Chinese website!

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
Previous article:Linux/Unix login scriptNext article:Linux/Unix login script