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 />

587<br />

Listing 27.12<br />

Continued<br />

if (!$result) {<br />

throw new Exception('Could not log you in.');<br />

}<br />

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

return true;<br />

} else {<br />

throw new Exception('Could not log you in.');<br />

}<br />

}<br />

As you can see, the login() function connects to the database <strong>and</strong> checks that there is a<br />

user with the username <strong>and</strong> password combination supplied. It returns true if there is or<br />

throws an exception if there is not or if the user’s credentials could not be checked.<br />

The check_valid_user() function does not connect to the database again, but<br />

instead just checks that the user has a registered session—that is, that he has already<br />

logged in.This function is shown in Listing 27.13.<br />

Listing 27.13 check_valid_user()Function from user_auth_fns.php—This<br />

Function Checks That the User Has a Valid Session<br />

function check_valid_user() {<br />

// see if somebody is logged in <strong>and</strong> notify them if not<br />

if (isset($_SESSION['valid_user'])) {<br />

echo "Logged in as ".$_SESSION['valid_user'].".";<br />

} else {<br />

// they are not logged in<br />

do_html_heading('Problem:');<br />

echo 'You are not logged in.';<br />

do_html_url('login.php', 'Login');<br />

do_html_footer();<br />

exit;<br />

}<br />

}<br />

If the user is not logged in, the function will tell him he has to be logged in to see this<br />

page, <strong>and</strong> give him a link to the login page.<br />

Logging Out<br />

You might have noticed the link marked Logout on the menu in Figure 27.6.This is a<br />

link to the logout.php script; the code for this script is shown in Listing 27.14.

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

Saved successfully!

Ooh no, something went wrong!