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.

522 Chapter 23 Using Session Control in <strong>PHP</strong><br />

{<br />

// if they are in the database register the user id<br />

$_SESSION[‘valid_user’] = $userid;<br />

}<br />

$db_conn->close();<br />

}<br />

Because you now know who the user is, you don’t need to show her the login form<br />

again. Instead, you can tell her you know who she is <strong>and</strong> give her the option to log out:<br />

if (isset($_SESSION[‘valid_user’]))<br />

{<br />

echo ‘You are logged in as: ‘.$_SESSION[‘valid_user’].’ ’;<br />

echo ‘Log out’;<br />

}<br />

If you tried to log her in <strong>and</strong> failed for some reason, you’ll have a userid but not a<br />

$_SESSION[‘valid_user’] variable, so you can give her an error message:<br />

if (isset($userid))<br />

{<br />

// if they’ve tried <strong>and</strong> failed to log in<br />

echo ‘Could not log you in.’;<br />

}<br />

That’s it for the main script. Now, let’s look at the Members page.The code for this<br />

script is shown in Listing 23.5.<br />

Listing 23.5 members_only.php—The Code for the Members’ Section of the <strong>Web</strong>site<br />

Checks for Valid Users<br />

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

Saved successfully!

Ooh no, something went wrong!