Wrox Beginning PHP5 Apache And MySQL Web Development Feb 2005 ISBN 0764579665 pdf

  

Beginning PHP5 , Apache, and

M ySQL ® Web Development

  

Elizabeth Naramore, Jason Gerner, Yann Le Scouarnec,

Jeremy Stolz, Michael K. Glass

  Beginning PHP5 , Apache, and M ySQL ® Web Development

  

Beginning PHP5 , Apache, and

M ySQL ® Web Development

  

Elizabeth Naramore, Jason Gerner, Yann Le Scouarnec,

Jeremy Stolz, Michael K. Glass

  ®

Beginning PHP5, Apache, and M ySQL 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: brandreview@wiley.com.

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.

  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.

  M ichael “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.

  Credits Acquisitions Editor Project Coordinator Debra Williams Cauley Erin Smith

Development Editor Graphics and Production Specialists

Brian MacDonald Carrie A. Foster Denny Hager Senior Production Editor Jennifer Heleine Angela Smith

  Quality Control Technician Technical Editor Brian H. Walls Jason Gerner

  Proofreading and Indexing Copy Editor TECHBOOKS Production Services Kim Cofer Editorial M anager Mary Beth Wakefield Vice President & Executive Group Publisher Richard Swadley Vice President and Publisher Joseph B. Wikert

  Contents

  Part I: Getting Started

  1 Chapter 1 : Configuring Your Installation

  3 Projects in This Book

  3 Brief Intro to PHP, Apache, M ySQL, and Open Source

  4 A Brie f His to ry o f Ope n So urc e Initiative s

  4 Why Ope n So urc e Ro c ks

  4 How the Pieces of the AM P M odule Work Together

  5 Apac he

  6 PHP

  6 MySQL

  7 AMP Ins talle rs

  8 Fo xs e rv

  8 PHPTriad

  8 XAMPP

  8 Configuring Your Apache Installation

  8 Te s ting Yo ur Ins tallatio n

  9 Cus to mizing Yo ur Ins tallatio n 1 0

  Adding PHP to the Equatio n 1 0 Do c ume nt Ro o t 1 1

  Configuring Your PHP Installation 1 3

  Te s ting Yo ur Ins tallatio n 1 3

  Cus to mizing Yo ur Ins tallatio n 1 4

  Co nfiguring PHP5 to Us e MySQL 1 6

  Configuring Your M ySQL Installation 1 7

  Te s ting Yo ur Ins tallatio n 1 7

  Co nfiguring Yo ur Ins tallatio n 1 9

  The my.c nf File 2 1 Se tting Up Us e rs and Privile ge s 2 4

  

Where to Go for Help and Other Valuable Resources 2 5

  He lp within the Pro grams 2 5

  So urc e We b Site s 2 5

  Summary 2 6 x Co nte nts Part II: Movie Review Web Site

  27 Chapter 2 : Creating PHP Pages Using PHP5 2 9 Overview of PHP Structure and Syntax 3 0

  Pas s ing Variable s with Co o kie s 4 9

  Alte rnate s to the e c ho Co mmand 7 8

  Alte rnate s to the <? php and ? > Tags 7 8

  7 4 Alternate Syntax for PHP 7 8

  So rting Arrays 6 9 fo re ac h Co ns truc ts 6 9 While You’re Here . . .

  Array Syntax 6 7

  Using Includes for Efficient Code 6 0 Using Functions for Efficient Code 6 2 All About Arrays 6 7

  Us ing if and e ls e To ge the r 5 9

  Ope rato rs 5 7 Spe c ial Syntax Co ns ide ratio ns 5 8

  Us ing if State me nts 5 7

  Using if/ else Arguments 5 7

  Fas t Prime r o n Fo rms 5 3

  Pas s ing Info rmatio n with Fo rms 5 3

  Pas s ing Variable s with Se s s io ns 4 7

  Ho w PHP Fits with HTML 3 0

  Spe c ial Charac te rs in URLs 4 5

  Pas s ing Variable s thro ugh a URL 4 2

  A Wo rd abo ut re gis te r_glo bals 4 1

  Passing Variables between Pages 4 0

  Ove rvie w o f Variable s 3 8

  Ove rvie w o f Co ns tants 3 7

  Using Constants and Variables to Add Functionality 3 7

  Co ns ide ratio ns with HTML Ins ide PHP 3 6

  Inte grating HTML with PHP 3 4

  Creating Your First Program 3 3 Using HTM L to Spice Up Your Pages 3 4

  What Make s a Gre at Pro gram? 3 2 Why Sho uld Yo u Care abo ut What Yo ur Co de Lo o ks Like ? 3 2

  The Impo rtanc e o f Co ding Prac tic e s 3 1

  The Rule s o f PHP Syntax 3 0

  Alte rnate s to Lo gic al Ope rato rs 7 9

  Co nte nts

  Alte rnate s to Do uble Quo te s : Us ing he re do c 7 9

  Alte rnate s to Inc re me nting/ De c re me nting Value s 7 9

  OOP Dreams 7 9

  A Brie f OOP Example 8 0

  Why Us e OOP? 8 2

  Summary 8 2 Exercises 8 2

