Tải bản đầy đủ (.pdf) (819 trang)

beginning php5 apache and mysql web development

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (13.7 MB, 819 trang )

Beginning PHP5, Apache, and
MySQL
®
Web Development
Elizabeth Naramore, Jason Gerner, Yann Le Scouarnec,
Jeremy Stolz, Michael K. Glass
01_579665 ffirs.qxd 12/30/04 8:08 PM Page iii
01_579665 ffirs.qxd 12/30/04 8:08 PM Page ii
Beginning PHP5, Apache, and
MySQL
®
Web Development
01_579665 ffirs.qxd 12/30/04 8:08 PM Page i
01_579665 ffirs.qxd 12/30/04 8:08 PM Page ii
Beginning PHP5, Apache, and
MySQL
®
Web Development
Elizabeth Naramore, Jason Gerner, Yann Le Scouarnec,
Jeremy Stolz, Michael K. Glass
01_579665 ffirs.qxd 12/30/04 8:08 PM Page iii
Beginning PHP5, Apache, and MySQL
®
Web Development
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2005 by Wiley Publishing, Inc., Indianapolis, Indiana


Published simultaneously in Canada
ISBN: 0-7645-7966-5
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
1B/SQ/QR/QV/IN
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form
or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as
permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior
written permission of the Publisher, or authorization through payment of the appropriate per-copy fee
to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978)
646-8600. Requests to the Publisher for permission should be addressed to the Legal Department,
Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317)
572-4355, e-mail:
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR
MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR
COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL
WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTIC-
ULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMO-
TIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE
SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT
THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PRO-
FESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A
COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR
THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN
ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A
POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR
THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY
PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE
THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED
BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.

For general information on our other products and services or to obtain technical support, please
contact our Customer Care Department within the U.S. at (800) 762-2974, outside the U.S. at (317)
572-3993 or fax (317) 572-4002.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print
may not be available in electronic books.
Library of Congress Cataloging-in-Publication Data available from the publisher.
Trademarks: Wiley, the Wiley Publishing logo, Wrox, the Wrox logo, Programmer to Programmer, and
related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affil-
iates, in the United States and other countries, and may not be used without written permission.
MySQL is a registered trademark of MySQL AB Limited Company. All other trademarks are the prop-
erty of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor
mentioned in this book.
01_579665 ffirs.qxd 12/30/04 8:08 PM Page iv
About the Authors
Elizabeth Naramore
Elizabeth graduated from Miami University (Ohio) with a degree in Organizational Behavior and has
been a Web developer since 1997. Her main focus is in e-commerce, but she develops sites across numer-
ous industries. She is currently a moderator at PHPBuilder.com, an online help center for PHP. She lives
in Cincinnati, Ohio with her husband and two children, and looks forward to someday returning to
Miami to get her Masters in Computer Science.
Thanks to my husband and soul mate who continues to be supportive of everything I do, and who
inspires me to always do a little better. Thanks to my children who make me understand the importance
of looking outside the box and keeping my sense of humor, and for making me proud to be a mom. Also,
thank you to Debra for always keeping us on track, and for having faith in us.
Jason “goldbug” Gerner
Jason currently spends his days working as a Web developer in Cincinnati and burns free time com-
plaining about lack of support for Web standards and abusing XML. He can often be found lurking in
the PHPBuilder.com discussion forums, waiting to chime in with nagging comments about CSS or code
efficiency.
Yann “Bunkermaster” Le Scouarnec

