With users now able to sign up to the site, Example 21-7, login.php, provides the code needed to let them
log in. Like the signup page, it features a simple HTML form and some
basic error checking, as well as using sanitizeString
before querying the MySQL
database.
The main thing to note here is that, upon successful verification of
the username and password, the session variables 'user'
and 'pass'
are given the username and password
values. As long as the current session remains active these variables will
be accessible by all the programs in the project, allowing them to
automatically provide access to logged-in users.
You may be interested in the use of the die
function upon successfully logging in. This
is there because it combines an echo
and an exit
command in one, thus saving
a line of code. For styling, this file (like most of the others) applies
the class main
to indent the content
from the lefthand edge.
When you call up this program in your browser, it should look like
Figure 21-3. Note how the <input />
type of password
has been used here to mask the password
with asterisks to prevent it from being viewed by anyone looking over the
user’s shoulder.
<?php // login.php include_once 'header.php'; echo "<div class='main'><h3>Please enter your details to log in</h3>"; $error = $user = $pass = ""; if (isset($_POST['user'])) { $user = sanitizeString($_POST['user']); $pass = sanitizeString($_POST['pass']); if ($user == "" || $pass == "") { $error = "Not all fields were entered<br />"; } else { $query = "SELECT user,pass FROM members WHERE user='$user' AND pass='$pass'"; if (mysql_num_rows(queryMysql($query)) == 0) { $error = "<span class='error'>Username/Password invalid</span><br /><br />"; } else { $_SESSION['user'] = $user; $_SESSION['pass'] = $pass; die("You are now logged in. Please <a href='members.php?view=$user'>" . "click here</a> to continue.<br /><br />"); } } } echo <<<_END <form method='post' action='login.php'>$error <span class='fieldname'>Username</span><input type='text' maxlength='16' name='user' value='$user' /><br /> <span class='fieldname'>Password</span><input type='password' maxlength='16' name='pass' value='$pass' /> _END; ?> <br /> <span class='fieldname'> </span> <input type='submit' value='Login' /> </form><br /></div></body></html>