Chapter 3 : Using PHP5 with M ySQL

  8 5 Overview of M ySQL Structure and Syntax 8 5

  MySQL Struc ture 8 6

  Fie ld Type s 8 6 Cho o s ing the Right Fie ld Type 8 8 null/ no t null 8 9 Inde xe s 9 0 Unique 9 0 Auto Inc re me nt 9 0 Othe r Parame te rs 9 1 Type s o f MySQL Table s and Sto rage Engine s 9 1

  MySQL Syntax and Co mmands 9 2

  How PHP Fits with M ySQL 9 2 Connecting to the M ySQL Server 9 3 Looking at a Ready-M ade Database 9 4 Querying the Database 9 9

  WHERE, o h WHERE 9 9

  Wo rking with PHP and Arrays o f Data: fo re ac h 1 0 2 A Tale o f Two Table s

  1 0 4

  Re fe re nc ing Two Table s 1 0 5 Jo ining Two Table s 1 0 7

  Helpful Tips and Suggestions 1 0 9

  Do c ume ntatio n 1 0 9

  Us ing PHPMyAdmin 1 0 9

  

Summary 1 1 0

Exercises 1 1 0

  

Chapter 4 : Using Tables to Display Data 1 1 1 Creating a Table 1 1 1 Populating the Table 1 1 4 Who’s the M aster? 1 2 0 xii Co nte nts

  A Lasting Relationship 1 2 8 Summary 1 3 4 Exercises 1 3 4

  1 5 0

  1 9 4

  What File Type s Can I Us e with GD and PHP? 1 9 4 Co mpiling PHP with GD

  

Chapter 7 : M anipulating and Creating Images with PHP 1 9 3

Working with the GD Library 1 9 3

  

Chapter 6 : Letting the User Edit the Database 1 6 3

Preparing the Battlefield 1 6 3 Inserting a Simple Record from phpM yAdmin 1 6 6 Inserting a Record in a Relational Database 1 7 0 Deleting a Record 1 7 8 Editing Data in a Record 1 8 3 Summary 1 9 1 Exercise 1 9 1

  Summary 1 6 0 Exercises 1 6 1

  Adding Ite ms 1 5 9

  De fault Re s po ns e 1 5 9

  The Ske le to n Sc ript 1 5 9

  Using Form Elements Together 1 5 0

  Manipulating a String as an Array to Change the Cas e o f the Firs t Charac te r 1 5 0 Te rnary Ope rato r

  

Chapter 5 : Form Elements: Letting the User Work with Data 1 3 5

Your First Form 1 3 6

  Dynamic Page Title 1 4 9

  Bas ic Input Te s ting 1 4 9

  Multiple Submit Butto ns 1 4 9

  Radio INPUT Ele me nt 1 4 8

  One Fo rm, Multiple Pro c e s s ing 1 4 4

  INPUT Che c kbo x Type 1 4 3

  Driving the User Input 1 4 1

  Pro c e s s ing the Fo rm 1 4 0

  INPUT Ele me nt 1 3 9

  FORM Ele me nt 1 3 8

  Allowing Users to Upload Images 1 9 6

  Co nte nts Converting Image File Types

  2 0 3 Black and White 2 0 8 Adding Captions 2 1 4 Adding Watermarks and M erging Images 2 1 8 Creating Thumbnails 2 2 0

  

