Custom function code in php to generate random passwords

  • 2020-10-07 18:36:25
  • OfStack

Code 1:

A function that generates a random password as a random string of lowercase letters and Numbers with a customizable length. This is relatively simple


<?php
/*
 * php Automatically generate a new password custom function (with an example demonstration) 
       Applicable Environment:  PHP5.2.x  / mysql 5.0.x
* */
function genPassword($min = 5, $max = 8)  
{  
    $validchars="abcdefghijklmnopqrstuvwxyz123456789";  
    $max_char=strlen($validchars)-1;  
    $length=mt_rand($min,$max);  
    $password = "";  
    for($i=0;$i<$length;$i )  
    {  
        $password.=$validchars[mt_rand(0,$max_char)];  
    }  
        return $password;  
    }  
    echo " The new password: ".genPassword()."<br>";  
    echo " The new password: ".genPassword(5,10)."<br>";
?>


The following is a summary of some examples of friends can refer to.

Case 1

The simplest way to generate it


function generatePassword($length=8)
{
    $chars = array_merge(range(0,9),
                     range('a','z'),
                     range('A','Z'),
                     array('!','@','$','%','^','&','*'));
    shuffle($chars);
    $password = '';
    for($i=0; $i<8; $i++) {
        $password .= $chars[$i];
    }
    return $password;
}

Case 2

1. Generate a random integer, such as 35, in 33? 126.
2. Convert 35 to corresponding ASCII code characters, such as 35 corresponding #
3. Repeat steps 1 and 2 above n times and connect to n bit password


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, passing the length argument $pw_length = 6
echo create_password(6);

The instance


<?php 
mt_srand((double) microtime() * 1000000); 

function gen_random_password($password_length = 32, $generated_password = ""){ 
 $valid_characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; 
 $chars_length = strlen($valid_characters) - 1; 
 for($i = $password_length; $i--; ) { 
  //$generated_password .= $valid_characters[mt_rand(0, $chars_length)]; 

  $generated_password .= substr($valid_characters, (mt_rand()%(strlen($valid_characters))), 1); 
 } 
 return $generated_password; 
} 

?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<title>php  Password generator  v 4.0</title> 
<style type="text/css"> 
body { 
 font-family: Arial; 
 font-size: 10pt; 
} 
</style> 
</head> 
<body> 
<span style="font-weight: bold; font-size: 15pt;"> Password generator v4.0 by freemouse</span><br /><br /> 
<?php 

if (isset($_GET['password_length'])){ 
 if(preg_match("/([0-9]{1,8})/", $_GET['password_length'])){ 
  print(" Password generation successful :<br /> 
<span style="font-weight: bold">" . gen_random_password($_GET['password_length']) . "</span><br /><br />n"); 
 } else { 
  print(" The password length is incorrect !<br /><br />n"); 
 } 
} 

print <<< end
 Please specify the length of the generated password for the password generation :<br /><br /> 
<form action="{$_SERVER['PHP_SELF']}" method="get"> 
 <input type="text" name="password_length"> 
 <input type="submit" value=" generate "> 
</form> 
end; 

?> 
</body> 
</html>

Example 4


1. A string of $chars is preset, including a, A, Z, 0, 9, and 1 special characters
2. Randomly select 1 character in the $chars string
3. Repeat step 2 n for a password of length n


function generate_password( $length = 8 ) {
    //  Password character set, you can add any character you want 
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_ []{}<>~`+=,.;:/?|';
    $password = '';
    for ( $i = 0; $i < $length; $i++ ) 
    {
        //  There are two ways to get characters 
        //  The first 1 Is using  substr  The interception $chars Any of the 1 A character; 
        //  The first 2 It's a character array  $chars  Any element of 
        // $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        $password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
    }
    return $password;
}

None of the above tested performs as well as the one below

1. Preset 1 character array of $chars, including a, A, Z, 0, 9, and 1 special characters
2. Randomly select $length elements from the array $chars through array_rand()
3. According to the obtained key name array $keys, extract the character concatenation string from the array $chars. The disadvantage of this method is that the same character will not be fetched repeatedly.


function make_password( $length = 8 )
{
    //  Password character set, you can add any character you want 
    $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 
    'i', 'j', 'k', 'l','m', 'n', 'o', 'p', 'q', 'r', 's', 
    't', 'u', 'v', 'w', 'x', 'y','z', 'A', 'B', 'C', 'D', 
    'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L','M', 'N', 'O', 
    'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y','Z', 
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '!', 
    '@','#', '$', '%', '^', '&', '*', '(', ')', '-', '_', 
    '[', ']', '{', '}', '<', '>', '~', '`', '+', '=', ',', 
    '.', ';', ':', '/', '?', '|');
    //  in  $chars  Randomly pick up  $length  The key names of the array elements 
    $keys = array_rand($chars, $length);
    $password = '';
    for($i = 0; $i < $length; $i++)
    {
        //  will  $length  Concatenates the elements of an array into a string 
        $password .= $chars[$keys[$i]];
    }
    return $password;
}


Related articles: