Beginning PHP6, Apache, MySQL Web Development- P15 docx

30 417 0
Beginning PHP6, Apache, MySQL Web Development- P15 docx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Chapter 12: User Logins, Profi les, and Personalization 391 You can then navigate to cookies_view.php . This page checks to see if the cookie values are valid. If they are not, it says “ No cookies are set, ” and you can try to set the cookies again. If the cookies were set successfully, then the screen will look like the one in Figure 12 - 17 . The Set Cookies link directs you to cookies_set.php , which does just what the name says: It sets cookie variables named username and remember_me , which are just hard - coded in this example. It then uses a header redirect to send you back to the main test page. Figure 12 - 16 shows cookies_set .php in action. Figure 12-16 c12.indd 391c12.indd 391 12/10/08 6:07:33 PM12/10/08 6:07:33 PM 392 Part II: Comic Book Fan Site Try closing out your browser and then reopening it to visit cookies_view.php again. You ’ ll see that the cookies are still active. The cookies are set to expire 30 days from when they were set. If you want to delete them, you can visit the Delete Cookies link. It calls cookies_delete.php , which expires the cookies by setting their expiration date in the past and blanking out their values. Remember that cookie information is exchanged within HTTP headers; cookies must be sent before the script generates any output. If you look at the documentation for the setcookie() function, you will see that it can accept more arguments than what we ’ ve given it in this simple test. In addition to the information it stores, each cookie has a set of attributes: an expiration date, a valid domain, a valid domain path, and an optional security flag. These attributes help ensure that the browser sends the correct cookie when a request is made to a server. The expiration time is used by the browser to determine when the cookie should be deleted. It is expressed as a UNIX timestamp plus the number of seconds before the cookie expires. Figure 12-17 c12.indd 392c12.indd 392 12/10/08 6:07:33 PM12/10/08 6:07:33 PM Chapter 12: User Logins, Profi les, and Personalization 393 The valid domain is a partial or complete domain name to which the cookie will be sent. For example, if the value for the valid domain attribute is www.example.net , the client will send the cookie information every time the user visits the www.example.net subdomain. For the cookie to be accessible within all subdomains of example.net (such as www.example.net , mail.example.net , news. example.net , users.example.net , etc.), a leading dot should be used, as in .example.net . The path attribute is used to identify sites within various paths in the same domain. For example, cookies with a path attribute of / will be accessible to both users.example.net/~joe and users .example.net/~sally . However, a cookie with a path attribute of /~tom will only be made available to users.example.net/~tom , not users.example.net/~sally . This is good to keep in mind if your site is on a shared server with the same domain name as other sites. The security flag attribute restricts a browser from sending cookie information over unsecured connections. The default value is 0 and allows the cookie to be sent over any type of HTTP connection. It may be set to 1, which will only permit the cookie to be sent over a secure HTTP (HTTPS) connection that utilizes SSL (Secure Socket Layer). Now that you have some cookie knowledge, you can use it in the login system if you want. When written and set appropriately, a cookie will only be sent to the appropriate web site. However, cookie information is still stored on the user ’ s computer in a plaintext format and can be viewed by anyone with access to the local machine. Never use cookies to store sensitive information such as passwords and credit card information, and make sure that any major operation (such as changing a user ’ s preferences or submitting/accessing credit card details) requires the user to enter his or her full password. Administrator Registration In this last portion of the chapter, you learn how logged - in admins can change information and delete information based on their access privileges. In this section, administrators are required to log in before they can view the users signed up in the user registration database. Once they are logged in, only certain privileged admins will be allowed to perform certain operations. For this example: Users with an admin privilege level of 0 are regular users. Users with an admin privilege level of 2 are allowed to update other user accounts, but not delete them. Users with an admin privilege level of 1 are allowed to update and delete other user accounts. This would be useful if a user was, for some reason, unable to log in to the site, and the administrator needed to reset passwords, change usernames, and so on — but you don ’ t want just any administrator to be allowed to do everything the main administrator does. ❑ ❑ ❑ c12.indd 393c12.indd 393 12/10/08 6:07:34 PM12/10/08 6:07:34 PM 394 Part II: Comic Book Fan Site Try It Out Administration Section First, enter the code for all of the pages that are in the following steps. We will explain how they work afterwards. 1. Create the first file, db_ch12 - 2.php : < ?php 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)); // update the user table $query = ‘ALTER TABLE site_user ADD COLUMN admin_level TINYINT UNSIGNED NOT NULL DEFAULT 0 AFTER password’; mysql_query($query, $db) or die (mysql_error($db)); // give one of our test accounts administrative privileges $query = ‘UPDATE site_user SET admin_level = 1 WHERE username = “john”’; mysql_query($query, $db) or die (mysql_error($db)); echo ‘Success!’; ? > 2. Load db_ch12 - 2.php in your browser, and you should see the success message. 3. Modify login.php as shown: < ?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)); // filter incoming values $username = (isset($_POST[‘username’])) ? trim($_POST[‘username’]) : ‘’; $password = (isset($_POST[‘password’])) ? $_POST[‘password’] : ‘’; $redirect = (isset($_REQUEST[‘redirect’])) ? $_REQUEST[‘redirect’] : ‘main.php’; if (isset($_POST[‘submit’])) { $query = ‘SELECT admin_level FROM site_user WHERE ‘ . ‘username = “’ . mysql_real_escape_string($username, $db) . ‘” AND ‘ . ‘password = PASSWORD(“’ . mysql_real_escape_string($password, $db) . ‘”)’; c12.indd 394c12.indd 394 12/10/08 6:07:34 PM12/10/08 6:07:34 PM Chapter 12: User Logins, Profi les, and Personalization 395 $result = mysql_query($query, $db) or die(mysql_error($db)); if (mysql_num_rows($result) > 0) { $row = mysql_fetch_assoc($result); $_SESSION[‘username’] = $username; $_SESSION[‘logged’] = 1; $_SESSION[‘admin_level’] = $row[‘admin_level’]; 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 > ’; mysql_free_result($result); mysql_close($db); die(); } else { // set these explicitly just to make sure $_SESSION[‘username’] = ‘’; $_SESSION[‘logged’] = 0; $_SESSION[‘admin_level’] = 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 > ’; } mysql_free_result($result); } ? > < 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 > c12.indd 395c12.indd 395 12/10/08 6:07:34 PM12/10/08 6:07:34 PM 396 Part II: Comic Book Fan Site < input type=”hidden” name=”redirect” value=” < ?php echo $redirect ? > ”/ > < input type=”submit” name=”submit” value=”Login”/ > < /tr > < /table > < /form > < /body > < /html > < ?php mysql_close($db); ? > 4. Make these changes to main.php : < ?php session_start(); ? > < html > < head > < title > Logged In < /title > < /head > < body > < h1 > Welcome to the home page! < /h1 > < ?php if (isset($_SESSION[‘logged’]) & & $_SESSION[‘logged’] == 1) { ? > < 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 if ($_SESSION[‘admin_level’] > 0) { echo ‘ < p > < a href=”admin_area.php” > Click here < /a > to access your ‘ . ‘administrator tools. < /p > ’; } } else { ? > < 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 } ? > c12.indd 396c12.indd 396 12/10/08 6:07:35 PM12/10/08 6:07:35 PM Chapter 12: User Logins, Profi les, and Personalization 397 5. Create admin_area.php with the following code: < ?php include ‘auth.inc.php’; if ($_SESSION[‘admin_level’] < 1) { header(‘Refresh: 5; URL=user_personal.php’); echo ‘ < p > < strong > < /strong > You are not authorized for this page . < /strong > < /p > ’; echo ‘ < p > You are now being redirected to the main page. If your browser ‘ . ‘doesn\’t redirect you automatically, < a href=”main.php” > click ‘ . ‘here < /a > . < /p > ’; die(); } 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)); ? > < html > < head > < title > Administration Area < /title > < style type=”text/css” > th { background-color: #999;} .odd_row { background-color: #EEE; } .even_row { background-color: #FFF; } < /style > < /head > < body > < h1 > Welcome to the Administration area. < /h1 > < p > Here you can view and manage other users. < /p > < p > < a href=”main.php” > Click here < /a > to return to the home page. < /p > < table style=”width:70%” > < tr > < th > Username < /th > < th > First Name < /th > < th > Last Name < /th > < /tr > < ?php $query = ‘SELECT u.user_id, username, first_name, last_name FROM site_user u JOIN site_user_info i ON u.user_id = i.user_id ORDER BY username ASC’; $result = mysql_query($query, $db) or die(mysql_error($db)); $odd = true; while ($row = mysql_fetch_array($result)) { echo ($odd == true) ? ‘ < tr class=”odd_row” > ’ : ‘ < tr class=”even_row” > ’; $odd = !$odd; echo ‘ < td > < a href=”update_user.php?id=’ . $row[‘user_id’]. ‘” > ’ . $row[‘username’] . ‘ < /a > < /td > ’; c12.indd 397c12.indd 397 12/10/08 6:07:35 PM12/10/08 6:07:35 PM 398 Part II: Comic Book Fan Site echo ‘ < td > ’ . $row[‘first_name’] . ‘ < /td > ’; echo ‘ < td > ’ . $row[‘last_name’] . ‘ < /td > ’; echo ‘ < /tr > ’; } mysql_free_result($result); mysql_close($db); ? > < /table > < /body > < /html > 6. Create the file update_user.php : < ?php include ‘auth.inc.php’; if ($_SESSION[‘admin_level’] < 1) { header(‘Refresh: 5; URL=user_personal.php’); echo ‘ < p > < strong > < /strong > You are not authorized for this page . < /strong > < /p > ’; echo ‘ < p > You are now being redirected to the main page. If your browser ‘ . ‘doesn\’t redirect you automatically, < a href=”main.php” > click ‘ . ‘here < /a > . < /p > ’; die(); } 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’); if (isset($_POST[‘submit’]) & & $_POST[‘submit’] == ‘Update’) { // filter incoming values $username = (isset($_POST[‘username’])) ? trim($_POST[‘username’]) : ‘’; $user_id = (isset($_POST[‘user_id’])) ? $_POST[‘user_id’] : ‘’; $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’])) ? $_POST[‘hobbies’] : array(); // delete user record c12.indd 398c12.indd 398 12/10/08 6:07:35 PM12/10/08 6:07:35 PM Chapter 12: User Logins, Profi les, and Personalization 399 if (isset($_POST[‘delete’])) { $query = ‘DELETE FROM site_user_info WHERE user_id = ‘ . $user_id; mysql_query($query, $db) or die(mysql_error()); $query = ‘DELETE FROM site_user WHERE user_id = ‘ . $user_id; mysql_query($query, $db) or die(mysql_error()); ? > < html > < head > < title > Update Account Info < /title > < /head > < body > < p > < strong > The account has been deleted. < /strong > < /p > < p > < a href=”admin_area.php” > Click here < /a > to return to the admin area. < /a > < /p > < /body > < /html > < ?php die(); } $errors = array(); if (empty($username)) { $errors[] = ‘Username cannot be blank.’; } // check if username already is registered $query = ‘SELECT username FROM site_user WHERE username = “’ . $username . ‘” AND user_id != ‘ . $user_id; $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($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 update the ‘ . ‘account information. < /strong > < /p > ’; echo ‘ < p > Please fix the following: < /p > ’; echo ‘ < ul > ’; c12.indd 399c12.indd 399 12/10/08 6:07:36 PM12/10/08 6:07:36 PM 400 Part II: Comic Book Fan Site foreach ($errors as $error) { echo ‘ < li > ’ . $error . ‘ < /li > ’; } echo ‘ < /ul > ’; } else { // No errors so enter the information into the database. if (!empty($password)) { $query = ‘UPDATE site_user SET password = PASSWORD(“’ . mysql_real_escape_string($password, $db) . ‘”) WHERE user_id = ‘ . $user_id; mysql_query($query, $db) or die(mysql_error()); } $query = ‘UPDATE site_user u, site_user_info SET username = “’ . mysql_real_escape_string($username, $db) . ‘”, first_name = “’ . mysql_real_escape_string($first_name, $db) . ‘”, last_name = “’ . mysql_real_escape_string($last_name, $db) . ‘”, email = “’ . mysql_real_escape_string($email, $db) . ‘”, city = “’ . mysql_real_escape_string($city, $db) . ‘”, state = “’ . mysql_real_escape_string($state, $db) . ‘”, hobbies = “’ . mysql_real_escape_string(join(‘, ‘, $hobbies), $db) . ‘” WHERE u.user_id = ‘ . $user_id; mysql_query($query, $db) or die(mysql_error()); mysql_close($db); ? > < html > < head > < title > Update Account Info < /title > < /head > < body > < p > < strong > The account information has been updated. < /strong > < /p > < p > < a href=”admin_area.php” > Click here < /a > to return to the admin area. < /a > < /p > < /body > < /html > < ?php die(); } } else { $user_id = (isset($_GET[‘id’])) ? $_GET[‘id’] : 0; if ($user_id == 0) { header(‘Location: admin_area.php’); die(); } $query = ‘SELECT c12.indd 400c12.indd 400 12/10/08 6:07:36 PM12/10/08 6:07:36 PM [...]... ‘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)); $sql = ‘CREATE TABLE IF NOT EXISTS cms_access_levels ( access_level TINYINT UNSIGNED NOT NULL AUTO_INCREMENT, access_name VARCHAR(50) NOT NULL DEFAULT “”, PRIMARY KEY (access_level) ) ENGINE=MyISAM’; mysql_ query($sql,... code, and save it as cms_transact_user.php: Update Account Info... ORDER BY comment_date DESC’; $result = mysql_ query($sql, $db) or die (mysql_ error($db)); if ($show_link) { echo ‘’ mysql_ num_rows($result) ‘ Comments’; if (isset($_SESSION[‘user_id’]) and $is_published) { echo ‘ - Add one’; } echo ‘’; } if (mysql_ num_rows($result)) { echo ‘’; while ($row = mysql_ fetch_array($result)) { extract($row);... ORDER BY comment_date DESC’; $result = mysql_ query($sql, $db) or die (mysql_ error($db)); if ($show_link) { echo ‘’ mysql_ num_rows($result) ‘ Comments’; if (isset($_SESSION[‘user_id’]) and $is_published) { echo ‘ - Add one’; } echo ‘’; } if (mysql_ num_rows($result)) { echo ‘’; while ($row = mysql_ fetch_array($result)) { extract($row);... nl2br(htmlspecialchars($article_text)) ‘’; } } mysql_ free_result($result); } function show_comments($db, $article_id, $show_link = TRUE) { if (empty($article_id)) { return; } $sql = ‘SELECT is_published FROM cms_articles WHERE article_id = ‘ $article_id; $result = mysql_ query($sql, $db) or die (mysql_ error($db)); $row = mysql_ fetch_assoc($result); $is_published = $row[‘is_published’]; mysql_ free_result($result); $sql... DEFAULT 1, PRIMARY KEY (user_id) ) ENGINE=MyISAM’; mysql_ query($sql, $db) or die (mysql_ error($db)); $sql = ‘INSERT IGNORE INTO cms_users (user_id, email, password, name, access_level) VALUES 409 c13.indd 409 12/10/08 6:04:27 PM Part II: Comic Book Fan Site (NULL, “admin@example.com”, PASSWORD(“secret”), “Administrator”, 3)’; mysql_ query($sql, $db) or die (mysql_ error($db)); $sql = ‘CREATE TABLE article_id... $show_link = TRUE) { if (empty($article_id)) { return; } $sql = ‘SELECT is_published FROM cms_articles WHERE article_id = ‘ $article_id; $result = mysql_ query($sql, $db) or die (mysql_ error($db)); $row = mysql_ fetch_assoc($result); $is_published = $row[‘is_published’]; mysql_ free_result($result); $sql = ‘SELECT 417 c13.indd 417 12/10/08 6:04:30 PM Part II: Comic Book Fan Site comment_text, UNIX_TIMESTAMP(comment_date)... able to perform such a search, you specified a FULLTEXT INDEX on the title and article_text columns Again, this informs MySQL to track the data in the optimal manner for this application For more information on how MySQL uses indexes, visit http://dev .mysql. com/doc/refman/5.1/ en /mysql- indexes.html Coding for Reusability As you become a more seasoned programmer, you will notice oft-repeated bits of... to work with $query = ‘ALTER TABLE site_user ADD COLUMN admin_level TINYINT UNSIGNED NOT NULL DEFAULT 0 AFTER Password’; mysql_ query($query, $db) or die (mysql_ error($db)); $query = ‘UPDATE site_user SET admin_level = 1 WHERE username = “john”’; mysql_ query($query, $db) or die (mysql_ error($db)); You made changes to main.php so that when the user logs in to the application and views his or her home . ‘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)); ?

Ngày đăng: 03/07/2014, 07:20

Từ khóa liên quan

Mục lục

  • cover.pdf

  • page_c1.pdf

  • page_r01.pdf

  • page_r02.pdf

  • page_r03.pdf

  • page_r04.pdf

  • page_r05.pdf

  • page_r06.pdf

  • page_r07.pdf

  • page_r08.pdf

  • page_r09.pdf

  • page_r10.pdf

  • page_r11.pdf

  • page_r12.pdf

  • page_r13.pdf

  • page_r14.pdf

  • page_r15.pdf

  • page_r16.pdf

  • page_r17.pdf

  • page_r18.pdf

Tài liệu cùng người dùng

Tài liệu liên quan