Summary 2 2 5

Exercises 2 2 5

Chapter 8 : Validating User Input

  2 2 7 Users Are Users Are Users . . .

  2 2 7 Incorporating Validation into the M ovie Site 2 2 8 Forgot Something? 2 2 9 Checking for Format Errors 2 3 9

  

Summary 2 5 0

Exercise 2 5 0

  

Chapter 9 : Handling and Avoiding Errors 2 5 1

How the Apache Web Server Deals with Errors 2 5 1 Apac he ’s Erro rDo c ume nt Dire c tive

  2 5 2 Apac he ’s Erro rDo c ume nt: Advanc e d Cus to m Erro r Page 2 5 6

  Error Handling and Creating Error Handling Pages with PHP 2 6 0

  Erro r Type s in PHP 2 6 0

  Ge ne rating PHP Erro rs 2 6 1

  Other M ethods of Error Handling 2 6 9

  Exc e ptio ns 2 6 9

  No t Me e ting Co nditio ns 2 7 1

  Pars e Erro rs 2 7 2

  

Summary 2 7 2

Exercises 2 7 2

Part III: Comic Book Fan Site

  273

  Chapter 1 0 : Building Databases 2 7 5 Getting Started

  2 7 5

  What Is a Re latio nal Databas e ? 2 7 6

  Ke ys 2 7 7

  Re latio ns hips 2 7 7

  Re fe re ntial Inte grity 2 7 8

  No rmalizatio n 2 7 8 Co nte nts Designing Your Database

  2 7 9

  Cre ating the Firs t Table 2 7 9

  What’s So No rmal Abo ut The s e Fo rms ? 2 8 3

  Standardizatio n 2 8 3 Finalizing the Databas e De s ign

  2 8 4

  Creating a Database in M ySQL 2 8 5 Creating the Comic Character Application 2 9 0 c harlis t.php

  3 1 6 c hare dit.php 3 2 0

  Summary 3 2 3 Exercises 3 2 4

  Chapter 1 1 : Sending E-mail 3 2 5 Setting Up PHP to Use E-mail

  3 2 5 Sending an E-mail 3 2 6 Dressing Up Your E-mails with HTM L 3 3 1

  Multipart Me s s age s 3 3 4

  Storing Images 3 3 7 Getting Confirmation 3 3 9 Creating a Reusable M ail Class 3 5 5 Summary 3 6 2 Exercises 3 6 3

  

Chapter 1 2 : User Logins, Profiles, and Personalization 3 6 5

The Easiest Way to Protect Your Files 3 6 5 Friendlier Logins Using PHP’s Session and Cookie Functions 3 7 0 Using Database-Driven Information 3 7 5

  Us ing Co o kie s in PHP 3 9 9

  Adminis trato r Re gis tratio n 4 0 2

  Summary 4 1 3 Exercises 4 1 3

  

Chapter 1 3 : Building a Content M anagement System 4 1 5

Getting Your Users to Return 4 1 5

  Co nte nt 4 1 5

  Manage me nt 4 1 6

  Sys te m 4 1 6

  Putting It All To ge the r 4 1 6

  Preparing the Database 4 1 7 xiv

  Co nte nts Coding for Reusability

  Opt-In ve rs us Opt-Out 5 1 4

  Privac y Po lic y 5 6 1 Re turn Po lic y 5 6 1 Warm Bo die s 5 6 1 Se c ure Cre dit Card Pro c e s s ing 5 6 1

  Impo rtanc e o f Trus t 5 6 0

  Info rmatio n Is Eve rything 5 6 0

  E-Commerce, Any Way You Slice It 5 5 9

  Sho pping Cart So ftware 5 1 9 Yo ur Own Cart So ftware Co de 5 1 9

  A Sho pping Cart 5 1 9

  So me thing to Se ll 5 1 8

  5 1 7

