Example of generating random string verification code in PHP

怪我咯
Release: 2023-03-12 15:42:01
Original
1242 people have browsed it

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´;
Copy after login

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´;//设置生成的随机数个数
Copy after login

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; 

?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!