PHP for Absolute Beginners PHẦN 9 ppt

41 316 0
PHP for Absolute Beginners PHẦN 9 ppt

Đ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 10  ADDING A COMMENTING SYSTEM TO YOUR BLOG 309 { // If set, store the entry from which we came $loc = isset($_POST['url']) ? $_POST['url'] : ' /'; // If the user clicked "Yes", continue with deletion if($_POST['confirm'] == "Yes") { // Include and instantiate the Comments class include_once 'comments.inc.php'; $comments = new Comments(); // Delete the comment and return to the entry if($comments->deleteComment($_POST['id'])) { header('Location: '.$loc); exit; } // If deleting fails, output an error message else { exit('Could not delete the comment.'); } } // If the user clicked "No", do nothing and return to the entry else { header('Location: '.$loc); exit; } } else { header('Location: /'); exit; } ?> Download at WoweBook.Com CHAPTER 10  ADDING A COMMENTING SYSTEM TO YOUR BLOG 310 At this point, you can delete comments from the database, thus removing them from your entry display. You can test this out by deleting your test comment. Navigate to the entry that you we entered for the comment in a browser, then click the delete link. Next, click Yes to confirm that you want to delete the comment. This takes you back to the entry, but the comment is no longer there. Instead, you see the default message: “There are no comments for this entry” (see Figure 10-6). Figure 10-6. After deleting your test comment, you see this default message Summary In this chapter, you learned how to add an interactive element to your blog by allowing users to comment on your blog entries. In doing so, you also learned a little more about object-oriented programming. In the next chapter, you’ll learn how to build a login system that lets you hide administrative controls from users who aren’t logged in, giving you better control over your blog. Download at WoweBook.Com C H A P T E R 11    311 Adding Password Protection to Administrative Links One of the last things you need to add before you can call your blog “web-ready” is to hide the administrative links from users who aren’t authorized to view them. In this chapter, you’ll learn how to build a system that lets you create administrators and require them to log in with a password before they can create, edit, and delete entries on the blog. Creating this system requires that you master the following tasks: • Adding an admin table to the simple_blog database • Building a function to place administrators in the admin table • Using sessions to hide controls from unauthorized users • Creating a login form that allows administrators to log in to the blog • Writing code to check submitted form data and display its controls if valid Adding an admin Table to the Database Enabling administrators for your site requires that you create a table to store their information. This simple table, admin, stores the following information: • username: The administrator’s login name • password: The administrator’s password Your username needs to be unique, so make it the table’s primary key. Specify both fields as of the VARCHAR type, limit the username to 75 characters, and limit the password to 40 characters. To create the admin table, navigate to http://localhost/phpmyadmin in a browser and open the SQL tab. Enter the following command to create your table: CREATE TABLE simple_blog.admin ( username VARCHAR(75) PRIMARY KEY, password VARCHAR(40) ) Download at WoweBook.Com CHAPTER 11  ADDING PASSWORD PROTECTION TO ADMINISTRATIVE LINKS 312 Adding Administrators in the Database You have a place to store administrators; now you’re ready to start creating them. Your first step is to create a form that allows you to enter a username and password in an HTML form. Once you accomplish this, you need to store the information in the database for later use. Building an HTML Form To build your HTML form, you need to write a new function, named createUserForm(). When called, this function returns a string of HTML that displays a form that asks for a username and password for the new admin. You can add the code in bold to functions.inc.php to make the createUserForm() function: function createUserForm() { return <<<FORM <form action="/simple_blog/inc/update.inc.php" method="post"> <fieldset> <legend>Create a New Administrator</legend> <label>Username <input type="text" name="username" maxlength="75" /> </label> <label>Password <input type="password" name="password" /> </label> <input type="submit" name="submit" value="Create" /> <input type="submit" name="submit" value="Cancel" /> <input type="hidden" name="action" value="createuser" /> </fieldset> </form> FORM; } Next, you need to add code to call this function if the user chooses to create a new admin. Use the http://localhost/simple_blog/admin/createuser URL as your call to create a new admin for your blog. To make this URL call the createUserForm() function, you need to add an if block to admin.php that triggers when the $page variable you use to determine what page is being edited is set to createuser. Next, modify admin.php with the code in bold to incorporate the new form into your blog: <?php /* * Include the necessary files */ Download at WoweBook.Com CHAPTER 11  ADDING PASSWORD PROTECTION TO ADMINISTRATIVE LINKS 313 include_once 'inc/functions.inc.php'; include_once 'inc/db.inc.php'; // Open a database connection $db = new PDO(DB_INFO, DB_USER, DB_PASS); if(isset($_GET['page'])) { $page = htmlentities(strip_tags($_GET['page'])); } else { $page = 'blog'; } if(isset($_POST['action']) && $_POST['action'] == 'delete') { if($_POST['submit'] == 'Yes') { $url = htmlentities(strip_tags($_POST['url'])); if(deleteEntry($db, $url)) { header("Location: /simple_blog/"); exit; } else { exit("Error deleting the entry!"); } } else { header("Location: /simple_blog/blog/$_POST[url]"); } } if(isset($_GET['url'])) { $url = htmlentities(strip_tags($_GET['url'])); // Check if the entry should be deleted if($page == 'delete') { $confirm = confirmDelete($db, $url); } Download at WoweBook.Com CHAPTER 11  ADDING PASSWORD PROTECTION TO ADMINISTRATIVE LINKS 314 // Set the legend of the form $legend = "Edit This Entry"; $e = retrieveEntries($db, $page, $url); $id = $e['id']; $title = $e['title']; $img = $e['image']; $entry = $e['entry']; } else { // Check if we're creating a new user if($page == 'createuser') { $create = createUserForm(); } // Set the legend $legend = "New Entry Submission"; // Set the variables to null if not editing $id = NULL; $title = NULL; $img = NULL; $entry = NULL; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <link rel="stylesheet" href="/simple_blog/css/default.css" type="text/css" /> <title> Simple Blog </title> </head> <body> <h1> Simple Blog Application </h1> Download at WoweBook.Com CHAPTER 11  ADDING PASSWORD PROTECTION TO ADMINISTRATIVE LINKS 315 <?php if($page == 'delete'): { echo $confirm; } elseif($page == 'createuser'): { echo $create; } else: ?> You are now able to navigate to http://localhost/simple_blog/admin/createuser and see your form (see Figure 11-1). Figure 11-1. The form you use to create site administrators Saving New Administrators in the Database You submit your form to update.inc.php with a hidden input named action that sends the value, createuser. To store administrators created through your createUserForm() HTML form, you need to modify update.inc.php to catch form information with an action of createuser. Download at WoweBook.Com CHAPTER 11  ADDING PASSWORD PROTECTION TO ADMINISTRATIVE LINKS 316 You need to prepare an SQL statement that places the username and password into the admin table. Do this after you ensure that the form was sent using the POST method, that the action is set to createuser, and that the username and password inputs were not submitted with empty values. Dealing with Passwords You need to take extra precautions now that you’re dealing with passwords. Passwords are sensitive information, and you do not want to store a password as plain text in the database. Fortunately, both PHP and MySQL provide means for encrypting strings. For the blog, you can use SHA1(), which is a basic encryption algorithm. Calling SHA1() on a string returns a 40-character string that is difficult to decode. Note For more information on encrypting passwords, look up the PHP manual entries on md5() and sha1(). Saving the Admin To save the admin information, you need to include the database credentials and open a new connection to your database. The SQL statement you use for this is a standard insert, except that you need to use MySQL’s built-in support for creating SHA1 hashes. After you insert the new entry into the table, you send the user back to the default blog home page. In update.inc.php, insert the following code in bold just before the last else block: // If an admin is being created, save it here else if($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['action'] == 'createuser' && !empty($_POST['username']) && !empty($_POST['password'])) { // Include database credentials and connect to the database include_once 'db.inc.php'; $db = new PDO(DB_INFO, DB_USER, DB_PASS); $sql = "INSERT INTO admin (username, password) VALUES(?, SHA1(?))"; $stmt = $db->prepare($sql); $stmt->execute(array($_POST['username'], $_POST['password'])); header('Location: /simple_blog/'); exit; } Download at WoweBook.Com CHAPTER 11  ADDING PASSWORD PROTECTION TO ADMINISTRATIVE LINKS 317 else { header('Location: /'); exit; } ?> You can now save new administrators to your admin table. Navigate to http://localhost/ simple_blog/admin/createuser in a browser and create a new user with the username of admin and the password of admin. Now click the Create button, navigate to http://localhost/phpmyadmin in a browser, select the simple_blog database and the admin table, then click the Browse tab. Your administrator is now saved in the table, and the password is saved as an encrypted hash (see Figure 11-2). Figure 11-2. Your first administrator Download at WoweBook.Com CHAPTER 11  ADDING PASSWORD PROTECTION TO ADMINISTRATIVE LINKS 318 Hiding Controls from Unauthorized Users You can use sessions to keep track of which users are authorized to view administrative links on your blog. A session allows the user to log in once, then navigate anywhere on the site without losing his administrative privileges. Note For a refresher on how sessions work, refer to the section on sessions in Chapter 3. Your first task is to wrap all administrative links in an if block; this ensures that a session variable is set for the current user. Call your session variable loggedin and store it in the $_SESSION['loggedin'] string. Modifying index.php Your next task is to hide all the admin links in index.php from unauthorized users. You need to enable sessions, which you can accomplish in a couple steps: call session_start(), then wrap all the admin links in your check for the $_SESSION[‘loggedin’] variable. Now modify index.php with the code in bold to make your changes: <?php session_start(); /* * Include the necessary files */ include_once 'inc/functions.inc.php'; include_once 'inc/db.inc.php'; // Open a database connection $db = new PDO(DB_INFO, DB_USER, DB_PASS); // Figure out what page is being requested (default is blog) if(isset($_GET['page'])) { $page = htmlentities(strip_tags($_GET['page'])); } else { $page = 'blog'; } Download at WoweBook.Com [...]... 'delete'=>NULL); } // Format the image if one exists $img = formatImage($e['image'], $e['title']); if($page=='blog') { // Load the comment object include_once 'inc/comments.inc .php' ; $comments = new Comments(); $comment_disp = $comments->showComments($e['id']); $comment_form = $comments->showCommentForm($e['id']); } else { $comment_form = NULL; } ?> < ?php echo $e['title'] ?> < ?php echo $img,... End the if statement // If the full display flag is 0, format linked entry titles else { // Loop through each entry foreach($e as $entry) { ?> < ?php echo $entry['title'] ?> < ?php } // End the foreach loop } // End the else ?> < ?php if($page=='blog' && isset($_SESSION['loggedin']) &&... $e['entry'] ?> < ?php echo $admin['edit'] ?> < ?php if($page=='blog') echo $admin['delete'] ?> 320 Download at WoweBook.Com CHAPTER 11 ADDING PASSWORD PROTECTION TO ADMINISTRATIVE LINKS < ?php if($page=='blog'): ?> Back to Latest Entries Comments for This Entry < ?php echo $comment_disp, $comment_form; endif; ?> < ?php } // End the if statement... NULL; // Load the comments for the entry $this->retrieveComments($blog_id); // Loop through the stored comments foreach($this->comments as $c) { // Prevent empty fields if no comments exist if(!empty($c['date']) && !empty($c['name'])) { // Outputs similar to: July 8, 20 09 at 4:39PM $format = "F j, Y \a\\t g:iA"; // Convert $c['date'] to a timestamp, then format $date = date($format, strtotime($c['date']));... to place your login form is at http://localhost/simple_blog/admin For the moment, admin .php shows a blank page if the user hasn’t logged in because authorization is required before the page will do anything at all You can fix that by placing the login form at the bottom of admin .php, inside an else block Doing so shows a login screen to anyone who isn’t logged in already Your login form requests a username... ADMINISTRATIVE LINKS < ?php echo $legend ?> Title Image Entry < ?php echo $entry ?>... PROTECTION TO ADMINISTRATIVE LINKS Modifying admin .php None of the actions performed by this page should be available to unauthorized users, so you want to require authorization before any of the functionality of admin .php can be accessed Doing this is as simple as wrapping the entire page in a conditional statement Modify admin .php by adding the code in bold: < ?php session_start(); // If the user is logged... "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> Please Log In Please Log In... method to send this information to update.inc .php, along with a hidden input named action that passes the value, login 328 Download at WoweBook.Com CHAPTER 11 ADDING PASSWORD PROTECTION TO ADMINISTRATIVE LINKS At the bottom of admin .php, just after the closing tag, modify the file with the code in bold: < ?php /* * If we get here, the user is not logged in Display a form * and ask them... rows="10">< ?php echo $entry ?> < ?php endif; ?> < ?php endif; // Ends the section available to logged in users ?> At this point, . bold to functions.inc .php to make the createUserForm() function: function createUserForm() { return <<<FORM <form action="/simple_blog/inc/update.inc .php& quot; method="post">. your HTML form, you need to write a new function, named createUserForm(). When called, this function returns a string of HTML that displays a form that asks for a username and password for the. create a form that allows you to enter a username and password in an HTML form. Once you accomplish this, you need to store the information in the database for later use. Building an HTML Form

Ngày đăng: 12/08/2014, 16:20

Từ khóa liên quan

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

Tài liệu liên quan