Specifications
LISTING 24.19 The get_random_word() Function from user_auth_fns.php—This Function
Gets a Random Word from the Dictionary for Use in Generating Passwords
function get_random_word($min_length, $max_length)
// grab a random word from dictionary between the two lengths
// and return it
{
// generate a random word
$word = “”;
$dictionary = “/usr/dict/words”; // the ispell dictionary
$fp = fopen($dictionary, “r”);
$size = filesize($dictionary);
// go to a random location in dictionary
srand ((double) microtime() * 1000000);
$rand_location = rand(0, $size);
fseek($fp, $rand_location);
// get the next whole word of the right length in the file
while (strlen($word)< $min_length || strlen($word)>$max_length)
{
if (feof($fp))
fseek($fp, 0); // if at end, go to start
$word = fgets($fp, 80); // skip first word as it could be partial
$word = fgets($fp, 80); // the potential password
};
$word=trim($word); // trim the trailing \n from fgets
return $word;
}
To work, this function needs a dictionary. If you are using a UNIX system, the built-in spell
checker ispell comes with a dictionary of words, typically located at /usr/dict/words, as it is
here. If you are using some other system or do not want to install ispell, don’t worry! You can
download the word list used by ispell from
http://ficus-www.cs.ucla.edu/ficus-members/geoff/ispell-dictionaries.html
This site also has dictionaries in many other languages, so if you would like a random, say,
Norwegian or Esperanto word, you can download one of those dictionaries instead. These files
are formatted with each word on a separate line, separated by newlines.
To get a random word from this file, we pick a random location between 0 and the filesize, and
read from the file there. If we read from the random location to the next newline, we will most
likely only get a partial word, so we skip the line we open the file to, and take the next word as
our word by calling fgets() twice.
Building Practical PHP and MySQL Projects
P
ART V
524
30 7842 ch24 3/6/01 3:34 PM Page 524