Yann is the senior developer for Jolt Online Gaming, a British gaming company. He is a moderator at
PHPBuilder.com and a developer of open source PHP software for the gaming community. He has also
worked for major software corporations as a software quality expert.
I thank all the innocent bystanders who got pushed around because of this project: Debra and Nancy,
who were patient enough not to have homicidal thoughts; and my wife and kids, who barely saw me for
six months.
Jeremy “stolzyboy” Stolz
Jeremy is a Web Developer at J&M Companies, Inc. (www.jmcompanies.com), a print company in Fargo,
North Dakota. Jeremy is primarily a PHP/MySQL developer, but he has also worked with many other
languages. When not working, he frequents the Internet and tries to keep his programming skills sharp
and up to date. He is a contributor to and moderator at PHPBuilder.com.
I’d like to thank my wife, my baby daughter, and the rest of my family for being patient with me while working on
this project.
01_579665 ffirs.qxd 12/30/04 8:08 PM Page v
Michael “BuzzLY” Glass
Michael Glass has been a gladiator in the software/Web site development arena for more than eight
years. He has more than ten years of commercial programming experience with a wide variety of tech-
nologies, including PHP, Java, Lotus Domino, and Vignette StoryServer. He divides his time between
computer programming, playing pool in the APA, and running his Web site at
www.ultimatespin.com.
You can usually find him slinking around on the PHPBuilder.com forums, where he is a moderator with
the nickname BuzzLY.
Thanks, Staci, for putting up with long and late hours at the computer. Elizabeth and Jason,
it wouldn’t have been the same project without you two. And thanks to my code testers at
www.ultimatespin.com: Spidon, Kaine, Garmy, Spidermanalf, Ping, Webhead, and FancyDan. You
guys rock!
To Donna and Gerry, who have influenced my life more than they can ever know, and who taught me
the importance of finishing what you’ve started.
01_579665 ffirs.qxd 12/30/04 8:08 PM Page vi
Credits

Acquisitions Editor
Debra Williams Cauley
Development Editor
Brian MacDonald
Senior Production Editor
Angela Smith
Technical Editor
Jason Gerner
Copy Editor
Kim Cofer
Editorial Manager
Mary Beth Wakefield
Vice President & Executive Group Publisher
Richard Swadley
Vice President and Publisher
Joseph B. Wikert
Project Coordinator
Erin Smith
Graphics and Production Specialists
Carrie A. Foster
Denny Hager
Jennifer Heleine
Quality Control Technician
Brian H. Walls
Proofreading and Indexing
TECHBOOKS Production Services
01_579665 ffirs.qxd 12/30/04 8:08 PM Page vii
01_579665 ffirs.qxd 12/30/04 8:08 PM Page viii
Contents
Part I: Getting Started 1

Chapter 1: Configuring Your Installation 3
Projects in This Book 3
Brief Intro to PHP, Apache, MySQL, and Open Source 4
A Brief History of Open Source Initiatives 4
Why Open Source Rocks 4
How the Pieces of the AMP Module Work Together 5
Apache 6
PHP 6
MySQL 7
AMP Installers 8
Foxserv 8
PHPTriad 8
XAMPP 8
Configuring Your Apache Installation 8
Testing Your Installation 9
Customizing Your Installation 10
Adding PHP to the Equation 10
Document Root 11
Configuring Your PHP Installation 13
Testing Your Installation 13
Customizing Your Installation 14
Configuring PHP5 to Use MySQL 16
Configuring Your MySQL Installation 17
Testing Your Installation 17
Configuring Your Installation 19
The my.cnf File 21
Setting Up Users and Privileges 24
Where to Go for Help and Other Valuable Resources 25
Help within the Programs 25
Source Web Sites 25

Summary 26
02_579665 ftoc.qxd 12/30/04 8:09 PM Page ix
x
Contents
Part II: Movie Review Web Site 27
Chapter 2: Creating PHP Pages Using PHP5 29
Overview of PHP Structure and Syntax 30
How PHP Fits with HTML 30
The Rules of PHP Syntax 30
The Importance of Coding Practices 31
What Makes a Great Program? 32
Why Should You Care about What Your Code Looks Like? 32
Creating Your First Program 33
Using HTML to Spice Up Your Pages 34
Integrating HTML with PHP 34
Considerations with HTML Inside PHP 36
Using Constants and Variables to Add Functionality 37
Overview of Constants 37
Overview of Variables 38
Passing Variables between Pages 40
A Word about register_globals 41
Passing Variables through a URL 42
Special Characters in URLs 45
Passing Variables with Sessions 47
Passing Variables with Cookies 49
Passing Information with Forms 53
Fast Primer on Forms 53
Using if/else Arguments 57
Using if Statements 57
Operators 57

