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");
or
$letterlist = array("ben", "mat", "sus");
but neither of these would produce such a good password.
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.
About the Author: John Dixon is a web developer and technical author. These days, John spends most of his time developing dynamic database-driven websites using PHP and MySQL.
Go to http://www.computernostalgia.net to view one of John's sites. This site contains articles and photos relating to the history of the computer.
To find out more about John's work, go to http://www.dixondevelopment.co.uk
Article Source: http://EzineArticles.com/?expert=John_Dixon