When developing a web application that enables users to register, it is often necessary to generate a password that would be (typically) emailed to an email address provided by the user at registration time. This article shows how to create a simple PHP function to generate a password.
The function, generate_password(), described below generates an eight character password, although it would be very straightforward to change it so that it generated a shorter or longer password.
function generate_password()
{
$letterlist = 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");
$firstletter = $letterlist[rand(0,count($letterlist) - 1)];
$secondletter = $letterlist[rand(0,count($letterlist) - 1)];
$thirdletter = $letterlist[rand(0,count($letterlist) - 1)];
$fourthletter = $letterlist[rand(0,count($letterlist) - 1)];
$fifthletter = $letterlist[rand(0,count($letterlist) - 1)];
$sixthletter = $letterlist[rand(0,count($letterlist) - 1)];
$number1 = rand(10,99);
$number2 = rand(10,99);
$word = $firstletter.$number1.$secondletter.$thirdletter.$fourthletter.$number2.$fifthletter.$sixthletter;
return $word;
}
The $letterlist array simply contains all the letters in the alphabet, in both lower and upper case. You could shorten this list, or change the items in the array so that they are, for example, short words instead of individual letters.
For example:
$letterlist = array("b", "m", "s", "f", "A");
or
$letterlist = array("ben", "mat", "sus", "john");
But neither of these would produce such a good password as the first example.
You could also change the $word variable so that it contains fewer characters.
For example:
$word = $firstletter.$secondletter.$number1;
But again, this would produce a less secure password.
Basically, you need to decide how secure you need the password to be. I've also encountered problems in the past where I've generated a complicated password, but users have had difficulty when it came to using it because they have got confused between say a "1" (one) and a lower case "l" (small L). Obviously, if they copy and paste the password from the email that is sent to them, they won't have a problem - but not everyone does that.