Adding E-Commerce to the Comic Book Fan Site 5 1 8

  

Summary 5 1 5

Exercises 5 1 5

Chapter 1 5 : Online Stores

  A Wo rd Abo ut Spam 5 1 4

  4 2 2 o utputfunc tio ns .php

  M ailing List Ethics 5 1 4

  5 0 4 us e r_trans ac t.php 5 0 5 thanks .php 5 0 9

  4 8 1 What Do You Want to Send Today? 4 8 1 Coding the Administration Application 4 8 2 Sign M e Up! 4 9 7 us e r.php

  

Summary 4 7 9

Exercises 4 7 9

Chapter 1 4 : M ailing Lists

  Additio nal CMS Fe ature s 4 7 2

  Artic le Publis hing 4 5 8

  Us e r Manage me nt 4 5 4

  Ge ne ral Func tio nality 4 4 4

  Transaction Pages 4 3 1 User Interface 4 4 4

  4 2 6 he ade r.php 4 2 9 http.php 4 3 1

  Pro fe s s io nal Lo o k 5 6 2 xvi Co nte nts

  Eas y Navigatio n 5 6 2

  Us e r Adminis tratio n 6 1 7

  PHP 6 4 4

  Apac he 6 4 2

  

Chapter 1 7 : Using Log Files to Improve Your Site 6 4 1

Locating Your Logs 6 4 2

  Afterthoughts 6 3 8 Summary 6 3 9 Exercises 6 3 9

  Se arc hing 6 3 6

  Re gular Expre s s io ns 6 2 4 The Two Type s o f re ge x Func tio ns 6 2 4 Ho w to Write a PCRE re ge x 6 2 5

  BBc o de Adminis tratio n 6 2 4

  Fo rum Adminis tratio n 6 2 3

  Bo ard Adminis tratio n 6 2 2

  Forum Functionality 6 1 8

  Transaction Pages 5 9 3 Account Functionality 6 0 4

  Co mmo n Links 5 6 2 Se arc h Func tio n 5 6 2 Typic al De s ign 5 6 2

  A Las t Lo o k at Us e r Authe ntic atio n 5 9 2

  Bre adc rumbs 5 9 0

  Paginatio n 5 8 6

  

Chapter 1 6 : Creating a Bulletin Board System 5 6 7

Your Bulletin Board 5 6 7 Preparing the Database 5 6 9 Reusable Code 5 7 7

  Summary 5 6 4 Exercises 5 6 4

  5 6 3

  Co mmunic atio n 5 6 3 Cus to me r Fe e dbac k

  Time ly De live ry 5 6 3

  Appro priate Me rc handis e 5 6 3

  Co mpe titive Pric ing 5 6 2

  MySQL 6 4 4

  Co nte nts Analyzing Your Log Data

  6 4 6

  We balize r 6 4 6

  Analo g 6 4 7

  We bTre nds 6 4 8

  AWStats 6 4 9

  HTTP Analyze 6 5 0

  Putting the Analysis to Work 6 5 1

  Site He alth 6 5 1

  Us e r Pre fe re nc e s and Info rmatio n 6 5 1

  Numbe r o f Hits and Page Vie ws 6 5 1

  Tre nds o ve r Time 6 5 2

  Re fe rring Site s 6 5 2

  

Summary 6 5 2

Chapter 1 8 : Troubleshooting

  Cle anup o n Line 2 6 . . . Oo ps , I Me an 9 4 6 5 4

  Where to Go for Help 6 5 9

  

