Home > Article > Backend Development > Several methods to generate random passwords in php (1/2)_PHP tutorial
mt_rand (int $min, int $max) function is used to generate random integers, where $min–$max is the range of ascii code, here it is 33-126, the range can be adjusted as needed, such as ascii code Bits 97–122 in the table correspond to the English letters a–z. For details, please refer to the ascii code table; the chr (int $ascii) function is used to convert the corresponding integer $ascii into the corresponding character.
Code:
function create_password($pw_length = 8)
{
$randpwd = '';
for ($i = 0; $i < $pw_length; $i++)
{
$randpwd .= chr(mt_rand(33, 126));
}
Return $randpwd;
}
// Call this function and pass the length parameter $pw_length = 6
echo create_password(6);
Method 2:
1. Preset a string $chars, including a–z, a–z, 0–9 and some special characters;
2. Randomly pick a character from the $chars string;
3. Repeat the second step n times to get a password of length n.
Code:
function generate_password( $length = 8 ) {
// Password character set, you can add any characters you need
$chars = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_ []{}<>~`+=,.;:/?|';
$password = '';
for ( $i = 0; $i < $length; $i++ )
{
// There are two ways to obtain characters
// The first is to use substr to intercept any character in $chars;
is to take any element of the character array $chars
// $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
$password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
}
Return $password;
}
1 2