13.09.2016 Views

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Implementing User Authentication<br />

595<br />

Listing 27.20 notify_password()Function from user_auth_fns.php—This<br />

Function Emails a Reset Password to a User<br />

function notify_password($username, $password) {<br />

// notify the user that their password has been changed<br />

$conn = db_connect();<br />

$result = $conn->query("select email from user<br />

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

if (!$result) {<br />

throw new Exception('Could not find email address.');<br />

} else if ($result->num_rows == 0) {<br />

throw new Exception('Could not find email address.');<br />

// username not in db<br />

} else {<br />

$row = $result->fetch_object();<br />

$email = $row->email;<br />

$from = "From: support@phpbookmark \r\n";<br />

$mesg = "Your <strong>PHP</strong>Bookmark password has been changed to ".$password."\r\n"<br />

."Please change it next time you log in.\r\n";<br />

}<br />

if (mail($email, '<strong>PHP</strong>Bookmark login information', $mesg, $from)) {<br />

return true;<br />

} else {<br />

throw new Exception('Could not send email.');<br />

}<br />

}<br />

In the notify_password() function, given a username <strong>and</strong> new password, you simply<br />

look up the email address for that user in the database <strong>and</strong> use <strong>PHP</strong>’s mail() function to<br />

send it to her.<br />

It would be more secure to give users a truly r<strong>and</strong>om password—made from any<br />

combination of upper <strong>and</strong> lowercase letters, numbers, <strong>and</strong> punctuation—rather than the<br />

r<strong>and</strong>om word <strong>and</strong> number. However, a password like zigzag487 will be easier for users<br />

to read <strong>and</strong> type than a truly r<strong>and</strong>om one. It is often confusing for users to work out<br />

whether a character in a r<strong>and</strong>om string is 0 or O (zero or capital O), or 1 or l (one or a<br />

lowercase L).<br />

On our system, the dictionary file contains about 45,000 words. If a cracker knew<br />

how we were creating passwords <strong>and</strong> knew a user’s name, he would still have to try<br />

22,500,000 passwords on average to guess one.This level of security seems adequate for<br />

this type of application even if our users disregard our emailed advice to change their<br />

password.

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

Saved successfully!

Ooh no, something went wrong!