Summary 6 6 0

  IRC Channe ls 6 6 0

  6 6 0

  6 6 0 Se arc h and Re s c ue

  PHPBuilde r.c o m 6 5 9 So urc e We b Site s

  www.wro x.c o m 6 5 9

  Te s t, Te s t, Te s t! 6 5 9

  6 5 3 Installation Troubleshooting 6 5 3 Parse Errors 6 5 3

  Divide and Co nque r 6 5 9

  Us ing e c ho 6 5 8

  “Headers Already Sent” Error 6 5 7 General Debugging Tips 6 5 8

  Ope n a Ne w Bro ws e r 6 5 6

  Co ns is te nt and Valid Variable Name s 6 5 6

  The Ultimate Bait-and-Switc h 6 5 5

  Empty Variables 6 5 5

  Ele me ntary, My De ar Wats o n! 6 5 4 xviii Co nte nts Appendix A: Answers to Exercises

  6 6 1 Appendix B: PHP Quick Reference 7 0 3 Appendix C: PHP5 Functions 7 0 7 Appendix D: M ySQL Data Types 7 4 7 Appendix E: M ySQL Quick Reference 7 5 1

  

Appendix F: Comparison of Text Editors 7 5 5

Appendix G: Choosing a Third-Party Host 7 5 9

Appendix H: An Introduction to PEAR

  7 6 3 Appendix I: AM P Installation 7 7 1 Index

  7 7 7

  Pa r t I : Ge t t i ng St a r t e d

Chapter 1: Configuring Your Installation

1 Conf i guri ng Your

  I nst a l l a t i on

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.

  Proje c t s 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. Chapte r 1

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.

  Brie f I nt ro t o PHP, Apa c he , M ySQL, a nd Ope n Sourc e

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

  Co nfiguring Yo ur Ins tallatio n ❑ They are cross-platform and “technology-neutral.” By requiring open source software to be non–platform specific, the open source community has ensured that the programs are usable by virtually everyone. According to the Open Source Definition provided by the Open Source Initiative at http://opensource.org/docs/definition.php , open source programs must not be dependent on any “individual technology or style of interface” and must be “technology- neutral.” As long as the software can run on more than one operating system, it meets the criterion. ❑ They must not restrict other software. This basically means that if an open source program is distributed along with other programs, those other programs may be open source or commer- cial in nature. This gives software developers maximum control and flexibility. ❑ They embrace diversity. Diversity of minds and cultures simply produces a better result. For this reason, open source programs cannot, by definition, discriminate against any person or group of persons, nor against any “field of endeavor.” For example, a program designed for use in the medical profession cannot be limited to that field if someone in another field wants to take the program and modify it to fit his or her needs. For a complete list of the criteria a piece of software must meet before it can be considered “open

source,” or for more information about the OSI or the open source community, visit the OSI Web site

at www.opensource.org .

  How t he Pie c e s of t he AM P M odule Work Toge t he r

Now that you’ve learned some of the history of open source, it’s important to understand the role each of these programs (Apache, MySQL, and PHP) plays in creating your Web site.

Imagine that your dynamic Web site is a fancy restaurant. Diners come to your place, and each one

wants something different and specific. They don’t worry so much about how the food is prepared, as

long as it looks and tastes delicious. Unlike a buffet-type spread, where everything is laid out and your

patrons simply choose from what’s available, a nice restaurant encourages patron/waiter interaction

and complete customization for any specific dietary needs. Similarly, a Web site shouldn’t be a static

page with little interaction from visitors; it should be a dynamic site where the visitor can choose what he or she wants to see. In this scenario, you can characterize the three components of the AMP module as follows: ❑ Apache: This is your highly trained master of culinary arts, the chef. Whatever people ask for, she prepares it without complaint. She is quick, flexible, and able to prepare a multitude of dif- ferent types of foods. Apache acts in much the same way as your HTTP server, parsing files and passing on the results. ❑ PHP: This is the waiter. He gets requests from the patron and carries them back to the kitchen with specific instructions about how the meal should be prepared. ❑ MySQL: This is your stockroom of ingredients (or in this case, information). Chapte r 1 When a patron (or Web site visitor) comes to your restaurant, he or she sits down and orders a meal with specific requirements, such as a steak, well done. The waiter (PHP) takes those specific requirements back to the kitchen and passes them off to the chef (Apache). The chef then goes to the stockroom (MySQL) to retrieve the ingredients (or data) to prepare the meal and presents the final dish to the patron, exactly the way he or she ordered it.

You can choose to install one, two, or all three components of the AMP package based on your specific

needs. For example, if you are responsible for providing a company-wide intranet, or hosting your own

