Home  >  Article  >  Backend Development  >  Example of generating random string verification code in PHP

Example of generating random string verification code in PHP

怪我咯
怪我咯Original
2017-07-04 14:00:581267browse

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!

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