13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Implementing User Authentication<br />

593<br />

Listing 27.18<br />

Continued<br />

$new_password .= $r<strong>and</strong>_number;<br />

// set user's password to this in database or return false<br />

$conn = db_connect();<br />

$result = $conn->query("update user<br />

set passwd = sha1('".$new_password."')<br />

where username = '".$username."'");<br />

if (!$result) {<br />

throw new Exception('Could not change password.'); // not changed<br />

} else {<br />

return $new_password; // changed successfully<br />

}<br />

}<br />

The reset_password() function generates its r<strong>and</strong>om password by getting a r<strong>and</strong>om<br />

word from a dictionary, using the get_r<strong>and</strong>om_word() function <strong>and</strong> suffixing it with a<br />

r<strong>and</strong>om number between 0 <strong>and</strong> 999.The get_r<strong>and</strong>om_word() function, shown in<br />

Listing 27.19, is also in the user_auth_fns.php library.<br />

Listing 27.19 get_r<strong>and</strong>om_word()Function from user_auth_fns.php—This<br />

Function Gets a R<strong>and</strong>om Word from the Dictionary for Use in Generating Passwords<br />

function get_r<strong>and</strong>om_word($min_length, $max_length) {<br />

// grab a r<strong>and</strong>om word from dictionary between the two lengths<br />

// <strong>and</strong> return it<br />

// generate a r<strong>and</strong>om word<br />

$word = '';<br />

// remember to change this path to suit your system<br />

$dictionary = '/usr/dict/words'; // the ispell dictionary<br />

$fp = @fopen($dictionary, 'r');<br />

if(!$fp) {<br />

return false;<br />

}<br />

$size = filesize($dictionary);<br />

// go to a r<strong>and</strong>om location in dictionary<br />

$r<strong>and</strong>_location = r<strong>and</strong>(0, $size);<br />

fseek($fp, $r<strong>and</strong>_location);<br />

// get the next whole word of the right length in the file<br />

while ((strlen($word) < $min_length) || (strlen($word)>$max_length) ||<br />

(strstr($word, "'"))) {<br />

if (feof($fp)) {<br />

fseek($fp, 0); // if at end, go to start

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!