Page 461 - Beginning PHP 5.3
P. 461
Chapter 14: Manipulating MySQL Data with PHP
displayPageHeader( “Thanks for logging in!”, true );
? >
< p > Thank you for logging in. Please proceed to the < a href=”index.
php” > members’ area < /a > . < /p >
< ?php
displayPageFooter();
}
? >
The structure of this script is similar to the register.php script you created earlier. If the login form
was submitted, processForm() is called; otherwise, displayForm() is called. displayForm()
displays the login form, which comprises username and password fields, as well as a Login button. Any
error message is displayed at the top of the form, and any missing fields are highlighted in red.
processForm() checks the submitted login details and, if valid, logs the member in. First it creates a
new Member object populated with the supplied username and password (filtered to remove any invalid
characters). If either field was missing, an error message is generated. Otherwise, the script validates the
entered username and password by calling the Member object ’ s authenticate() method:
} elseif ( !$loggedInMember = $member- > authenticate() ) {
Remember that this method returns a Member object representing the logged - in member if the username
and password matched; otherwise it returns nothing. So if $loggedInMember is false , the login
failed and an error message is generated:
$errorMessages[] = ‘ < p class=”error” > Sorry, we could not log you in with
those details. Please check your username and password, and try again. < /p > ’;
If any error messages were generated, the form is redisplayed. Otherwise, all went well, so the logged - in
Member object is stored in the session, and a thank - you page is displayed:
if ( $errorMessages ) {
displayForm( $errorMessages, $missingFields, $member );
} else {
$_SESSION[“member”] = $loggedInMember;
displayThanks();
}
By storing a Member object representing the logged - in member in the $_SESSION array, other scripts in
the application can easily test if a member is currently logged in, and identify the logged - in member,
simply by looking in the session data.
The final function, displayThanks() , thanks the member for logging in and provides them with a link
to take them to the main page of the members ’ area, index.php .
423
9/21/09 9:14:10 AM
c14.indd 423
c14.indd 423 9/21/09 9:14:10 AM