Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 30 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
30
Dung lượng
700,58 KB
Nội dung
Chapter 12: User Logins, Profi les, and Personalization 361 $_SESSION[‘username’] = $username; $_SESSION[‘logged’] = 1; header (‘Refresh: 5; URL=’ . $redirect); echo ‘ < p > You will be redirected to your original page request. < /p > ’; echo ‘ < p > If your browser doesn\’t redirect you properly ‘ . ‘automatically, < a href=”’ . $redirect . ‘” > click here < /a > . < /p > ’; die(); } else { // set these explicitly just to make sure $_SESSION[‘username’] = ‘’; $_SESSION[‘logged’] = 0; $error = ‘ < p > < strong > You have supplied an invalid username and/or ‘ . ‘password! < /strong > Please < a href=”register.php” > click here ‘ . ‘to register < /a > if you have not done so already. < /p > ’; } } } ? > < html > < head > < title > Login < /title > < /head > < body > < ?php if (isset($error)) { echo $error; } ? > < form action=”login.php” method=”post” > < table > < tr > < td > Username: < /td > < td > < input type=”text” name=”username” maxlength=”20” size=”20” value=” < ?php echo $username; ? > ”/ > < /td > < /tr > < tr > < td > Password: < /td > < td > < input type=”password” name=”password” maxlength=”20” size=”20” value=” < ?php echo $password; ? > ”/ > < /td > < /tr > < tr > < td > < /td > < td > < input type=”hidden” name=”redirect” value=” < ?php echo $redirect ? > ”/ > < input type=”submit” name=”submit” value=”Login”/ > < /tr > < /table > < /form > < /body > < /html > c12.indd 361c12.indd 361 12/10/08 6:07:23 PM12/10/08 6:07:23 PM 362 Part II: Comic Book Fan Site 4. Save the file as login.php . 5. Navigate to the secret.php page you created. Because you haven ’ t logged in yet, the auth.inc.php file you included redirects you to the login.php page, as shown in Figure 12 - 3 . Figure 12-3 6. Try using incorrect login information so you can see how the page works. You will see a screen similar to the one shown in Figure 12 - 4 . c12.indd 362c12.indd 362 12/10/08 6:07:23 PM12/10/08 6:07:23 PM Chapter 12: User Logins, Profi les, and Personalization 363 7. Now, input the correct information: wroxbooks for the username and aregreat for the password. You are redirected to the page you originally requested, because you supplied the correct information. You will see a screen similar to Figure 12 - 5 . Figure 12-4 c12.indd 363c12.indd 363 12/10/08 6:07:24 PM12/10/08 6:07:24 PM 364 Part II: Comic Book Fan Site How It Works The PHP pages you just created are used to authorize a user to view a certain page of your site. When you navigate to secret.php , the included auth.inc.php file checks to see if you have successfully started a session by logging in. If not, you are redirected to the login page. This is the magic line of code that does the checking: if (!isset($_SESSION[‘logged’]) || $_SESSION[‘logged’] != 1) { The $ _SESSION[ ‘ logged ’ ] is the variable you are checking for, and the value 1 is another way of checking for true. Right now, you have a username and password hard - coded into your page. If you want numerous users, you would have to edit your page accordingly and add those values for those users. if (!empty($_POST[‘username’]) & & $_POST[‘username’] == ‘wroxbooks’ & & !empty($_POST[‘password’]) & & $_POST[‘password’] == ‘aregreat’) { This is a very useful way to protect your PHP files to limit use to logged - in users and administrators. However, there is one major drawback that you will resolve later when you integrate the database - driven system: Hard - coded usernames and passwords are only manageable when the number of users Figure 12-5 c12.indd 364c12.indd 364 12/10/08 6:07:24 PM12/10/08 6:07:24 PM Chapter 12: User Logins, Profi les, and Personalization 365 with login information is small. As the number of users grows, the credentials will become more cumbersome and unwieldy to manage. In the next sections, you learn how you can use PHP in conjunction with MySQL to create user - driven login systems. You also learn how to allow for multiple administrators, multiple usernames and passwords, and privilege levels that can be managed with the MySQL database. Using Database - Driven Information Before you can use database - driven logins, you obviously need to have the appropriate tables set up. So first you will create the tables in your MySQL database. You will also add a few sample user accounts for testing purposes. Try It Out Creating the Database Tables 1. Create a new PHP script with the following code: < ?php require ‘db.inc.php’; $db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or die (‘Unable to connect. Check your connection parameters.’); mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db)); // create the user table $query = ‘CREATE TABLE IF NOT EXISTS site_user ( user_id INTEGER NOT NULL AUTO_INCREMENT, username VARCHAR(20) NOT NULL, password CHAR(41) NOT NULL, PRIMARY KEY (user_id) ) ENGINE=MyISAM’; mysql_query($query, $db) or die (mysql_error($db)); // create the user information table $query = ‘CREATE TABLE IF NOT EXISTS site_user_info ( user_id INTEGER NOT NULL, first_name VARCHAR(20) NOT NULL, last_name VARCHAR(20) NOT NULL, email VARCHAR(50) NOT NULL, city VARCHAR(20), state CHAR(2), hobbies VARCHAR(255), FOREIGN KEY (user_id) REFERENCES site_user(user_id) c12.indd 365c12.indd 365 12/10/08 6:07:25 PM12/10/08 6:07:25 PM 366 Part II: Comic Book Fan Site ) ENGINE=MyISAM’; mysql_query($query, $db) or die (mysql_error($db)); // populate the user table $query = ‘INSERT IGNORE INTO site_user (user_id, username, password) VALUES (1, “john”, PASSWORD(“secret”)), (2, “sally”, PASSWORD(“password”))’; mysql_query($query, $db) or die (mysql_error($db)); // populate the user information table $query = ‘INSERT IGNORE INTO site_user_info (user_id, first_name, last_name, email, city, state, hobbies) VALUES (1, “John”, “Doe”, “jdoe@example.com”, NULL, NULL, NULL), (2, “Sally”, “Smith”, “ssmith@example.com”, NULL, NULL, NULL)’; mysql_query($query, $db) or die (mysql_error($db)); echo ‘Success!’; ? > 2. Save the file as db_ch12 - 1.php . 3. Open db_ch12 - 1.php in your web browser. PHP will execute the code to create the tables in your database and then show you the success message if everything goes correctly. How It Works First, you created an administration table named site user . This is where you can keep track of the administrators managing your system. $query = ‘CREATE TABLE IF NOT EXISTS site_user ( user_id INTEGER NOT NULL AUTO_INCREMENT, username VARCHAR(20) NOT NULL, password CHAR(41) NOT NULL, PRIMARY KEY (user_id) ) ENGINE=MyISAM’; mysql_query($query, $db) or die (mysql_error($db)); Then, you created a second table named site_user_info to store additional information about your administrators, such as their names, where they are from, and their hobbies: $query = ‘CREATE TABLE IF NOT EXISTS site_user_info ( user_id INTEGER NOT NULL, first_name VARCHAR(20) NOT NULL, last_name VARCHAR(20) NOT NULL, email VARCHAR(50) NOT NULL, city VARCHAR(20), c12.indd 366c12.indd 366 12/10/08 6:07:25 PM12/10/08 6:07:25 PM Chapter 12: User Logins, Profi les, and Personalization 367 state CHAR(2), hobbies VARCHAR(255), FOREIGN KEY (user_id) REFERENCES site_user(user_id) ) ENGINE=MyISAM’; mysql_query($query, $db) or die (mysql_error($db)); You then added a couple of administrators in your tables, so you can begin to create the registration portion of your PHP code to allow users to register and log in, and update their information or delete their accounts if needed. $query = ‘INSERT IGNORE INTO site_user (user_id, username, password) VALUES (1, “john”, PASSWORD(“secret”)), (2, “sally”, PASSWORD(“password”))’; mysql_query($query, $db) or die (mysql_error($db)); $query = ‘INSERT IGNORE INTO site_user_info (user_id, first_name, last_name, email, city, state, hobbies) VALUES (1, “John”, “Doe”, “jdoe@example.com”, NULL, NULL, NULL), (2, “Sally”, “Smith”, “ssmith@example.com”, NULL, NULL, NULL)’; mysql_query($query, $db) or die (mysql_error($db)); If you looked at the records stored in site_user after running db_ch12 - 1.php , you will have noticed what looks like gibberish stored in the password column. You aren ’ t storing the user ’ s actual password. Rather, you are storing a hash representation of it, by using MySQL ’ s PASSWORD() function. You can think of hashing as a form of one - way encryption. The algorithms that perform the hashing for you are quite complex, and guarantee that every time you hash the same value you will get the same gibberish - looking string as a result. If the input values are off, even ever so slightly, then the result will be wildly different. For example, when you hash the word “ secret ” with the PASSWORD() function, you get * 14E65567ABDB5135D0CFD9A70B3032C179A49EE7 . But if you hash “ Secret ” you get * 0CD5E5F2DE02BE98C175EB67EB906B926F001B9B instead! So how will you verify the user when he or she logs in to your web site and provides a username and password? Simple. Remember, the hash will always be the same for the same value. So all you need to do is take a provided password and hash it with PASSWORD() . Then, if that value matches the value stored in the database, you know the user entered the correct password. You will see this in action shortly. It is a good idea to avoid storing the user ’ s actual password, if you can. This way, if your database were to be compromised, the attacker would be faced with quite a task trying to figure out the users ’ passwords from the hash values. Unlike encryption, hashing is a one - direction - only process. That is, you cannot take a hash value and convert it back to the original value. Once the user has been authenticated, you can again use sessions to track the user and provide access to sensitive sections of your web site. Let ’ s continue forward in building the user login system. c12.indd 367c12.indd 367 12/10/08 6:07:25 PM12/10/08 6:07:25 PM 368 Part II: Comic Book Fan Site Try It Out Session Tracking with PHP and My SQL In this exercise, you create a user login system that uses the database tables you created earlier. You will program it so that the user is required to input a username, password, first name, last name, and e - mail address. The other fields that will be stored in the site_user_info table will be optional. 1. First, create an index page that looks for login information, similar to the one in the previous example, but don ’ t include an authorization page, so that you can show different content based on whether or not the user is logged in. This allows the user the chance to log in, if he or she wishes to. Call this page main.php , and use the following code to create it: < ?php session_start(); ? > < html > < head > < title > Main Page < /title > < /head > < body > < h1 > Welcome to the home page! < /h1 > < ?php if (isset($_SESSION[‘logged’]) & & $_SESSION[‘logged’] == 1) { // user is logged in } else { // user is not logged in } ? > < /body > < /html > 2. Now, modify the main.php file as shown, so you can have different content show up, depending on whether or not a user is logged in. This first branch will be available when the user is logged in, and will contain links to the users ’ own personal area (which you create later), to allow them to update personal information or delete their account entirely. The second branch will simply contain some information about the benefits that registering provides and explain how to go about registering: < ?php session_start(); ? > < html > < head > < title > Main Page < /title > < /head > < body > < h1 > Welcome to the home page! < /h1 > < ?php if (isset($_SESSION[‘logged’]) & & $_SESSION[‘logged’] == 1) { // user is logged in c12.indd 368c12.indd 368 12/10/08 6:07:25 PM12/10/08 6:07:25 PM Chapter 12: User Logins, Profi les, and Personalization 369 ? > < p > Thank you for logging into our system, < b > < ?php echo $_SESSION[‘username’];? > . < /b > < /p > < p > You may now < a href=”user_personal.php” > click here < /a > to go to your own personal information area and update or remove your information should you wish to do so. < /p > < ?php } else { // user is not logged in ? > < p > You are currently not logged in to our system. Once you log in, you will have access to your personal area along with other user information. < /p > < p > If you have already registered, < a href=”login.php” > click here < /a > to log in. Or if you would like to create an account, < a href=”register.php” > click here < /a > to register. < /p > < ?php } ? > < /body > < /html > 3. Create the registration page, making sure you include the optional fields, and that the username chosen by the user registering isn ’ t the same as an existing username. Call it register.php . If users don ’ t fill out some required fields, or use an already registered username, you will notify them and keep what has already been entered in the appropriate fields, so they don ’ t have to reenter everything. < ?php session_start(); include ‘db.inc.php’; $db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or die (‘Unable to connect. Check your connection parameters.’); mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db)); $hobbies_list = array(‘Computers’, ‘Dancing’, ‘Exercise’, ‘Flying’, ‘Golfing’, ‘Hunting’, ‘Internet’, ‘Reading’, ‘Traveling’, ‘Other than listed’); // filter incoming values $username = (isset($_POST[‘username’])) ? trim($_POST[‘username’]) : ‘’; $password = (isset($_POST[‘password’])) ? $_POST[‘password’] : ‘’; $first_name = (isset($_POST[‘first_name’])) ? trim($_POST[‘first_name’]) : ‘’; $last_name = (isset($_POST[‘last_name’])) ? trim($_POST[‘last_name’]) : ‘’; $email = (isset($_POST[‘email’])) ? trim($_POST[‘email’]) : ‘’; $city = (isset($_POST[‘city’])) ? trim($_POST[‘city’]) : ‘’; $state = (isset($_POST[‘state’])) ? trim($_POST[‘state’]) : ‘’; $hobbies = (isset($_POST[‘hobbies’]) & & is_array($_POST[‘hobbies’])) ? c12.indd 369c12.indd 369 12/10/08 6:07:26 PM12/10/08 6:07:26 PM 370 Part II: Comic Book Fan Site $_POST[‘hobbies’] : array(); if (isset($_POST[‘submit’]) & & $_POST[‘submit’] == ‘Register’) { $errors = array(); // make sure manditory fields have been entered if (empty($username)) { $errors[] = ‘Username cannot be blank.’; } // check if username already is registered $query = ‘SELECT username FROM site_user WHERE username = “’ . $username . ‘”’; $result = mysql_query($query, $db) or die(mysql_error()); if (mysql_num_rows($result) > 0) { $errors[] = ‘Username ‘ . $username . ‘ is already registered.’; $username = ‘’; } mysql_free_result($result); if (empty($password)) { $errors[] = ‘Password cannot be blank.’; } if (empty($first_name)) { $errors[] = ‘First name cannot be blank.’; } if (empty($last_name)) { $errors[] = ‘Last name cannot be blank.’; } if (empty($email)) { $errors[] = ‘Email address cannot be blank.’; } if (count($errors) > 0) { echo ‘ < p > < strong style=”color:#FF000;” > Unable to process your ‘ . ‘registration. < /strong > < /p > ’; echo ‘ < p > Please fix the following: < /p > ’; echo ‘ < ul > ’; foreach ($errors as $error) { echo ‘ < li > ’ . $error . ‘ < /li > ’; } echo ‘ < /ul > ’; } else { // No errors so enter the information into the database. $query = ‘INSERT INTO site_user (user_id, username, password) VALUES (NULL, “’ . mysql_real_escape_string($username, $db) . ‘”, ‘ . ‘PASSWORD(“’ . mysql_real_escape_string($password, $db) . ‘”))’; c12.indd 370c12.indd 370 12/10/08 6:07:26 PM12/10/08 6:07:26 PM [...]... = mysql_ connect (MYSQL_ HOST, MYSQL_ USER, MYSQL_ PASSWORD) or die (‘Unable to connect Check your connection parameters.’); mysql_ select_db (MYSQL_ DB, $db) or die (mysql_ error($db)); if (isset($_POST[‘submit’]) && $_POST[‘submit’] == ‘Yes’) { $query = ‘DELETE i FROM site_user u JOIN site_user_info i ON u.user_id = i.user_id WHERE u.username=”’ mysql_ real_escape_string($_SESSION[‘username’], $db) ‘”’; mysql_ query($query,... the username and password against usernames and passwords stored in the MySQL database The necessary changes are highlighted: Personal Info Welcome to your personal information area.... Create the first page, update_account.php, with the following code: . ‘db.inc.php’; $db = mysql_ connect (MYSQL_ HOST, MYSQL_ USER, MYSQL_ PASSWORD) or die (‘Unable to connect. Check your connection parameters.’); mysql_ select_db (MYSQL_ DB, $db) or die (mysql_ error($db)); . ‘db.inc.php’; $db = mysql_ connect (MYSQL_ HOST, MYSQL_ USER, MYSQL_ PASSWORD) or die (‘Unable to connect. Check your connection parameters.’); mysql_ select_db (MYSQL_ DB, $db) or die (mysql_ error($db)); . ‘db.inc.php’; $db = mysql_ connect (MYSQL_ HOST, MYSQL_ USER, MYSQL_ PASSWORD) or die (‘Unable to connect. Check your connection parameters.’); mysql_ select_db (MYSQL_ DB, $db) or die (mysql_ error($db)); ?