Beginning PHP and MySQL E-Commerce From Novice to Professional phần 5 potx

74 320 0
Beginning PHP and MySQL E-Commerce From Novice to Professional phần 5 potx

Đ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

Catalog Administration: Departments and Categories In the previous chapters, you worked with catalog information that already existed in the database. You have probably inserted some records yourself, or maybe you downloaded the department, category, and product information from this book’s accompanying source code. Obviously, both ways are unacceptable for a real web site, so you need to write some code to allow easy management of your data. That said, the final detail to take care of before launch- ing a web site is to create its administrative interface. Although visitors will never see this part, it’s key to delivering a quality web site to your client. In this chapter and the following one, you implement a catalog administration page. With this feature, you complete the first stage of your web site’s development! Because this page can be implemented in many ways, a serious discussion with the client is required to get the specific list of required features. In our case, we’ll implement a control panel that allows managing the site’s departments, categories, products, and the product attributes. In this chapter, we deal with administering departments and categories, leaving the rest for Chapter 11. More specifically, in this chapter we will create features that allow for • Adding and removing departments • Modifying existing departments’ information (name and description) • Viewing the list of categories that belong to a department • Adding and removing categories • Editing existing categories’ information (name and description) To secure the sensitive pages of your site, such as the administrative section, you’ll also do the following: • Implement a login form where the administrator needs to supply a username and password. • Learn how to secure the login form and the administrative pages using SSL. 267 CHAPTER 10 8644ch10FINAL.qxd 1/30/08 12:32 PM Page 267 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Previewing the Catalog Administration Page Although the long list of objectives might look intimidating at first, they will be easy to imple- ment. We have already covered most of the theory in the previous chapters, but you’ll still learn quite a bit in this chapter. The first step toward creating the catalog administration page is to create a login mecha- nism, which will be implemented as the simple login page that you can see in Figure 10-1. Figure 10-1. The TShirtShop login page Next, you build the management part of the site (commonly referred to as the control panel) by creating its main page (admin.php), its associated template (store_admin.tpl), a main menu template (admin_menu.tpl) used to navigate through different administrative sections that we’ll extend in the next chapters, a componentized template to manage the authentication (admin_login), and two componentized templates for catalog administration (admin_departments and admin_categories). After logging in, the administrator is presented with the list of departments (generated by the admin_departments Smarty template, which is loaded from the main administration page, admin.php), as shown in Figure 10-2. Here, the administrator can • Edit the department’s name or description by clicking the Edit button. • View the categories that belong to a department by clicking the Edit Categories button. • Completely remove a department from the database by clicking the Delete button (this works only if the department has no related categories). CHAPTER 10 ■ CATALOG ADMINISTRATION: DEPARTMENTS AND CATEGORIES268 8644ch10FINAL.qxd 1/30/08 12:32 PM Page 268 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 10-2. The TShirtShop departments Admin page When clicking the Edit button, the corresponding row from the table enters edit mode, and its fields become editable, as shown in Figure 10-3. Also, as you can see, instead of the Edit button, you get Update and Cancel buttons. Clicking Update submits the changes to the database, whereas clicking Cancel simply quits edit mode and reverts the data table to its original state. Figure 10-3. Editing department information CHAPTER 10 ■ CATALOG ADMINISTRATION: DEPARTMENTS AND CATEGORIES 269 8644ch10FINAL.qxd 1/30/08 12:32 PM Page 269 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com The administrator can add new departments by entering the new department’s name and description in the text boxes below the table and clicking the Add button. When the administrator clicks the Edit Categories button, the admin.php page is reloaded with an additional parameter in the query string: DepartmentId. This parameter tells admin.php to load the admin_categories Smarty template, which lets the administrator edit the categories that belong to the selected department (see Figure 10-4). Figure 10-4. The TShirtShop categories Admin page This page works similar to the one for editing departments. You also get a link (“back to departments”) that takes you back to the department’s administration page. The navigation logic among the department, category, and product administration pages is done using query string parameters. As you can see in Figure 10-4, when a department is selected, its ID is appended to the query string. You also used this technique when creating the index.php page. There, you decided which componentized template to load (at runtime) by analyzing the query string parameters. The catalog administration part of the site consists of admin.php and a number of other PHP files and Smarty templates. You’ll build these components one at a time. For each component, you’ll first implement the presentation layer, then write the business tier code, and finally write the data tier methods. You’ll extend the administrative section of the web site in the following chapters. In Chapter 11, you’ll add product administration features, and in later chapters, you’ll implement orders and shopping cart administration features, and you’ll handle your customers’ sensitive data such as credit card data, phone numbers, and so on. CHAPTER 10 ■ CATALOG ADMINISTRATION: DEPARTMENTS AND CATEGORIES270 8644ch10FINAL.qxd 1/30/08 12:32 PM Page 270 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Setting Up the Catalog Administration Page Before building any administrative pages, we need to put in place a security mechanism for restricting the access to these pages. Only authorized personnel should be able to modify the product catalog! Security is obviously a large topic, and its complexity depends a lot on the value of the data you’re protecting. While we don’t have the resources to create such a secure environment as that implemented by banks, for example, when creating an online store, we still have a great responsibility to make sure our data and our customers’ data is safe. Our security implementation deals with these important concepts: • Authentication: This is the process in which users are uniquely identified. The typical way to identify users, which we’ll also implement in TShirtShop, is to ask for a username and a password. • Authorization: This concept refers to the process of identifying the resources an authen- ticated user can access and restricting his or her access accordingly. For example, you can have administrators who can only edit product names and descriptions and admin- istrators who can also view customers’ personal data. The administrators of our little shop will have access to all the restricted areas, but as the site gets larger, you may want to delegate administrative tasks to more employees for both management and security reasons. • Secure communication channel: Of course, all of our authentication and authorization efforts are in vain if it’s easy for a hacker to implement a man-in-the-middle attack, which refers to the scenario where an individual listens to the traffic on a network to intercept sensitive data. Such an attack could be made when an administrator logs in while the attacker listens to the network traffic to intercept the administrator’s username and password. To guard against this potential problem, we use the HTTPS protocol, which encrypts the transmitted data and ensures a degree of confidentiality of the transmission. Using Secure Connections HTTP isn’t a secure protocol, and even if your site protects sensitive areas using passwords (or other forms of authentication), the transmitted data could be intercepted and stolen. To avoid this, you need to set up the application to work with Secure Socket Layer (SSL) connections using the Hypertext Transport Protocol, Secure (HTTPS) protocol. To be able to accept incoming HTTPS connections, a web server must be configured with a security certificate. Security certificates are basically public-private key pairs similar to those used in asynchronous encryption algorithms. You can generate these yourself, but if you’re not a trusted certification authority (such as VeriSign or Thawte), this method may be problematic. Digitally signed SSL certificates that aren’t issued by trusted certification authorities will cause browsers to doubt your security. When a user accesses secure pages whose certificate isn’t issued by a trusted certification authority, the browser will show a warning message. This isn’t disastrous when securing pages that are to be visited by your company personnel but would certainly affect customer confidence if such a warning message shows up, for example, when paying for an order. If you configured your system using XAMPP, as described in Chapter 1, your Apache web server is already configured with a certificate. If you set up Apache on your own, we recommend CHAPTER 10 ■ CATALOG ADMINISTRATION: DEPARTMENTS AND CATEGORIES 271 8644ch10FINAL.qxd 1/30/08 12:32 PM Page 271 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com you check out the article at http://www.sitepoint.com/article/securing-apache-2-server-ssl. For test purposes, you can also get an SSL-enabled Apache version from http://www.devside.net/ web/server/free/download. For a production scenario, you need to buy a trusted certificate through your web hosting company, or, if you manage the web server yourself, obtain a SSL certificate from a known and respected organization that specializes in web security, such as these: • VeriSign (http://www.verisign.com/) • Thawte (http://www.thawte.com/) • InstantSSL (http://www.instantssl.com/) Web browsers have built-in root certificates from organizations such as these and are able to authenticate the digital signature of SSL certificates supplied by them. This means that no warning message will appear, and an SSL-secured connection will be available with a minimum of fuss. For example, when loading such a URL in Opera, a little golden lock shows up next to the address bar. Clicking that symbol shows the name of the company that registered the SSL certificate (see Figure 10-5). Figure 10-5. Verifying a web site certificate in Opera The certificate that we have from XAMPP, issued by the local machine, is not in the list of trusted certificate providers (obviously). With this setup, web browsers will show a warning message, such as the one displayed by Safari shown in Figure 10-6. CHAPTER 10 ■ CATALOG ADMINISTRATION: DEPARTMENTS AND CATEGORIES272 8644ch10FINAL.qxd 1/30/08 12:32 PM Page 272 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 10-6. Safari doesn’t like untrusted certificates. If you click Show Certificate, you can see that the certificate has been issued by localhost for Apache Friends. Apache Friends (http://www.apachefriends.org) is the maker of the XAMPP package. The warning message you get when using an untrusted certificate varies from browser to browser. In Internet Explorer 7, the message is even more obvious (see Figure 10-7). Figure 10-7. Internet Explorer doesn’t like untrusted certificates either. Configuring TShirtShop for SSL If you decide to use SSL, you’ll need to install an SSL certificate, as shown in the next few pages. When using SSL, it’s also advisable to force any sensitive page to be accessed through SSL; that is, if anyone tries accessing a sensitive page (such as the login page) through http://, the request will be automatically redirected to an https:// URL. However, if you want to postpone handling SSL and focus on building the administration pages for the moment, you can. To make the solution configurable, we’ll add a constant named USE_SSL to the include/config.php file. If its value is yes, the secure areas will be forced to be loaded through HTTPS; otherwise, they’ll work via HTTP. CHAPTER 10 ■ CATALOG ADMINISTRATION: DEPARTMENTS AND CATEGORIES 273 8644ch10FINAL.qxd 1/30/08 12:32 PM Page 273 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Obtaining an SSL Certificate Obtaining a certificate is a relatively painless experience. We’re covering here the steps required to get a certificate from VeriSign, but the process is similar with the other providers as well. The full instructions are available on the VeriSign web site (http://www.verisign.com/). You can also get test certificates from VeriSign, which are free to use for a trial period. Here are the basic steps: 1. Sign up for a trial certificate on the VeriSign web site. 2. Generate a Certificate Signing Request (CSR) on your web server. This involves filling out various personal information, including the name of your web site, and so on. For this to work, you need to install an SSL module in your web server, as described in the tutorial at http://www.sitepoint.com/article/securing-apache-2-server-ssl. 3. Copy the contents of the generated CSR into the VeriSign request system. 4. Shortly afterward, you will receive a certificate from VeriSign to copy into your web server to install the certificate. There is a little more to it than that, but as noted previously, detailed instructions are available on the VeriSign web site, and you shouldn’t run into any difficulties. Enforcing SSL Connections After you’ve installed the certificate, you can access any web pages on your web server using an SSL connection, simply by replacing the http:// part of the URL used to access the page with https:// (assuming that your firewall is set up to allow an SSL connection, which by default uses port 443). Obviously, you don’t need SSL connections for all areas of the site. If a page can be accessed only via HTTPS, there are two details to keep in mind: • Search engines don’t index HTTPS locations. • Delivering pages via HTTPS consume web server resources, which must encrypt the transferred data. So you have two solid reasons for which you should enforce HTTPS connections only for the sensitive areas of your site. In this chapter, we’ll enforce SSL for the administrator login page and for the administration pages of your site (in later chapters, when we’ll handle pay- ments ourselves, we’ll also want to enforce SSL for the checkout, customer login, customer registration, and other administrative pages). If you want to ensure that all requests to the administrative script (admin.php) are done through HTTPS, you’ll simply need to add this code at the beginning of presentation/ store_admin.php (we’ll take care of it in an exercise, you don’t need to type it now): // Class constructor public function __construct() { $this->mSiteUrl = Link::Build('', 'https'); CHAPTER 10 ■ CATALOG ADMINISTRATION: DEPARTMENTS AND CATEGORIES274 8644ch10FINAL.qxd 1/30/08 12:32 PM Page 274 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com // Enforce page to be accessed through HTTPS if USE_SSL is on if (USE_SSL == 'yes' && getenv('HTTPS') != 'on') { header ('Location: https://' . getenv('SERVER_NAME') . getenv('REQUEST_URI')); exit(); } } Note that the secure connection isn’t enforced if the USE_SSL constant defined in include/ config.php is set to no. Setting the constant to no may be useful when developing the web site if you don’t have access to a real SSL-enabled server. Authenticating Administrators Because you only want certain users to access the catalog administration page, you need to imple- ment an authentication and authorization mechanism that controls access to the sensitive pages in the site. Users who want to access the catalog administration page should first authenticate themselves. After you know who the user is, you decide whether the user is authorized to access the administration page. At this stage, we’ll only have two kinds of users: anonymous users, who are regular visitors of your site, and administrators, who can access the administrative parts of the site (later in the book, you’ll let visitors create accounts on your web site, but we’re not there yet). In TShirtShop, you’ll use an authentication method called HTTP authentication, which allows you to control the login process through an HTML form. After the client is authenti- cated, we save a cookie on the client and use it to authenticate all subsequent requests. If the cookie is not found, the client is shown the HTML login form. ■Note We assume the administrator accesses the administrative pages from a client that has cookies enabled. The username and password combinations can be physically stored in various ways. For example, in Chapter 16, you’ll see how to store hashed (encrypted) customer passwords in the database. ■Tip Hashing is a common method for storing passwords. The hash value of a password is calculated by applying a mathematical function (hash algorithm) to it. When the user tries to authenticate, the password is hashed, and the resulting hash value is compared to the hash value of the original (correct) password. If the two values are identical, then the entered password is correct. The essential property about the hash algo- rithm is that, theoretically, you cannot obtain the original password from its hash value (the algorithm is one way). In practice, scientists have recently found vulnerabilities with the popular MD5, SHA-0, and SHA-1 hashing algorithms. CHAPTER 10 ■ CATALOG ADMINISTRATION: DEPARTMENTS AND CATEGORIES 275 8644ch10FINAL.qxd 1/30/08 12:32 PM Page 275 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com A more simple method is to store the username and password combination in your PHP file. This method isn’t as flexible as using the database, but it’s fast and easy to implement. When storing the username and password data, you can choose to store the password either in clear text or as hashed text with a hashing algorithm such as MD5 or SHA-1. In the following exercise, you’ll simply store the password in clear text, but it’s good to know you have other options as well. You’ll learn more about hashing in Chapter 16. Exercise: Implementing the Skeleton of the Admin Page 1. Modify the presentation/templates/first_page_contents.tpl file to add a link to the administra- tion page. Note that adding this link is optional, as it only helps with easier access to the page while developing the site. If you decide not to add the link, skip this step and the next one. {* first_page_contents.tpl *} {load_presentation_object filename="first_page_contents" assign="obj"} <p class="description"> We hope you have fun developing TShirtShop, the e-commerce store from Beginning PHP and MySQL E-Commerce: From Novice to Professional! </p> <p class="description"> We have the largest collection of t-shirts with postal stamps on Earth! Browse our departments and categories to find your favorite! </p> <p>Access the <a href="{$obj->mLinkToAdmin}">admin page</a>.</p> {include file="products_list.tpl"} 2. Create a new file named first_page_contents.php in the presentation folder, and add the following code in it. This is necessary for adding the link on the main page to the administration page. <?php class FirstPageContents { public $mLinkToAdmin; public function __construct() { $this->mLinkToAdmin = Link::ToAdmin(); } } ?> 3. Create a new file named admin.php in your site’s root folder (tshirtshop), and write the following code in it. You’ll notice that admin.php is quite similar to index.php, except that in admin.php we don’t check the incoming link using Link::CheckRequest() and that we load a different template file. <?php // Activate session session_start(); CHAPTER 10 ■ CATALOG ADMINISTRATION: DEPARTMENTS AND CATEGORIES276 8644ch10FINAL.qxd 1/30/08 12:32 PM Page 276 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... href="{$obj->mLinkToStoreAdmin}">CATALOG ADMIN | STOREFRONT | LOGOUT | 10 Now, create a new file named admin_menu .php in the presentation folder, and add the following code: < ?php class AdminMenu { public $mLinkToStoreAdmin; public $mLinkToStoreFront; public $mLinkToLogout; public function construct() { $this->mLinkToStoreAdmin... presentation/templates/store_admin.tpl template file, which is loaded from the admin .php file we just created, and add the following code in it: {load_presentation_object filename="store_admin" assign="obj"} Demo Store Admin from Beginning PHP and MySQL E-Commerce... admin .php is the entry point into the administrative part of the site You’ll continue to develop it in the rest of this chapter Studying this file, you can see that it doesn’t have any visual output It just prepares the environment and loads the store_admin Smarty componentized template • store_admin is a componentized template (made of store_admin .php and store_admin.tpl) that is loaded by admin .php to. .. stores the current authentication state in the visitor’s session under a variable named admin_logged In the construct function, we test whether the supplied username and password match the values stored in config .php as ADMIN_USERNAME and ADMIN_PASSWORD; if they match, we set the value of admin_logged to true and redirect to admin .php: 8644ch10FINAL.qxd 1/30/08 12:32 PM Page 2 85 Simpo PDF Merge and. .. $departmentId); // Execute the query and return the results return DatabaseHandler::GetOne($sql, $params); } Implementing the Data Tier You’ll add four stored procedures to the data tier that correspond to the four business tier methods you wrote earlier Let’s see what this is all about Exercise: Adding Data Tier Stored Procedures to the Database 1 Use phpMyAdmin to execute and create the stored procedures described... constant, and the administrator login information at the end of include/config .php If you prefer not to use SSL for now, simply set the USE_SSL constant to no As you can see, the administrator account is named by default tshirtshopadmin, and its password is also tshirtshopadmin In a production scenario, you’ll want to change these values to something less obvious to a potential hacker // We enable and enforce... template generates a list populated with each department’s information, two text boxes, and a button used to add a new department to the list When you click a department’s Edit button, the name and the description of that department become editable, and the Update and Cancel buttons appear in place of the Edit button, as you saw earlier in Figure 10-3 Exercise: Implementing the admin_departments Componentized... form where the administrator can edit the department name and description with Update/Cancel, Edit Categories, and Delete buttons // > {else} and description, and also Edit, Edit Categories, and Delete buttons // > {/if} {/section} By default, the department name and description are not editable, but when you click the Edit button of one department,... Edit Categories buttons The object recognizes which button was clicked and knows what to do after parsing the list of posted variables and reading the clicked button’s name A button named submit_edit_dept_1 tells the presentation object to enter edit mode for the department with a department_id value of 1 Note that with the Add department button, the department’s ID specified in the button name becomes... unsets the admin_logged session variable in store_admin .php and redirects the administrator to admin .php This way, on the next attempt to access the administration page, the administrator will be redirected to the login page // If logging out if (isset ($_GET['Page']) && ($_GET['Page'] == 'Logout')) { unset($_SESSION['admin_logged']); header('Location: ' Link::ToAdmin()); exit(); } Administering Departments . class="description"> We hope you have fun developing TShirtShop, the e-commerce store from Beginning PHP and MySQL E-Commerce: From Novice to Professional! </p> <p class="description"> We. __construct() { $this->mLinkToStoreAdmin = Link::ToAdmin(); $this->mLinkToStoreFront = Link::ToIndex(); $this->mLinkToLogout = Link::ToLogout(); } } ?> 11. Open presentation/link .php file, and modify. intercepted and stolen. To avoid this, you need to set up the application to work with Secure Socket Layer (SSL) connections using the Hypertext Transport Protocol, Secure (HTTPS) protocol. To be able to

