Please wait...
Random Password Generator
If you are creating a user management system, password are a must. You may want to generate random passwords for users the first time they register. Well, this tutorial will guide you on how to make a random password generator.
First, create a new function. Something called randomPassword. In this function we want to pass two variable. $length and $strength. Length will be how long the random password will be. Strength will be how strong we want our password to be.
# Random Password Function. function randomPassword( $length, $strength ) { }
Now we have our function, lets start putting some code in. First we need to set some default characters for our passwords.
$vowels = 'aeuy'; $consonants = 'bdghjmnpqrstvz';
These will be the starting point for creating our random password. Next we need to start creating some different strengths for our password. For this we will use some if statements and add some new chacrters as the strength increases.
if ($strength & 1) { $consonants .= 'BDGHJLMNPQRSTVWXZ'; } if ($strength & 2) { $vowels .= "AEUY"; } if ($strength & 4) { $consonants .= '23456789'; } if ($strength & 8) { $consonants .= '@#$%'; }
Now we have our strengths from 1 to 8. Now we need to randomize these characters to make it a random password. This will take a random number generated by the current time-stamp, then looped for how many characters we want for our password.
$password = ''; $alt = time() % 2; for ($i = 0; $i < $length; $i++) { if ($alt == 1) { $password .= $consonants[(rand() % strlen($consonants))]; $alt = 0; } else { $password .= $vowels[(rand() % strlen($vowels))]; $alt = 1; } }
Now all we need to do is to return our password.
return $password;
Thats how to generate a random password in PHP.Even though we can select different strengths for our passwords, it is generaly safe practice to have a high strength password, 8 would be a good idea to use all the time. Example usage and the full function code is available below.
function generatePassword($length=9, $strength=0) { $vowels = 'aeuy'; $consonants = 'bdghjmnpqrstvz'; if ($strength & 1) { $consonants .= 'BDGHJLMNPQRSTVWXZ'; } if ($strength & 2) { $vowels .= "AEUY"; } if ($strength & 4) { $consonants .= '23456789'; } if ($strength & 8) { $consonants .= '@#$%'; } $password = ''; $alt = time() % 2; for ($i = 0; $i < $length; $i++) { if ($alt == 1) { $password .= $consonants[(rand() % strlen($consonants))]; $alt = 0; } else { $password .= $vowels[(rand() % strlen($vowels))]; $alt = 1; } } return $password; } $random_password = randomPassword(9, 8);