Special Syntax Considerations 58
Using if and else Together 59
Using Includes for Efficient Code 60
Using Functions for Efficient Code 62
All About Arrays 67
Array Syntax 67
Sorting Arrays 69
foreach Constructs 69
While You’re Here . . . 74
Alternate Syntax for PHP 78
Alternates to the <?php and ?> Tags 78
Alternates to the echo Command 78
Alternates to Logical Operators 79
02_579665 ftoc.qxd 12/30/04 8:09 PM Page x
xi
Contents
Alternates to Double Quotes: Using heredoc 79
Alternates to Incrementing/Decrementing Values 79
OOP Dreams 79
A Brief OOP Example 80
Why Use OOP? 82
Summary 82
Exercises 82
Chapter 3: Using PHP5 with MySQL 85
Overview of MySQL Structure and Syntax 85
MySQL Structure 86
Field Types 86
Choosing the Right Field Type 88
null/not null 89
Indexes 90

Unique 90
Auto Increment 90
Other Parameters 91
Types of MySQL Tables and Storage Engines 91
MySQL Syntax and Commands 92
How PHP Fits with MySQL 92
Connecting to the MySQL Server 93
Looking at a Ready-Made Database 94
Querying the Database 99
WHERE, oh WHERE 99
Working with PHP and Arrays of Data: foreach 102
A Tale of Two Tables 104
Referencing Two Tables 105
Joining Two Tables 107
Helpful Tips and Suggestions 109
Documentation 109
Using PHPMyAdmin 109
Summary 110
Exercises 110
Chapter 4: Using Tables to Display Data 111
Creating a Table 111
Populating the Table 114
Who’s the Master? 120
02_579665 ftoc.qxd 12/30/04 8:09 PM Page xi
xii
Contents
A Lasting Relationship 128
Summary 134
Exercises 134
Chapter 5: Form Elements: Letting the User Work with Data 135

Your First Form 136
FORM Element 138
INPUT Element 139
Processing the Form 140
Driving the User Input 141
INPUT Checkbox Type 143
One Form, Multiple Processing 144
Radio INPUT Element 148
Multiple Submit Buttons 149
Basic Input Testing 149
Dynamic Page Title 149
Manipulating a String as an Array to Change the Case of the First Character 150
Ternary Operator 150
Using Form Elements Together 150
The Skeleton Script 159
Default Response 159
Adding Items 159
Summary 160
Exercises 161
Chapter 6: Letting the User Edit the Database 163
Preparing the Battlefield 163
Inserting a Simple Record from phpMyAdmin 166
Inserting a Record in a Relational Database 170
Deleting a Record 178
Editing Data in a Record 183
Summary 191
Exercise 191
Chapter 7: Manipulating and Creating Images with PHP 193
Working with the GD Library 193
What File Types Can I Use with GD and PHP? 194

Compiling PHP with GD 194
Allowing Users to Upload Images 196
02_579665 ftoc.qxd 12/30/04 8:09 PM Page xii
xiii
Contents
Converting Image File Types 203
Black and White 208
Adding Captions 214
Adding Watermarks and Merging Images 218
Creating Thumbnails 220
Summary 225
Exercises 225
Chapter 8: Validating User Input 227
Users Are Users Are Users . . . 227
Incorporating Validation into the Movie Site 228
Forgot Something? 229
Checking for Format Errors 239
Summary 250
Exercise 250
Chapter 9: Handling and Avoiding Errors 251
How the Apache Web Server Deals with Errors 251
Apache’s ErrorDocument Directive 252
Apache’s ErrorDocument: Advanced Custom Error Page 256
Error Handling and Creating Error Handling Pages with PHP 260
Error Types in PHP 260
Generating PHP Errors 261
Other Methods of Error Handling 269
Exceptions 269
Not Meeting Conditions 271
Parse Errors 272

Summary 272
Exercises 272
Part III: Comic Book Fan Site 273
Chapter 10: Building Databases 275
Getting Started 275
What Is a Relational Database? 276
Keys 277
Relationships 277
Referential Integrity 278
Normalization 278
02_579665 ftoc.qxd 12/30/04 8:09 PM Page xiii
xiv
Contents
Designing Your Database 279
Creating the First Table 279
What’s So Normal About These Forms? 283
Standardization 283
Finalizing the Database Design 284
Creating a Database in MySQL 285
Creating the Comic Character Application 290
charlist.php 316
charedit.php 320
Summary 323
Exercises 324
Chapter 11: Sending E-mail 325
Setting Up PHP to Use E-mail 325
Sending an E-mail 326
Dressing Up Your E-mails with HTML 331
Multipart Messages 334
Storing Images 337

Getting Confirmation 339
Creating a Reusable Mail Class 355
Summary 362
Exercises 363
Chapter 12: User Logins, Profiles, and Personalization 365
The Easiest Way to Protect Your Files 365
Friendlier Logins Using PHP’s Session and Cookie Functions 370
Using Database-Driven Information 375
Using Cookies in PHP 399
Administrator Registration 402
Summary 413
Exercises 413
Chapter 13: Building a Content Management System 415
Getting Your Users to Return 415
Content 415
Management 416
System 416
Putting It All Together 416
Preparing the Database 417
02_579665 ftoc.qxd 12/30/04 8:09 PM Page xiv
xv
Contents
Coding for Reusability 422
outputfunctions.php 426
header.php 429
http.php 431
Transaction Pages 431
User Interface 444
General Functionality 444
User Management 454

Article Publishing 458
Additional CMS Features 472
Summary 479
Exercises 479
Chapter 14: Mailing Lists 481
What Do You Want to Send Today? 481
Coding the Administration Application 482
Sign Me Up! 497
user.php 504
user_transact.php 505
thanks.php 509
Mailing List Ethics 514
A Word About Spam 514
Opt-In versus Opt-Out 514
Summary 515
Exercises 515
Chapter 15: Online Stores 517
Adding E-Commerce to the Comic Book Fan Site 518
Something to Sell 518
A Shopping Cart 519
Shopping Cart Software 519
Your Own Cart Software Code 519
E-Commerce, Any Way You Slice It 559
Information Is Everything 560
Importance of Trust 560
Privacy Policy 561
Return Policy 561
Warm Bodies 561
Secure Credit Card Processing 561
Professional Look 562

02_579665 ftoc.qxd 12/30/04 8:09 PM Page xv
xvi
Contents
Easy Navigation 562
Common Links 562
Search Function 562
Typical Design 562
Competitive Pricing 562
Appropriate Merchandise 563
Timely Delivery 563
Communication 563
Customer Feedback 563
Summary 564
Exercises 564
Chapter 16: Creating a Bulletin Board System 567
Your Bulletin Board 567
Preparing the Database 569
Reusable Code 577
Pagination 586
Breadcrumbs 590
A Last Look at User Authentication 592
Transaction Pages 593
Account Functionality 604
User Administration 617
Forum Functionality 618
Board Administration 622
Forum Administration 623
BBcode Administration 624
Regular Expressions 624
The Two Types of regex Functions 624

How to Write a PCRE regex 625
Searching 636
Afterthoughts 638
Summary 639
Exercises 639
Chapter 17: Using Log Files to Improve Your Site 641
Locating Your Logs 642
Apache 642
PHP 644
MySQL 644
02_579665 ftoc.qxd 12/30/04 8:09 PM Page xvi
xvii
Contents
Analyzing Your Log Data 646
Webalizer 646
Analog 647
WebTrends 648
AWStats 649
HTTP Analyze 650
Putting the Analysis to Work 651
Site Health 651
User Preferences and Information 651
Number of Hits and Page Views 651
Trends over Time 652
Referring Sites 652
Summary 652
Chapter 18: Troubleshooting 653
Installation Troubleshooting 653
Parse Errors 653
Cleanup on Line 26 . . . Oops, I Mean 94 654

Elementary, My Dear Watson! 654
Empty Variables 655
The Ultimate Bait-and-Switch 655
Consistent and Valid Variable Names 656
Open a New Browser 656
“Headers Already Sent” Error 657
General Debugging Tips 658
Using echo 658
Divide and Conquer 659
Test, Test, Test! 659
Where to Go for Help 659
www.wrox.com 659
PHPBuilder.com 659
Source Web Sites 660
Search and Rescue 660
IRC Channels 660
Summary 660
02_579665 ftoc.qxd 12/30/04 8:09 PM Page xvii
xviii
Contents
Appendix A: Answers to Exercises 661
Appendix B: PHP Quick Reference 703
Appendix C: PHP5 Functions 707
Appendix D: MySQL Data Types 747
Appendix E: MySQL Quick Reference 751
Appendix F: Comparison of Text Editors 755
Appendix G: Choosing a Third-Party Host 759
Appendix H: An Introduction to PEAR 763
Appendix I: AMP Installation 771
Index 777

02_579665 ftoc.qxd 12/30/04 8:09 PM Page xviii
Part I: Getting Started
Chapter 1: Configuring Your Installation
03_579665 pt01.qxd 12/30/04 8:09 PM Page 1
03_579665 pt01.qxd 12/30/04 8:09 PM Page 2
1
Configuring Your
Installation
You’ve spent your hard-earned money and purchased this book, so you undoubtedly know the
enormous benefits of using PHP, Apache, and MySQL together to create your Web site. But in case
you found this book on your desk one Monday morning with a sticky note reading “Learn this!,”
this chapter looks at the basics of PHP, MySQL, and Apache to show you what makes the “AMP”
combination so popular. This chapter also walks you through the procedure for installing all three
components of the AMP module and advises you on how to best configure the software to meet
your specific needs.
Projects in This Book
Over the course of this book, you will develop two complete Web sites:
❑ Movie Review Web site. Developing this site introduces you to writing a PHP program,
making your pages look professional, working with variables and includes, and integrat-
ing PHP with MySQL to make your site truly dynamic as pages are created on the fly for
your Web site visitor. You will also get experience in error handling and data validation
while working on this site.
❑ Comic Book Fan Web site. The creation of this Web site takes you through the steps of
building databases from scratch, manipulating images and sending out e-mails using
PHP, authenticating users, managing content through CMS, creating a mailing list, setting
up an e-commerce section, and developing and customizing a discussion forum.
Finally, this book covers how to learn about your visitors through the use of log files and how to
troubleshoot common mistakes or problems. The appendixes in this book provide you with the
necessary reference materials you’ll need to assist you in your Web site development journey and
offer tools to make you more efficient.

04_579665 ch01.qxd 12/30/04 8:09 PM Page 3
After reading this book, you will be able to create a well-designed, dynamic Web site using tools avail-
able for free. Although this book is not intended to be a detailed analysis of Apache, PHP, and MySQL, it
points you in the right direction to explore further issues you may wish to delve into.
Brief Intro to PHP, Apache,
MySQL, and Open Source
PHP, Apache, and MySQL are all part of the open source group of software programs. The open source
movement is a collaboration of some of the finest minds in computer programming. By allowing the
open exchange of information, programmers from all over the world contribute to make a truly power-
ful and efficient piece of software available to everyone. Through the contributions of many people to
the publicly available source code, bugs get fixed, improvements are made, and a good software pro-
gram becomes a great one over time.
A Brief History of Open Source Initiatives
The term open source was coined in 1998 after Netscape decided to publish the source code for its popu-
lar Navigator browser. This announcement prompted a small group of software developers who had
been long-time supporters of the soon-to-be open source ideology to formally develop the Open Source
Initiatives (OSI) and the Open Source Definition.
Although the OSI ideology was initially promoted in the hacker community, upon Netscape’s release of
Navigator’s source code, programmers from all walks of life began to offer suggestions and fixes to
improve the browser’s performance. The OSI mission was off and running, as the mainstream comput-
ing world began to embrace the idea.
Linux became the first operating system that could be considered open source (although BSD was a
close runner-up, distributed from Berkeley in 1989), and many programs followed soon thereafter. Large
software corporations, such as Corel, began to offer versions of their programs that worked on Linux
machines.
Although there are now numerous classifications of OSI open source licenses, any software that bears the
OSI Certification seal can be considered open source because it has passed the Open Source Definition test.
These programs are available from a multitude of Web sites; the most popular is
www.sourceforge.net,
which houses more than 83,000 open source projects.

Why Open Source Rocks
Open source programs are very cool because:
❑ They are free. The greatest thing about open source software is that it is free and available to the
general public. Software developers and programmers volunteer their time to improve existing
software and create new programs. Open source software cannot, by definition, require any sort
of licensing or sales fees.
4
Chapter 1
04_579665 ch01.qxd 12/30/04 8:09 PM Page 4

×