Memorable Password Generator
In this tutorial you will learn to create a password generator that creates pronouncable easy to remember passwords. Lets start with the full script.
<?php function genPass($lenght) { $vowels = "a,o,u,e,i,y,ea,ou"; $cons = "q,w,r,t,p,d,f,g,h,j,k,l,c,v,b,n,m,th,ch,cr,br,ch,ph,cl"; $vowelsArray = explode(",",$vowels); $consArray = explode(",",$cons); for ($i = 0; $i < $lenght/2; $i++){ $password .= $vowelsArray[(mt_rand(0,count($vowelsArray)-1))]; $password .= $consArray[(mt_rand(0,count($consArray)-1))]; } $password = substr($password,0,$lenght); return $password; } ?>
First we define the function, it can take a variable to decide the lenght of the password:
function genPass($lenght) {
Here we create 2 strings, with letters separated by commas. We will use these letters when we create the password:
$vowels = "a,o,u,e,i,y,ea,ou"; $cons = "q,w,r,t,p,d,f,g,h,j,k,l,c,v,b,n,m,th,ch,cr,br,ch,ph,cl";
To easier work with these letters, we split them up and put them into arrays. Resulting in $vowelsArray[0] == a, $vowelsArray[1] == o etc.
$vowelsArray = explode(",",$vowels); $consArray = explode(",",$cons);
Then we have 2 lines inside a for loop. count($vowelsArray)-1 Will count how many positions we have in that array, and substract with 1. (mt_rand(0,count($vowelsArray)-1)) Will then return a random numer, from 0 to count($vowelsArray)-1. We will end up with e.g $vowelsArray[3];. Using the .= operator we will add both a vowel and a consonant to the string.
for ($i = 0; $i < $lenght/2; $i++){ $password .= $vowelsArray[(mt_rand(0,count($vowelsArray)-1))]; $password .= $consArray[(mt_rand(0,count($consArray)-1))]; }
The next line will give us a password with the lenght that we want. Taking out a substring from $password, with start from letter 0 with the lenght of $lenght.
$password = substr($password,0,$lenght);
Then we reurn the password.
return $password;
Here is how we can use the script:
$newpass = genPass(6); echo "<p>$newpass</p>";