Several Methods for quickly generating random passwords in PHP, and several methods for generating random passwords in php
The idea is that the password is usually a mix of English letters and numbers. We can use the random function rand to randomly select a part of a long string.
function random_code($length = 8,$chars = null){ if(empty($chars)){ $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; } $count = strlen($chars) - 1; $code = ''; while( strlen($code) < $length){ $code .= substr($chars,rand(0,$count),1); } return $code;}echo random_code;//A1zYbN5X
The purpose of using the rand function is to generate random strings, but if a function can be used, we do not need to use the rand function.
function random_char($length = 8,$chars = null){ if( empty($chars) ){ $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; } $chars = str_shuffle($chars); $num = $length < strlen($chars) - 1 ? $length:str_len($chars) - 1; return substr($chars,0,$num);}
We can see that the str_shuffle function is used instead of the rand function, which greatly reduces the amount of code.
More closely, our function not only generates random passwords, but also SMS verification codes and high-intensity server logon passwords.
function random_code_type($length = 8,$type = 'alpha-number'){ $code_arr = array( 'alpha' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'number'=> '0123456789', 'sign' => '#$%@*-_', ); $type_arr = explode('-',$type); foreach($type_arr as $t){ if( ! array_key_exists($t,$code_arr)){ trigger_error("Can not generate type ($t) code"); } } $chars = ''; foreach($type_arr as $t){ $chars .= $code_arr[$t]; } $chars = str_shuffle($chars); $number = $length > strlen($chars) - 1 ? strlen($chars) - 1:$length; return substr($chars,0,$number);}echo random_code_type(8,"alpha-number-sign");#kXM*mC$S
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.