Web site, you should probably install all three. If your site is hosted by a third-party Web hosting company,

however, you do not necessarily need to install all three components (or, for that matter, any of them).

  

Installing the three components, even if you don’t have to, enables you to develop and test your site in

the comfort of your own workspace without having to upload to the file server just to test at every little

step. Even if you do a lot of off-line testing, however, we highly recommend that you still perform a com-

plete test once your site is live and running, because your settings may differ from those on your Web-

hosting company’s server. Even a small difference can cause you big headaches.

  Apache

Apache acts as your Web server. Its main job is to parse any file requested by a browser and display the

correct results according to the code within that file. Apache is quite powerful and can accomplish virtu- ally any task that you, as a Webmaster, require.

The version of Apache covered in this book is the most recent and stable at the time of this writing: ver-

sion 2.0.50. The features and server capabilities available in this version include the following:

  ❑ Password-protected pages for a multitude of users ❑ Customized error pages ❑ Display of code in numerous levels of HTML, and the capability to determine at what level the browser can accept the content ❑ Usage and error logs in multiple and customizable formats ❑ Virtual hosting for different IP addresses mapped to the same server ❑ DirectoryIndex directives to multiple files ❑ URL aliasing or rewriting with no fixed limit

  

According to the Netcraft Web site ( www.netcraft.com ), at the time of this writing Apache is running

over 34 million Internet servers, more than Microsoft, Sun ONE, and Zeus combined. Its flexibility,

power, and, of course, price make it a popular choice. It can be used to host a Web site for the general

public, or a company-wide intranet, or for simply testing your pages before they are uploaded to a

secure server on another machine. Later in this chapter, you learn to configure your Apache setup to

accommodate all of these options.

  PHP

PHP is a server-side scripting language that allows your Web site to be truly dynamic. PHP stands for

PHP: Hypertext Preprocessor (and, yes, we’re aware PHP is a “recursive acronym” — probably meant to

  6

  Co nfiguring Yo ur Ins tallatio n

confuse the masses). Its flexibility and relatively small learning curve (especially for programmers who

have a background in C, Java, or Perl) make it one of the most popular scripting languages around. PHP’s

popularity continues to increase as businesses, and individuals everywhere embrace it as an alternative

to Microsoft’s ASP language and realize that PHP’s benefits most certainly outweigh the costs (three

cheers for open source!). According to Netcraft, PHP code can now be found in approximately 16 million Web sites.

  

The version of PHP referenced in this book is the most recent stable release at the time of publication:

version 5.0.0. Although we discuss several of the most common uses and functions of PHP, you can find

a complete list of PHP functions in Appendix B of this book. As you continue to program in PHP and

your comfort level increases (or the demands of your boss grow), we encourage you to expand your use

of built-in PHP functions to take advantage of its tremendous power. You can download the PHP soft-

ware from PHP’s Web site at www.php.net .

  M ySQL

Another open source favorite, MySQL is the database construct that enables PHP and Apache to work

together to access and display data in a readable format to a browser. It is a Structured Query Language

server designed for heavy loads and processing of complex queries. As a relational database system,

MySQL allows many different tables to be joined together for maximum efficiency and speed.

  This book references version 4.0.20, the most stable release of MySQL at the time of writing. You can find

a complete list of features at the MySQL Web site ( www.mysql.com ), but some of the more popular fea-

tures of this program are as follows: ❑ Multiple CPUs usable through kernel threads

  ❑ Multi-platform operation ❑ Numerous column types cover virtually every type of data ❑ Group functions for mathematical calculations and sorting ❑ Commands that allow information about the databases to be easily and succinctly shown to the administrator ❑ Function names that do not affect table or column names

  ❑ A password and user verification system for added security ❑ Up to 32 indexes per table permitted; this feature has been successfully implemented at levels of 60,000 tables and 5,000,000,000 rows (version 4.1.2, currently in development, will allow 64 indexes)

  ❑ International error reporting usable in many different countries

MySQL is the perfect choice for providing data via the Internet because of its ability to handle heavy

loads and its advanced security measures.

  