Ngày đăng: 12/08/2014, 10:21

Mục lục

  • Beginning PHP and MySQL E-Commerce: From Novice to Professional, Second Edition

  • Contents at a Glance

  • About the Technical Reviewers

  • Introduction

    • Who This Book Is For

    • How This Book Is Structured

      • Phase I of Development

        • Chapter 1: Starting an E-Commerce Site

        • Chapter 2: Laying Out the Foundations

        • Chapter 3: Starting the TShirtShop Project

        • Chapter 4: Creating the Product Catalog: Part 1

        • Chapter 5: Creating the Product Catalog: Part 2

        • Chapter 7: Search Engine Optimization

        • Chapter 8: Searching the Catalog

        • Chapter 9: Receiving Payments Using PayPal

        • Chapter 10: Catalog Administration: Departments and Categories

        • Chapter 11: Catalog Administration: Products and Attributes

        • Phase II of Development

          • Chapter 12: Creating Your Own Shopping Cart

          • Chapter 13: Implementing AJAX Features

          • Chapter 14: Accepting Customer Orders

          • Phase III of Development

            • Chapter 16: Managing Customer Details

            • Chapter 17: Storing Customer Orders

            • Chapter 18: Implementing the Order Pipeline: Part 1

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

  • Đang cập nhật ...

Tài liệu liên quan