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

Beginning PHP 6, apache, MySQL 6 web development tủ tài liệu bách khoa

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 (9.98 MB, 838 trang )

Wrox Programmer to Programmer TM

g

Beginning

PHP6, Apache,
MySQL
®

Web Development
Timothy Boronczyk, Elizabeth Naramore, Jason Gerner, Yann Le Scouarnec,
Jeremy Stolz, Michael K. Glass

Updates, source code, and Wrox technical support at www.wrox.com
www.allitebooks.com


Programmer to Programmer™

Get more out of
WROX.com
Interact

Chapters on Demand

Take an active role online by participating in
our P2P forums

Purchase individual book chapters in pdf
format



Wrox Online Library

Join the Community

Hundreds of our books are available online
through Books24x7.com

Sign up for our free monthly newsletter at
newsletter.wrox.com

Wrox Blox

Browse

Download short informational pieces and
code to keep you up to date and out of
trouble!

Ready for more Wrox? We have books and
e-books available on .NET, SQL Server, Java,
XML, Visual Basic, C#/ C++, and much more!

Contact Us.
We always like to get feedback from our readers. Have a book idea?
Need community support? Let us know by e-mailing
www.allitebooks.com


Beginning

PHP6, Apache, MySQL® Web Development
Introduction ......................................................................................................... xxiii

Part I: Movie Review Web Site
Chapter 1: Configuring Your Installation ..........................................................3
Chapter 2: Creating PHP Pages Using PHP6 ..................................................19
Chapter 3: Using PHP with MySQL ................................................................77
Chapter 4: Using Tables to Display Data ......................................................105
Chapter 5: Form Elements: Letting the User Work with Data ........................131
Chapter 6: Letting the User Edit the Database .............................................153
Chapter 7: Manipulating and Creating Images with PHP...............................175
Chapter 8: Validating User Input .................................................................217
Chapter 9: Handling and Avoiding Errors ......................................................241

Part II: Comic Book Fan Site
Chapter 10: Building Databases ..................................................................263
Chapter 11: Sending E-mail .........................................................................315
Chapter 12: User Logins, Profiles, and Personalization .................................355
Chapter 13: Building a Content Management System ..................................407
Chapter 14: Mailing Lists............................................................................469
Chapter 15: Online Stores ...........................................................................505
Chapter 16: Creating a Bulletin Board System .............................................557
Chapter 17: Using Log Files to Improve Your Site.........................................627
Chapter 18: Troubleshooting .......................................................................641
Appendix A: Answers to Exercises ..............................................................649
Appendix B: PHP Quick Reference...............................................................685
(continued)

www.allitebooks.com



Appendix C: PHP6 Functions.......................................................................695
Appendix D: MySQL Data Types...................................................................753
Appendix E: MySQL Quick Reference ...........................................................757
Appendix F: Comparison of Text Editors.......................................................761
Appendix G: Choosing a Third-Party Host .....................................................765
Appendix H: An Introduction to PHP Data Objects........................................769
Appendix I: Installation and Configuration on Linux ......................................777
Index .........................................................................................................785

www.allitebooks.com


Beginning

PHP6, Apache, MySQL® Web Development

www.allitebooks.com


www.allitebooks.com


Beginning

PHP6, Apache, MySQL® Web Development
Timothy Boronczyk
Elizabeth Naramore
Jason Gerner
Yann Le Scouarnec

Jeremy Stolz
Michael K. Glass

Wiley Publishing, Inc.

www.allitebooks.com


Beginning PHP6, Apache, MySQL® Web Development
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com

Copyright © 2009 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-0-470-39114-3
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
Library of Congress Cataloging-in-Publication Data.
Beginning PHP6, Apache, MySQL web development / Timothy Boronczyk . . . [et al.].
p. cm.
Includes index.
ISBN 978-0-470-39114-3 (paper/website)
1. Web sites—Design. 2. Apache (Computer file : Apache Group) 3. PHP (Computer program
language) 4. MySQL (Electronic resource) I. Boronczyk, Tim, 1979TK5105.888.B426 2009
006.7'8—dc22
2008047012
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 Permissions Department, John Wiley &
Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at
/>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 particular purpose. No
warranty may be created or extended by sales or promotional 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 professional 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 Web site 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 Web site may provide or recommendations it may
make. Further, readers should be aware that Internet Web sites 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 please contact our Customer Care Department
within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related
trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the
United States and other countries, and may not be used without written permission. MySQL is a registered
trademark of MySQL AB. All other trademarks are the property of their respective owners. Wiley
Publishing, Inc., is not associated with any product or vendor mentioned in this book.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not
be available in electronic books.

www.allitebooks.com



About the Authors
Timothy Boronczyk is a native of Syracuse, New York, where he works as a programmer by day and a
freelance developer, writer, and technical editor by night. He has been involved in web design since
1998, and over the years has written several articles on PHP programming and various design topics, as
well as the book PHP and MySQL: Create-Modify-Reuse (Wrox). Timothy holds a degree in software
application programming, is a Zend Certified Engineer, and recently started his first business venture,
Salt City Tech (www.saltcitytech.com). In his spare time, he enjoys photography, hanging out with
friends, and sleeping with his feet hanging off the end of his bed. He’s easily distracted by shiny objects.
Elizabeth Naramore 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
numerous 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 U. to get her masters in computer science.
Jason “Goldbug” Gerner currently spends his days working as a web developer in Cincinnati and burns
free time complaining 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 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.
Jeremy “Stolzyboy” Stolz 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.
Michael “BuzzLY” 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 technologies, 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.

www.allitebooks.com


www.allitebooks.com


Credits
Acquisitions Editor

Vice President and Executive Group Publisher

Jenny Watson

Richard Swadley

Development Editor

Vice President and Executive Publisher

Adaobi Obi Tulton

Barry Pruett

Technical Editor

Associate Publisher

Robert Shimonski


Jim Minatel

Production Editor

Project Coordinator, Cover

Kathleen Wisor

Lynsey Stanford

Copy Editor

Proofreader

Foxxe Editorial Services

Jen Larsen, Word One

Editorial Manager

Indexer

Mary Beth Wakefield

Robert Swanson

Production Manager
Tim Tate




Acknowledgments
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 who make me proud to be a mom. Also,
thank you to Debra for always keeping us on track, and for having faith in us.
— Elizabeth Naramore
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.
— Yann Le Scouarnec
I’d like to thank my wife, my baby daughter, and the rest of my family for being patient with me
while I was working on this project.
— Jeremy Stolz
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 have taught
me the importance of finishing what you’ve started.
— Michael Glass



Beginning

PHP6, Apache, MySQL® Web Development




Contents
Introduction

xxiii

Part I: Movie Review Web Site
Chapter 1: Configuring Your Installation
Projects in This Book
A Brief Introduction to Apache, MySQL, PHP, and Open Source
A Brief History of Open Source Initiatives
Why Open Source Rocks

How the AMP Pieces Work Together
Installing Apache, MySQL, and PHP on Windows
Installing Apache
Installing PHP
Configuring PHP to Use MySQL
Installing MySQL

Where to Go for Help and Other Valuable Resources
Help within the Programs
Source Web Sites

Summary

Chapter 2: Creating PHP Pages Using PHP6
Overview of PHP Structure and Syntax

3
3

4
4
5

5
6
6
10
11
13

17
18
18

18

19
20

How PHP Fits with HTML
The Rules of PHP Syntax
The Importance of Coding Practices

20
20
21

Creating Your First Program
Using HTML to Spice Up Your Pages


23
26

Integrating HTML with PHP
Considerations with HTML inside PHP

26
28

Using Constants and Variables to Add Functionality
Overview of Constants
Overview of Variables

29
29
31

Passing Variables between Pages

33

Passing Variables through a URL

33


Contents
Passing Variables with Sessions
Passing Variables with Cookies

Passing Information with Forms

Using if/else Arguments
Using if Statements
Using if and else Together

Using Includes for Efficient Code
Using Functions for Efficient Code
All about Arrays
Array Syntax
Sorting Arrays
foreach Constructs

While You’re Here . . .
Alternate Syntax for PHP
Alternates
Alternates
Alternates
Alternates

to
to
to
to

the echo Command
Logical Operators
Double Quotes: Using heredoc
Incrementing/Decrementing Values


OOP Dreams
Classes
Properties and Methods
Why Use OOP?

Summary
Exercises

Chapter 3: Using PHP with MySQL
Overview of MySQL Structure and Syntax
MySQL Structure
MySQL Syntax and Commands

How PHP Fits with MySQL
Connecting to the MySQL Server
Looking at a Ready-Made Database
Querying the Database
WHERE, oh WHERE
Working with PHP and Arrays of Data: foreach
A Tale of Two Tables

38
41
44

49
49
51

52

55
59
60
61
63

67
72
72
73
73
73

74
74
75
75

76
76

77
77
78
84

85
86
86
91

91
94
97

Helpful Tips and Suggestions

102

Documentation
Using MySQL Query Browser

102
102

Summary
Exercises

xvi

103
103


Contents
Chapter 4: Using Tables to Display Data
Creating a Table
Wait a Minute
Who’s the Master?
A Lasting Relationship
Summary

Exercises

Chapter 5: Form Elements: Letting the User Work with Data
Your First Form

105
105
110
118
125
129
129

131
131

FORM Element
INPUT Element
Processing the Form

134
134
135

Driving the User Input

135

One Form, Multiple Processing
Radio INPUT Element

Multiple Submit Buttons
Basic Input Testing
Ternary Operator

Linking Forms Together
Summary
Exercises

Chapter 6: Letting the User Edit the Database
Preparing the Battlefield
Inserting a Record in a Relational Database
Deleting a Record
Editing Data in a Record
Summary
Exercise

Chapter 7: Manipulating and Creating Images with PHP
Working with the GD Library
What File Types Can I Use with GD & PHP?
Enabling GD in PHP

Allowing Users to Upload Images
Converting Image File Types
Special Effects
Adding Captions

139
142
143
143

144

145
151
152

153
153
156
162
167
174
174

175
175
176
176

177
188
192
202

xvii


Contents
Adding Watermarks and Merging Images
Creating Thumbnails

Summary
Exercises

Chapter 8: Validating User Input

209
212
216
216

217

Users Are Users Are Users . . .
Incorporating Validation into the Movie Site
Forgot Something?
Checking for Format Errors
Summary
Exercises

Chapter 9: Handling and Avoiding Errors
How the Apache Web Server Deals with Errors
Apache’s ErrorDocument Directive
Apache’s ErrorDocument: Advanced Custom Error Page

Error Handling and Creating Error-Handling Pages with PHP
Error Types in PHP
Generating PHP Errors

217
218

218
226
238
239

241
241
242
246

248
249
250

Other Methods of Error Handling

256

Exceptions
Not Meeting Conditions
Parse Errors

256
258
260

Summary
Exercises

260

260

Part II: Comic Book Fan Site
Chapter 10: Building Databases

263

Getting Started

263

What Is a Relational Database?
Keys
Relationships
Referential Integrity
Normalization

264
265
265
266
266

Designing Your Database

267

Creating the First Table

267


xviii
www.allitebooks.com


Contents
What’s So Normal about These Forms?
Standardization
Finalizing the Database Design

Creating a Database in MySQL
Creating the Comic Character Application
Summary
Exercises

Chapter 11: Sending E-mail
Setting Up PHP to Use E-mail
Sending an E-mail
Dressing Up Your E-mails with HTML
Multipart Messages

Storing Images
Getting Confirmation
Creating a Reusable Mail Class
Summary
Exercises

Chapter 12: User Logins, Profiles, and Personalization
The Easiest Way to Protect Your Files
Friendlier Logins Using PHP’s Session and Cookie Functions

Using Database-Driven Information
Using Cookies in PHP
Administrator Registration

Summary
Exercises

Chapter 13: Building a Content Management System
Fresh Content Is a Lot of Work
You Need a Content Management System

271
272
272

273
278
312
313

315
316
316
322
326

328
330
343
352

353

355
356
359
365
388
393

405
406

407
407
408

Laying Down the Rules
Preparing the Database
Coding for Reusability
Transaction Pages
User Interface

408
409
412
420
432

General Functionality
User Management

Article Publishing

432
442
447

xix


Contents
Additional CMS Features

Summary
Exercises

Chapter 14: Mailing Lists
What Do You Want to Send Today?
Coding the Administration Application
Sign Me Up!
Mailing List Ethics
A Word about Spam
Opt-In versus Opt-Out

Summary
Exercises

Chapter 15: Online Stores
Adding E-Commerce to the Comic Book Fan Site
Something to Sell
A Shopping Cart


E-Commerce, Any Way You Slice It
Information Is Everything
Importance of Trust
Professional Look
Easy Navigation
Competitive Pricing
Appropriate Merchandise
Timely Delivery
Communication
Customer Feedback

Summary
Exercises

Chapter 16: Creating a Bulletin Board System
Your Bulletin Board
Preparing the Database
Reusable Code
Pagination
Breadcrumbs
A Last Look at User Authentication

Transaction Pages

xx

461

467

468

469
469
470
486
502
502
503

503
504

505
506
506
507

551
552
552
553
554
554
554
555
555
555

556

556

557
557
558
564
573
577
579

580


Contents
Account Functionality

593

User Administration

605

Forum Functionality

606

Board Administration
Forum Administration
BBcode Administration
Searching


Afterthoughts
Summary
Exercises

Chapter 17: Using Log Files to Improve Your Site
Locating Your Logs
Apache
PHP
MySQL

Analyzing Your Log Data
Webalizer
Analog
AWStats
HTTP Analyze
Google Analytics

Putting the Analysis to Work
Site Health
User Preferences and Information
Number of Hits and Page Views
Trends over Time
Referring Sites

Summary

Chapter 18: Troubleshooting
Installation Troubleshooting
Parse Errors

Cleanup on Line 26 . . . Oops, I Mean 94
Elementary, My Dear Watson!

Empty Variables
Consistent and Valid Variable Names
Open a New Browser

“Headers Already Sent” Error
General Debugging Tips

610
612
612
623

624
625
625

627
628
628
630
630

633
633
634
634
635

636

637
637
638
638
638
638

639

641
641
642
642
642

643
643
643

644
645

xxi


Contents
Use echo
Divide and Conquer

Test, Test, Test!
Debug with Xdebug

Where to Go for Help
www.wrox.com
PHPBuilder.com
Source Web Sites
Search and Rescue
IRC Channels

Summary

645
646
646
647

647
647
647
647
648
648

648

Appendix A: Answers to Exercises

649


Appendix B: PHP Quick Reference

685

Appendix C: PHP6 Functions

695

Appendix D: MySQL Data Types

753

Appendix E: MySQL Quick Reference

757

Appendix F: Comparison of Text Editors

761

Appendix G: Choosing a Third-Party Host

765

Appendix H: An Introduction to PHP Data Objects

769

Appendix I: Installation and Configuration on Linux


777

Index

785

xxii


Introduction
Welcome to Beginning PHP6, Apache, MySQL Web Development, your new trusty resource for assistance in
creating your own dynamic web sites. There are a lot of technologies available that can be used to deliver
great web sites, and we’re glad you chose the Apache/MySQL/PHP (sometimes referred to simply as
AMP) approach. You may or may not have had a taste of these three components in the past, but either
way we’re confident that you will be impressed with the power that lies within them. With this guide by
your side, you’ll soon learn why this combination is rapidly becoming the most popular way to develop
dynamic web sites!
Apache, MySQL and PHP are each complex in and of themselves, and it’s impossible for this book to
cover every advanced detail of all three. The purpose of this book is to give you the best possible
foundation for understanding how each of the core components work separately and together, which
will enable you to take full advantage of all that they have to offer. Where we cannot discuss some of the
advanced topics, either because it would lead us off on a tangent and cause us to lose focus or because of
the space constraints of print media, we provide plenty of direction to authoritative resources you can go
to for more information. We show you the tip of the iceberg and provide you with the tools to explore
it to its greatest depths. When you’ve finished reading this book, you’ll have a thorough understanding
of the core concepts you need to be an effective developer using Apache, MySQL, and PHP, and
hopefully a burning desire to continue learning and growing as a developer.

Who ’s This Book For?
We assume that anyone reading this book has some experience with web site development concepts and

a basic working knowledge of HTML and CSS. Knowledge of other programming languages besides
PHP is not a prerequisite for this book, but certainly any programming experience you have will help
you understand and apply the concepts we present.
This book is geared toward the “newbie” to Apache, MySQL, and PHP, and we’ve done our best to distill
many of the core concepts and code snippets down to their most basic levels. You will find more
complex and perhaps more efficient ways of accomplishing the same tasks we present in this book as
your knowledge, comfort level, and experience increase. When that happens, you can congratulate
yourself and know that you have come over to the “dark side” to join us as Apache, MySQL, and PHP
enthusiasts!

What ’s Covered in the Book
A variety of topics are covered in this book:


Installation and configuration of Apache, MySQL, and PHP.



Basic introduction to each component and how they interact with one another.


×