For more information on how MySQL was developed, or other specific information not covered in this book, visit the resource Web site at www.mysql.com . Chapte r 1 AM P Installers

  

If you’d like to take your entire Saturday afternoon to install each of these components separately, feel

free to refer to Appendix I at the back of this book. However, we can also tell you about some third-party

software programs that will complete the installation for you. You can find an extended list of these

types of installers at www.hotscripts.com .

  Foxserv

Foxserv is an Apache/MySQL/PHP installer that is available at www.foxserv.net . It is offered as an

open source program and is free to the general public. Foxserv allows you to customize your configura-

tion files during installation and also allows for PEAR modules to be downloaded. (You can read more

about the use of PEAR in Appendix H.) This installer is compatible with both Windows and Linux

systems.

  PHPTriad

PHPTriad is another open source installer that is available at no charge. It is available for download at

  http://sourceforge.net/projects/phptriad/ but is currently applicable to Windows systems

  

only. Along with Apache, PHP, and MySQL, the package includes Perl and phpMyAdmin (another

powerful database administration system we discuss in Chapter 3).

XAM PP

  XAMPP, available at http://sourceforge.net/projects/xampp , is an open source installer that will install Apache, MySQL, PHP, Perl, phpMyAdmin, and an FTP server. It is suitable for Linux, Solaris, and Windows systems.

  Configuring Your Apa c he I nst a lla t ion

For the purposes of working through this book, we assume that you have installed Apache on your

computer. If you haven’t done so but would like to, you can find detailed installation instructions in

Appendix I.

Before you begin configuring and customizing your installation, take a minute to make sure you have

installed everything correctly.

  You can access the Apache executable file in three ways: ❑ During installation, the default option is to add Apache to your Start menu, so unless you dis- abled this, you can locate the Apache HTTP Server listing directly from your Start button. This gives you shortcuts to starting the server and to testing and configuring features, as well. ❑ Open Windows Explorer and go to the directory where you have installed Apache, the default being c:\program files\Apache Group\Apache2\bin\ ; click Apache.exe to start your

  Apache HTTP server. ❑ At the DOS prompt, change directories to the location where the Apache file has been loaded, and type apache. This starts the server.

  8

  Co nfiguring Yo ur Ins tallatio n Testing Your Installation

  To test installation of your Apache server, open your Web browser and type the following:

  http://localhost/

  

If your installation was successful, you will see an Apache “success” page in your browser. If not, check

your error log by opening the error. log file, which you can find in c:\program files\Apache

  Group\Apache2\logs\ . This gives you an indication of where your installation went wrong. For a more in-depth discussion of logs, please refer to Chapter 17.

  

If you had installation problems, note that you might experience errors, such as the “no services installed”

error if Apache is trying to share port 80 with another Web server or application, such as a firewall. To fix

this, open your httpd.conf file in the c:\program files\Apache group\Apache2\conf directory and locate the following lines:

  # Listen: Allows you to bind Apache to specific IP addresses and/or # ports, instead of the default. See also the <VirtualHost> # directive.

  # # Change this to Listen on specific IP addresses as shown below to # prevent Apache from glomming onto all bound IP addresses (0.0.0.0) # #Listen 12.34.56.78:80 Listen 80

  Change the last line of this block to read

  Listen 8080

  Then locate the following lines:

  # # ServerName gives the name and port that the server uses to identify itself. # This can often be determined automatically, but we recommend you specify # it explicitly to prevent problems during startup. # # If this is not set to valid DNS name for your host, server-generated # redirections will not work. See also the UseCanonicalName directive. # # If your host doesn’t have a registered DNS name, enter its IP address here. # You will have to access it by its address anyway, and this will make # redirections work in a sensible way. # ServerName www.yourdomainnamehere.com:80

  Change the last line of this code to the following:

  ServerName www.yourdomainnamehere.com:8080 Chapte r 1

Finally, if you are still experiencing problems and you are running a Windows system, The Apache

Foundation has provided a nifty document about some other issues that may arise during installation.

You can view the document by going to http://httpd.apache.org/docs-2.0/platform/ windows.html .