There's an element to using cookies that most people forget about until they spend a few hours trying to debug something that isn't even wrong (I've done this). When a web browser accepts a cookie, you can't extract its value until the next HTTP request is made.
In other words, if you set a cookie called name with a value of Julie on page 1, you can't extract that value until the user reaches page 2 (or page 5 or page 28—just some other page that isn't the page on which the cookie is initially set).
In the authentication script in the previous chapter, you had a login form and a results page. However, the authentication was valid only for the result page because it dynamically displayed the secret content (in this case, a Congratulations! message). If you want to require authentication for a series of static pages, you have to make some minor adjustments.
Open do_authuser.php in your text editor.
Scroll down to the if…else block that deals with the result of the authentication. Add a block that sets a cookie:
if ($num != 0) {
$cookie_name = "auth";
$cookie_value = "ok";
$cookie_expire = "0";
$cookie_domain = "127.0.0.1";
setcookie($cookie_name, $cookie_value, $cookie_expire,
"/" , $cookie_domain, 0);
| Note |
The setcookie() function will send a cookie called auth with a value of ok. It will expire at the end of the browser session and will be valid for all directories on 127.0.0.1. Use your own domain name if appropriate. |
Delete this line:
$msg = "<P>Congratulations, you're authorized!</p>";
Add this string:
$display_block = " <p><strong>Secret Menu:</strong></p> <ul> <li><a href=\"secretA.php\">secret page A</a> <li><a href=\"secretB.php\">secret page B</a> </ul>";
| Note |
Don't worry; you'll create the pages in this menu soon enough. |
Scroll until you see the following code:
<? echo "$msg"; ?>
Replace it with this:
<? echo "$display_block"; ?>
Save the file.
Your new code should look like this:
<?
//check for required fields
if ((!$_POST[username]) || (!$_POST[password])) {
header("Location: /show_login.html");
exit;
}
//setup names of database and table to use
$db_name = "testDB";
$table_name = "auth_users";
//connect to server and select database
$connection = @mysql_connect("localhost", "spike", "9sj7En4")
or die(mysql_error());
$db = @mysql_select_db($db_name, $connection) or die(mysql_error());
//build and issue query
$sql = "SELECT * FROM $table_name WHERE
username = \"$_POST[username]\" AND
password = password(\"$_POST[password]\")";
$result = @mysql_query($sql) or die (mysql_error());
//get the number of rows in the result set
$num = mysql_numrows($result);
//print a message and set a cookie if authorized,
//or redirect elsewhere if unauthorized
if ($num != 0) {
$cookie_name = "auth";
$cookie_value = "ok";
$cookie_expire = "0";
$cookie_domain = "127.0.0.1";
setcookie($cookie_name, $cookie_value, $cookie_expire,
"/" , $cookie_domain, 0);
$display_block = "
<p><strong>Secret Menu:</strong></p>
<ul>
<li><a href=\"secretA.php\">secret page A</a>
<li><a href=\"secretB.php\">secret page B</a>
</ul>";
} else {
header("Location: /show_login.html");
exit;
}
?>
<HTML>
<HEAD>
<TITLE>Secret Area</TITLE>
</HEAD>
<BODY>
<? echo "$display_block"; ?>
</BODY>
</HTML>
Open your web browser and type http://127.0.0.1/show_login.html to get to the login form, and then enter a valid username and password. If you still have your preferences set to warn before accepting cookies, you'll see a dialog box with cookie information in it.
After you click on Yes (or OK, depending on the dialog box), the new menu will be displayed:
The secret menu contains links to two files: secretA.php and secretB.php. By adding a snippet of code to the beginning of these pages, you can check for an authorized user.
Open a new file in your text editor and start a PHP block:
<?
Start an if…else block to check the value of $_COOKIE[auth]. The value must be ok for the user to be an authorized user:
Create a value to hold a success message:
$msg = "<P>Welcome to secret page A, authorized user!</p>";
Continue the if…else statement to account for an unauthorized visitor. An unauthorized user will be redirected to the login form:
} else {
header("Location: /show_login.html");
exit;
}
| Note |
A unauthorized visitor is one who attempts to access secretA.php directly without going through the authentication process. |
Close the PHP block and type the following HTML:
?> <HTML> <HEAD> <TITLE>Secret Page A</TITLE> </HEAD> <BODY>
Display the message:
<? echo "$msg"; ?>
Add some more HTML so that the document is valid:
</BODY> </HTML>
Save the file with the name secretA.php, and place this file in the document root of your web server.
The contents of secretB.php should be nearly identical to secretA.php, so create another file just like secretA.php, only change "A" to "B" in the messaging.
It's time for some tests. Unless your browser crashed, you should still be logged in (the auth cookie hasn't expired), and you should have the secret menu in front of you.
Click on the link for secret page A. You should see the success message shown in the following figure.
Now exit completely out of your web browser. This includes closing all browser windows and your mail client (if it's integrated). The auth cookie should now have expired (there's nothing to see; it just goes away).
Reopen your web browser, and attempt to directly access secretB.php by typing http://127.0.0.1/secretB.php.
Because you are not an authorized user anymore, you should be redirected to the login screen. Go ahead and log back in as an authorized user, and accept the cookie.
Click on the link for secret page B.
You should see the success message now shown in the following figure.
Thus concludes a brief, yet useful introduction to user authentication.