Home >Backend Development >PHP Tutorial >PHP random password generation_PHP tutorial
Generate a random string that can be used to automatically generate passwords.
Features:
1. You can specify that the password contains numbers or characters, and the default is mixed mode
2. Specify any password length, the default length is 6 characters
The code is as follows:
#------------------------------------------------
# Generate a random string that can be used to automatically generate passwords
# Default length is 6 characters, mixed letters and numbers
# $format ALL NUMBER CHAR string composition format
#------------------------------------------------
function randStr($len=6,$format='ALL') {
switch($format) {
case 'ALL':
$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~'; break;
case 'CHAR':
$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-@#~'; break;
case 'NUMBER':
$chars='0123456789'; break;
default :
$chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~';
break;
}
mt_srand((double)microtime()*1000000*getmypid());
$password="";
while(strlen($password)<$len)
$password.=substr($chars,(mt_rand()%strlen($chars)),1);
return $password;
}