Effortless e commerce with PHP and MySQL

411 395 0
Effortless e commerce with PHP and MySQL

Đ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

Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL Effortless e commerce with PHP and MySQL

EFFORTLESS E-COMMERCE with PHP and MySQL LARRY ULLMAN Effortless E-Commerce with PHP and MySQL Larry Ullman New Riders 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 (fax) Find us on the Web at: www.newriders.com To report errors, please send a note to: errata@peachpit.com New Riders is an imprint of Peachpit, a division of Pearson Education Copyright © 2011 by Larry Ullman Project Editor: Rebecca Gulick Editor: Robyn G Thomas Technical Reviewer: Jay Blanchard Production Coordinator: Myrna Vladic Compositor: David Van Ness Proofreader: Patricia Pane Cover Designer: Aren Howell Straiger Interior Designer: Terri Bogaards Indexer: Valerie Haynes Perry Notice of Rights All rights reserved No part of this book may be reproduced or transmitted in any form by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher For information on getting permission for reprints and excerpts, contact permissions@peachpit.com Notice of Liability The information in this book is distributed on an “As Is” basis, without warranty While every precaution has been taken in the preparation of the book, neither the author nor Peachpit shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the instructions contained in this book or by the computer software and hardware products described in it Trademarks MySQL is a registered trademark of MySQL AB in the United States and in other countries Macintosh and Mac OS X are registered trademarks of Apple Computer, Inc Microsoft and Windows are registered trademarks of Microsoft Corp This book is not officially endorsed by nor affiliated with any of the above companies, including MySQL AB Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book, and Peachpit was aware of a trademark claim, the designations appear as requested by the owner of the trademark All other product names and services identified throughout this book are used in editorial fashion only and for the benefit of such companies with no intention of infringement of the trademark No such use, or the use of any trade name, is intended to convey endorsement or other affiliation with this book ISBN 13: 978-0-321-65622-3 ISBN 10: 0-321-65622-9 Printed and bound in the United States of America Download from WoweBook.com This book is dedicated to all the friends, family, and coworkers who have been so helpful, supportive, understanding, and generous with their time over the past year and a half It’s a long list, in no particular order: Roxanne, Nicole, Sarah, Meredith, Paula, Barb, Christina, Shirley, Cyndi, Sommar, Brian, Gary, Heather, Rich, Gina, Mike, Kay, Janice, David, and everyone at Peachpit Press Download from WoweBook.com A BUSHEL—THAT’S FOUR WHOLE PECKS—OF THANKS TO… Rebecca, Nancy, and Nancy, for making this project happen And for continuing to work with me time and again Robyn, for managing the project, and for being so pleasant and well organized Jay, for providing a top-notch technical review, and a couple of good jokes, to boot David and Myrna, for magically converting a handful of random materials into something that walks and talks like a book Patricia, for the sharp proofreading eye The indexer, Valerie, who makes it easy for readers to find what they need to know without wading through all of my blather Terri and Aren, for the snazzy interior and cover design work All the readers who requested that I write this book and provided detailed thoughts as to what they would and would not want this book to be I hope it’s what you were looking for! Gary at Kona Earth coffee (www.konaearth.com) for the ton of feedback And for the truly excellent coffee! Templates.com (www.templates.com) and spyka Webmaster (www.spyka.net) for permission to use their templates in the book’s examples Jon, for permission to use his “Architecture by Hand” stencil for some of the book’s figures (www.jonathanbrown.me) Karnesha, for entertaining the kids so that I can get some work done, even if I’d rather not Zoe and Sam, for being the kid epitome of awesomeness Jessica, for doing everything you and everything you can Download from WoweBook.com CONTENTS Introduction xiii What is E-Commerce? xiii About This Book xiv Technologies Used xv Getting Help xv What You’ll Need xv Some Fundamental Skills xvi A Web Server xvi And a Bit More xvi PART ONE: FUNDAMENTALS Chapter 1: Getting Started Identifying Your Business Goals Researching Legal Issues National and International Laws PCI Compliance Choosing Web Technologies Selecting a Web Host Hosting Options My Hosting Recommendation 12 Finding a Good Host 12 Using a Payment System 13 Payment Processors 14 Payment Gateways 15 Which Should You Use? 16 The Development Process 17 Site Planning 18 HTML Design 18 Download from WoweBook.com vi CONTENTS Database Design 19 Programming 21 Testing 22 Going Live 24 Maintaining 24 Improving 25 Chapter 2: Security Fundamentals 26 Security Theory 26 No Web Site Is Secure 27 Maximum Security Isn’t the Goal 28 Security for Customers 29 PCI Requirements 31 Server Security 33 Hosting Implications 33 PHP and Web Security 34 Database Security 36 Secure Transactions 38 Common Vulnerabilities 40 Protecting Information 40 Protecting the User 41 Protecting the Site 42 PART TWO: SELLING VIRTUAL PRODUCTS 47 Chapter 3: First Site: Structure and Design 48 Database Design 49 Server Organization 52 Connecting to the Database 55 The Config File 57 The HTML Template 61 Creating the Header 63 Adding Dynamic Functionality to the Header 64 Download from WoweBook.com CONTENTS vii Creating the Footer 66 Adding Dynamic Functionality to the Footer 68 Creating the Home Page 70 Chapter 4: User Accounts 72 Defining Helper Functions 72 Creating Form Inputs 73 Protecting Passwords 77 Redirecting the Browser 79 Registration 81 Creating the Basic Shell 82 Creating the Form 83 Processing the Form 84 Logging In 91 Processing the Form 91 Creating the Form 94 Logging Out 95 Managing Passwords 96 Recovering Passwords 97 Changing Passwords 100 Improving the Security 104 Chapter 5: Managing Site Content 106 Creating an Administrator 106 Adding Pages 107 Creating the Basic Script 108 Adding a WYSIWYG Editor 112 Displaying Page Content 115 Creating category.php 115 Creating page.php 118 Adding PDFs 121 Setting Up the Server 122 Creating the PHP Script 123 Download from WoweBook.com viii CONTENTS Displaying PDF Content 130 Creating pdfs.php 130 Creating view_pdf.php 132 Chapter 6: Using PayPal 136 About PayPal 136 Payment Solutions 138 Payment Buttons 139 Testing PayPal 140 Registering at the PayPal Sandbox 140 Creating Test Accounts 141 Creating a Button 143 Integrating PayPal 145 Updating the Registration Page 145 Creating thanks.php 146 Creating cancel.php 148 Testing the Site 149 Using IPN 150 Enabling IPN 151 Updating the Registration Script 151 Creating the IPN Script 153 Updating the Thanks Script 157 Renewing Accounts 158 Going Live 159 PART THREE: SELLING PHYSICAL PRODUCTS 161 Chapter 7: Second Site: Structure and Design 162 About the Site 162 What’s Being Sold 163 No Customer Registration 164 Implementing MVC 164 Heightened Security 165 Download from WoweBook.com CONTENTS ix Database Design 166 Product Tables 166 Customer Tables 167 The SQL 169 Server Setup 172 Server Organization 172 Customizing the Server Behavior 173 Helper Files 179 Connecting to the Database 179 The Config File 180 The HTML Template 182 Newer MySQL Features 185 Prepared Statements 186 Stored Procedures 188 Chapter 8: Creating a Catalog 192 Preparing the Database 192 Populating the Tables Using SQL 193 Looking at the Stored Procedure Queries 196 Creating Stored Procedures 201 Shopping by Category 204 Creating the PHP Script 204 Creating the View Files 206 Listing Products 210 Creating the PHP Script 210 Creating the View Files 212 Creating the “No Products” View 216 Indicating Availability 217 Showing Sale Prices 219 Updating the Stored Procedure 220 Updating product_functions.inc.php 222 Updating list_products.html 223 Updating list_coffees.html 224 Download from WoweBook.com 2    Chapter Creating Add to Wish List Links A simple change you could make to the site would be to include Add to Wish List links beside products, just like the Add to Cart links With the wishlist.php script as written, you would just need to create an “add” action conditional, like the one in cart.php Shipping Alternatives Shipping, like the choice of payment processor itself, is such a big topic that I could arguably dedicate an entire chapter to the myriad of ways to handle this part of an order The simplest, but clearly not the best, way to handle shipping is to not charge anything additional at all: Just factor enough profit into each item sold to cover the expense The site that does this will run the risk of losing business to other sites that overtly charge less for the same item, even though those sites will later add in shipping charges Also, this approach would not allow for different shipping options (such as the speed of delivery) or easy adjustments to the cost of shipping as they change over time The second simplest way to calculate shipping is implemented here: a proportional amount dictated by the order total This approach is easy to manage, easy to change, and reasonable, both for the business and for the customer To calculate shipping based on the weight of the order, you’d need to modify the database so that the weight of items is recorded along with the other product details Depending on what you’re selling, you’d be best off representing all weights in the same unit: grams, kilograms, ounces, pounds, what have you The shopping cart would then need to retrieve the weight for each product, generate a weight total, and then calculate the shipping using the total weight On a similar note, you could create an additional shipping cost representative column in the database This could be a column added to the specific products tables (non_coffee_products and specific_coffees, accordingly), in which case there would expect to be a lot of NULL values, which is not ideal Alternatively, you could create a new table that represents each product that has an additional shipping cost as one row: CREATE TABLE `extra_shipping` ( `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, `product_type` ENUM('coffee','other') NOT NULL, `product_id` MEDIUMINT UNSIGNED NOT NULL, `extra_charge` DECIMAL(4,2) UNSIGNED NOT NULL, Download from WoweBook.com Building a Shopping Cart     `date_created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, `date_modified` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), KEY `product_type` (`product_type`,`product_id`), ) ENGINE=MyISAM DEFAULT CHARSET=utf8; Unfortunately, this would mean another table joined into many of the SELECT queries The most complicated way of calculating shipping is based on the distance (and possibly the weight or size as well) To pull this off, you’d need the customer’s postal code and, for international orders, country You would then tie into the system developed by your shipping company of choice For example, UPS and FedEx both have Application Programming Interfaces (APIs) available through which you can get exact prices on shipping based upon the distance, the weight, the size, and the delivery speed These APIs work quite similarly to the payment gateway API For more information, see the documentation for the shipping company of your choosing Improving the Cart Display The success of the site will depend, in some small part, on the user’s reaction to the shopping cart If it’s nice and inviting and makes the customer comfortable, they’re more likely to complete the sale With that in mind, you may want to put some effort into improving that interface For example, you should probably consider creating links from the products in the cart to the product’s image and description in the site Customers often like being able to revisit what they’re buying Second, you could add messages to the cart page to indicate the result of the latest action The message could range from something as simple as “The cart has been updated.” to something more specific like “Mugs::Red Dragon has been removed from your shopping cart.” To this, the HTML view file will need to check for and display a message: if ($message) echo $message; Then the PHP script would assign a value to $message for each action If you want to refer to specific products by name, you’d also need to create a stored procedure that retrieved the product information for a given product type and ID Such a procedure could then be called after an INSERT, UPDATE, or DELETE query is executed Download from WoweBook.com 4    Chapter Tweaking the Database tip On *nix systems, cron can be used to execute a PHP script automatically at periodic intervals Such a script can be used to perform maintenance The foundation of the Web site is the database, so I’d be remiss not to mention alternatives there To start, the system as written will create a lot of flotsam: wish list and shopping cart items never to be purchased You would likely want to create a PHP (or command-line) script that routinely rids the database of old stuff A record is old if its modification date is more than, say, six months old or if its creation date is more than six months old and its modification date is still 0000-00-00 00:00:00, meaning the record had never been updated Second, if you’re using the stored procedures and like how they work, you should probably read up on how to handle errors in stored procedures While not hard to do, the topic is large and technical enough that I had to omit it from the book, lest I took away from the more important points Finally, you could get much better performance from the database by taking advantage of VIEW tables A VIEW table is a memorized SELECT query that you can run other queries on as if it were a real table The syntax for creating a VIEW is: CREATE VIEW view_name AS As an example, the UNION used in the procedures for retrieving every shopping cart or wish list item is quite demanding You could create a VIEW that performs all the JOINs, effectively replacing the product_type and product_id values from the database tables with the actual information you want to display in the Web browser The view would also store the associated user session ID values CREATE VIEW cart_view AS SELECT user_session_id, CONCAT("O", ncp.id) AS sku, c.quantity, ➥ncc.category, ncp.name, ncp.price, ncp.stock, sales.price AS sale_price ➥FROM carts AS c INNER JOIN non_coffee_products AS ncp ON ➥c.product_id=ncp.id INNER JOIN non_coffee_categories AS ncc ON ➥ncc.id=ncp.non_coffee_category_id LEFT OUTER JOIN sales ON ( ➥sales.product_id=ncp.id AND sales.product_type='other' AND ((NOW( ) ➥BETWEEN sales.start_date AND sales.end_date) OR (NOW( ) > ➥sales.start_date AND sales.end_date IS NULL)) ) WHERE ➥c.product_type="other" UNION SELECT user_session_id, ➥CONCAT("C", sc.id), c.quantity, gc.category, CONCAT_WS(" - ", s.size, ➥sc.caf_decaf, sc.ground_whole), sc.price, sc.stock, sales.price FROM ➥carts AS c INNER JOIN specific_coffees AS sc ON c.product_id=sc.id ➥INNER JOIN sizes AS s ON s.id=sc.size_id INNER JOIN general_coffees Download from WoweBook.com Building a Shopping Cart     ➥AS gc ON gc.id=sc.general_coffee_id LEFT OUTER JOIN sales ON ➥(sales.product_id=sc.id AND sales.product_type='coffee' AND ((NOW( ) ➥BETWEEN sales.start_date AND sales.end_date) OR (NOW( ) > ➥sales.start_date AND sales.end_date IS NULL)) ) WHERE ➥c.product_type="coffee"; To be clear, the SELECT…UNION…SELECT query is the same as the one in the get_shopping_cart_contents( ) stored procedure, except that the user_session_id value is now part of the selection, instead of part of the WHERE condition Figure 9.11 shows two SELECT queries run on this VIEW table, with the latter automatically reflecting changes in the carts table (due to customer actions) Figure 9.11 Once this view is defined, the get_shopping_cart_contents( ) query would only need to a SELECT on this one table, with a single condition: matching the user’s session ID: SELECT * FROM cart_views WHERE user_session_id=uid; tip VIEW tables were added to MySQL in version 5.0 Download from WoweBook.com CheCking Out     emailing ReCeipts The final.php script includes email_receipt.php, whose role it is to email a receipt to the customer Because a lot of information could be in this receipt (itemizing multiple products), sending an HTML receipt is a logical choice Considering that some people like HTML email and others don’t, the professional solution is to send an email that’s viewable in either HTML (Figure 10.18) or plain text format (Figure 10.19) That’s what email_receipt.php will Figure 10.18 tip Authorize.net can send out confirmation emails, too, but you cannot control the format as easily Figure 10.19 In theory, you can create a multipart email (one that’s readable in both formats) by just creating the proper body and headers that adhere to the email standard In my experience, that’s much, much easier said than done A better solution is to use a third-party library that will guarantee accurate and reliable results For email_receipt.php, let’s turn to the Zend Framework (http://framework.zend.com) tip You can also use the PEAR Mail_Mime class to send out HTML email Installing the Zend Framework The Zend Framework is created and supported by key PHP developers and has a module for just about anything you’ll want to with PHP The framework is thoroughly documented and well established One of the best features of the framework is that you can use pieces of it as needed, without having to embrace or incorporate the entire library In other words, a site like this one can use just Zend_Mail without the entire site being Zend Framework-based To use the Zend Framework on the site, you’ll need to grab a copy of it first tip If you a lot of PHP development, you ought to be familiar with the Zend Framework, even if you don’t routinely use it Go to http://framework.zend.com Click Downloads > Latest Release On the Latest Release page, download the minimal version Download from WoweBook.com 2    ChapteR 10 The framework can be downloaded directly or by registering with Zend.com first It’s up to you which route you choose The minimal version is an alternative to the full version and includes only the core modules, such as Zend_Mail Expand the downloaded file Depending upon the version you downloaded in Step 3, you’ll either have a zip or a tar.gz archive that needs to be expanded From the expanded framework folder, copy the entire library directory to your Web site’s root directory You won’t actually need the entire Zend Framework library for this site, but there’s no harm in copying it all over Creating the PHP Script The email_receipt.php page has to send out an email available in two versions: plain text and HTML This means the script needs to create two separate email bodies Create a new PHP script in your text editor or IDE to be named email_receipt.php and stored in the includes directory:

Ngày đăng: 19/06/2017, 16:22

Từ khóa liên quan

Mục lục

  • Contents

  • Introduction

    • What is E-Commerce?

    • About This Book

      • Technologies Used

      • Getting Help

      • What You’ll Need

        • Some Fundamental Skills

        • A Web Server

        • And a Bit More

        • PART ONE: FUNDAMENTALS

          • Chapter 1: Getting Started

            • Identifying Your Business Goals

            • Researching Legal Issues

            • Choosing Web Technologies

            • Selecting a Web Host

            • Using a Payment System

            • The Development Process

            • Chapter 2: Security Fundamentals

              • Security Theory

              • PCI Requirements

              • Server Security

              • Secure Transactions

              • Common Vulnerabilities

              • PART TWO: SELLING VIRTUAL PRODUCTS

                • Chapter 3: First Site: Structure and Design

                  • Database Design

                  • Server Organization

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

Tài liệu liên quan