Hack57.Create a Login System


Hack 57. Create a Login System

Sturdy login systems are required for any complex multi-user web application.

With any multi-user web application, you are going to need a user authentication system. You can use Apache's authentication mechanism, which pops up a dialog with a username and password when pages are accessed, but that means integrating your application and database with that authentication mechanism. And, unfortunately, it means that you don't have control over the login dialog; you can't include an "I've forgotten my password" option or a contact link.

Figure 6-14 shows the page flow of the login system. The user starts at index.php, the login page. From there, login.php verifies the login credentials the user provides.

Figure 6-14. The page flow of the login system


If login.php approves the credentials, the user receives a session and is sent to welcome.php. At welcome.php, the user can click on the logout link, which takes him back to the logout.php script, removes his session, and then finally sends him to the original index.php page. If the user types the welcome.php URL directly into his browser's location field without logging in, the welcome.php page will detect that and will send the sneaky user back to the index.php login page.

6.8.1. The Code

Save the code in Example 6-14 as users.sql.

Example 6-14. The database definition for the users
 DROP TABLE IF EXISTS users; CREATE TABLE users (  id MEDIUMINT NOT NULL AUTO_INCREMENT,  name TEXT,  password TEXT,  PRIMARY KEY( id ) ); INSERT INTO users VALUES ( 0, 'jack', MD5( 'toronto' ) ); INSERT INTO users VALUES ( 0, 'megan', MD5( 'seattle' ) ); 

Save the code in Example 6-15 as index.php.

Example 6-15. The login page
 <html> <head><title>Login</title></head> <body> <?php if ( $_GET['bad'] == 1 ) { ?> <font color="red">Bad login or password, please try again<br/></font> <?php } ?> <form action="login.php" method="post"> <table width="300" border="0" cellspacing="0" cellpadding="2"> <tr><td>User name:</td><td><input type="text" name="user" /></td></tr> <tr><td>Password:</td><td><input type="password" name="password" /></td></tr> <tr><td colspan="2"><center><input type="submit" value="Login" /></center></td></ tr> </table> </form> </body> </html> 

Save the code in Example 6-16 as login.php.

Example 6-16. The form handler for the login
 <?php require_once( "DB.php" ); $dsn = 'mysql://root:password@localhost/time'; $db =& DB::Connect( $dsn, array() ); if (PEAR::isError($db)) { die($db->getMessage()); } $res = $db->query( "SELECT id FROM users WHERE name=? AND password=MD5(?)",  array( $_POST['user'], $_POST['password'] ) ); $row = array( null );  if ( $res != null )  $res->fetchInto( $row ); if ( $row[0] != null )  { session_start();  $_SESSION['user'] = $row[0];  header( "Location: welcome.php" ); }  else  { header( "Location: index.php?bad=1" ); } ?> 

Save the code in Example 6-17 as welcome.php.

Example 6-17. The home page for the users
 <?php session_start(); if ( $_SESSION['user'] == null || $_SESSION['user'] < 1 ) { header( "Location: index.php" );  exit;  } require_once( "DB.php" ); $dsn = 'mysql://root:password@localhost/time'; $db =& DB::Connect( $dsn, array( ) ); if (PEAR::isError($db)) { die($db->getMessage( )); } $res = $db->query( "SELECT name FROM users WHERE id=?", array( $_SESSION['user'] ) ); $res->fetchInto( $row ); ?> <html> <head><title>Welcome</title></head> <body> Welcome <?php echo( $row[0] ); ?><br/><br/> <a href="logout.php">Logout</a> </body> </html> 

Save the code in Example 6-18 as logout.php.

Example 6-18. The logout handler
 <?php session_destroy(); header( "Location: index.php" ); ?> 

This hack starts with the index.php page, which presents a login form to the user. From there, the user enters her name and password, and the form is submitted to the login.php page, which queries the database to see whether the user is in the system and the password matches. If the credentials match, the script sets the session and forwards her to the welcome.php page, which acts as her home page. From there, she can log out by clicking a link to the logout.php page. That page removes her session.

6.8.2. Running the Hack

After uploading the files to the server, the first step is to set up the users database:

 % mysqladmin --user=root --password=password create time % mysql --user=root --password=password time < users.sql 

The first command creates the database. The second loads the SQL script into the database, creates the users table, and adds a few accounts.

The next step is to surf over to the index.php page. This should look like Figure 6-15.

Figure 6-15. The login page


To test the login, first try a bad password. Type "jack" into the "User name" field and "hello" as the password; then click on the Login button. The login.php page checks the login, figures out that it's wrong, and forwards you back to the index.php page with the 3 value set to 1. This also brings up red error text, as shown in Figure 6-16.

This time, type "jack" as the username and "toronto" as the password, and click the Login button again. Now the login.php page verifies that the information is correct, and configures your session with the valid user ID. You're then forwarded to the welcome.php page. That page displays your user account and offers you the opportunity to log out, as shown in Figure 6-17.

If you click on the Logout link, the logout.php page will end your session and forward you back to the login page.

Figure 6-16. The login page after a bad username or password


Figure 6-17. The home page after a successful login


You can build your multi-user application on this simple authentication framework by using the welcome.php page as a template for your other pages. When you use this as a starting point for other pages, each page will check to make sure the user is logged in properly and will forward him back to the index.php page if he doesn't have an active session.

6.8.3. See Also

  • "Apply Security by Role" [Hack #58]



PHP Hacks
PHP Hacks: Tips & Tools For Creating Dynamic Websites
ISBN: 0596101392
EAN: 2147483647
Year: 2006
Pages: 163

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net