Prev | Current Page 440 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"

For purposes of this example, the data store is limited to three fields??”
a primary key, a username, and a password. These columns are placed into a table
called logins, shown in Listing 14-5.
?– Note If you??™re unfamiliar with the MySQL server and are confused by the syntax found in this
example, consider reviewing the material found in Chapter 30.
Listing 14-5. A User Authentication Table
CREATE TABLE logins (
id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT,
username VARCHAR(16) NOT NULL,
pswd VARCHAR(32) NOT NULL,
PRIMARY KEY(id));
A few lines of sample data follow:
id username password
1 wjgilmore 098f6bcd4621d373cade4e832627b4f6
2 mwade 0e4ab1a5a6d8390f09e9a0f2d45aeb7f
3 jgennick 3c05ce06d51e9498ea472691cd811fb6
Listing 14-6 displays the code used to authenticate a user-supplied username and
password against the information stored within the logins table.
374 CHAPTER 14 ?–  AUTHENTICATING YOUR USERS
Listing 14-6. Authenticating a User Against a MySQL Database
/* Because the authentication prompt needs to be invoked twice,
embed it within a function.
*/
function authenticate_user() {
header('WWW-Authenticate: Basic realm="Secret Stash"');
header("HTTP/1.0 401 Unauthorized");
exit;
}
/* If $_SERVER['PHP_AUTH_USER'] is blank, the user has not yet been
prompted for the authentication information.
*/
if (! isset($_SERVER['PHP_AUTH_USER'])) {
authenticate_user();
} else {
// Connect to the MySQL database
mysql_pconnect("localhost","authenticator","secret")
or die("Can't connect to database server!");
mysql_select_db("corporate")
or die("Can't select database!");
// Create and execute the selection query
$query = "SELECT username, pswd FROM userauth
WHERE username='$_SERVER[PHP_AUTH_USER]' AND
pswd=MD5('$_SERVER[PHP_AUTH_PW]')";
$result = mysql_query($query);
CHAPTER 14 ?–  AUTHENTICATING YOUR USERS 375
// If nothing was found, reprompt the user for the login information
if (mysql_num_rows($result) == 0) {
authenticate_user();
} else {
echo "Welcome to the secret archive!";
}
}
?>
Although database authentication is more powerful than the previous two methodologies
described, it is really quite trivial to implement.


Pages:
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452