Upload
others
View
2
Download
0
Embed Size (px)
Citation preview
Luke Welling and Laura Thomson
201 West 103rd St., Indianapolis, Indiana, 46290 USA
PHP and MySQL
Web Development
00 7842 FM 3/6/01 3:38 PM Page i
PHP and MySQL Web DevelopmentCopyright © 2001 by Sams PublishingAll rights reserved. No part of this book shall be reproduced, stored in aretrieval system, or transmitted by any means, electronic, mechanical, photo-copying, recording, or otherwise, without written permission from the pub-lisher. No patent liability is assumed with respect to the use of the informationcontained herein. Although every precaution has been taken in the preparationof this book, the publisher and author assume no responsibility for errors oromissions. Neither is any liability assumed for damages resulting from the useof the information contained herein.
International Standard Book Number: 0-672-31784-2
Library of Congress Catalog Card Number: 99-64841
Printed in the United States of America
First Printing: March 2001
04 03 02 01 4 3 2 1
TrademarksAll terms mentioned in this book that are known to be trademarks or servicemarks have been appropriately capitalized. Sams Publishing cannot attest tothe accuracy of this information. Use of a term in this book should not beregarded as affecting the validity of any trademark or service mark.
Warning and DisclaimerEvery effort has been made to make this book as complete and as accurate aspossible, but no warranty or fitness is implied. The information provided is onan “as is” basis. The authors and the publisher shall have neither liability norresponsibility to any person or entity with respect to any loss or damages aris-ing from the information contained in this book or from the use of the CD-ROM or programs accompanying it.
ACQUISITIONS EDITORShelley Johnston Markanday
DEVELOPMENT EDITORScott D. Meyers
MANAGING EDITORCharlotte Clapp
COPY EDITORRhonda Tinch-Mize
INDEXERKelly Castell
PROOFREADERSKathy BidwellTony Reitz
TECHNICAL EDITORSIsrael DenisChris Newman
TEAM COORDINATORAmy Patton
SOFTWARE DEVELOPMENTSPECIALISTDan Scherf
INTERIOR DESIGNAnne Jones
COVER DESIGNAnne Jones
PRODUCTIONAyanna LaceyHeather Hiatt MillerStacey Richwine-DeRome
00 7842 FM 3/6/01 3:38 PM Page ii
OverviewIntroduction 1
PART I Using PHP
1 PHP Crash Course 9
2 Storing and Retrieving Data 49
3 Using Arrays 69
4 String Manipulation and Regular Expressions 93
5 Reusing Code and Writing Functions 117
6 Object-Oriented PHP 147
PART II Using MySQL
7 Designing Your Web Database 171
8 Creating Your Web Database 183
9 Working with Your MySQL Database 207
10 Accessing Your MySQL Database from the Web with PHP 227
11 Advanced MySQL 245
PART III E-commerce and Security
12 Running an E-commerce Site 267
13 E-commerce Security Issues 281
14 Implementing Authentication with PHP and MySQL 303
15 Implementing Secure Transactions with PHP and MySQL 327
PART IV Advanced PHP Techniques
16 Interacting with the File System and the Server 351
17 Using Network and Protocol Functions 369
18 Managing the Date and Time 391
19 Generating Images 401
20 Using Session Control in PHP 429
21 Other Useful Features 447
00 7842 FM 3/6/01 3:38 PM Page iii
PART V Building Practical PHP and MySQL Projects
22 Using PHP and MySQL for Large Projects 459
23 Debugging 477
24 Building User Authentication and Personalization 497
25 Building a Shopping Cart 539
26 Building a Content Management System 587
27 Building a Web-Based Email Service 617
28 Building a Mailing List Manager 655
29 Building Web Forums 711
30 Generating Personalized Documents in Portable Document Format (PDF) 743
PART VI
A Installing PHP 4 and MySQL 781
B Web Resources 803
Index 807
00 7842 FM 3/6/01 3:38 PM Page iv
ContentsIntroduction 1
Who Should Read This Book? ..............................................................1What Is PHP? ..........................................................................................1What Is MySQL? ....................................................................................2Why Use PHP and MySQL? ..................................................................2Some of PHP’s Strengths ........................................................................3
Performance ......................................................................................3Database Integration ..........................................................................3Built-In Libraries ..............................................................................4Cost ....................................................................................................4Learning PHP ....................................................................................4Portability ..........................................................................................4Source Code ......................................................................................4
Some of MySQL’s Strengths ..................................................................4Performance ......................................................................................5Low Cost ..........................................................................................5Ease of Use ........................................................................................5Portability ..........................................................................................5Source Code ......................................................................................5
How Is This Book Organized? ..............................................................5What’s New in PHP Version 4? ..............................................................6Finally ....................................................................................................6
PART I Using PHP 7
1 PHP Crash Course 9Using PHP ............................................................................................11Sample Application: Bob’s Auto Parts ................................................11
The Order Form ..............................................................................11Processing the Form ........................................................................13
Embedding PHP in HTML ..................................................................13Using PHP Tags ..............................................................................14PHP Tag Styles ................................................................................15PHP Statements ..............................................................................15Whitespace ......................................................................................16Comments ........................................................................................16
Adding Dynamic Content ....................................................................17Calling Functions ............................................................................18The date() Function ........................................................................18
00 7842 FM 3/6/01 3:38 PM Page v
PHP AND MYSQL WEB DEVELOPMENTvi
Accessing Form Variables ....................................................................19Form Variables ................................................................................19String Concatenation ......................................................................20Variables and Literals ......................................................................21
Identifiers ..............................................................................................21User-Declared Variables ......................................................................22Assigning Values to Variables ..............................................................22Variable Types ......................................................................................22
PHP’s Data Types ............................................................................22Type Strength ..................................................................................23Type Casting ....................................................................................23Variable Variables ............................................................................23
Constants ..............................................................................................24Variable Scope ......................................................................................25Operators ..............................................................................................25
Arithmetic Operators ......................................................................26String Operators ..............................................................................27Assignment Operators ....................................................................27Comparison Operators ....................................................................29Logical Operators ............................................................................30Bitwise Operators ............................................................................31Other Operators ..............................................................................32
Using Operators: Working Out the Form Totals ..................................33Precedence and Associativity: Evaluating Expressions ........................34Variable Functions ................................................................................36
Testing and Setting Variable Types ................................................36Testing Variable Status ....................................................................37Reinterpreting Variables ..................................................................37
Control Structures ................................................................................38Making Decisions with Conditionals ..................................................38
if Statements ....................................................................................38Code Blocks ....................................................................................38A Side Note: Indenting Your Code ................................................39else Statements ................................................................................39elseif Statements ..............................................................................40switch Statements ............................................................................41Comparing the Different Conditionals ............................................42
Iteration: Repeating Actions ................................................................43while Loops ....................................................................................44for Loops ........................................................................................45do..while Loops ..............................................................................46
00 7842 FM 3/6/01 3:38 PM Page vi
CONTENTSvii
Breaking Out of a Control Structure or Script ....................................47Next: Saving the Customer’s Order ......................................................47
2 Storing and Retrieving Data 49Saving Data for Later ..........................................................................50Storing and Retrieving Bob’s Orders ..................................................50Overview of File Processing ................................................................52Opening a File ......................................................................................52
File Modes ......................................................................................52Using fopen() to Open a File ..........................................................53Opening Files for FTP or HTTP ....................................................54Problems Opening Files ..................................................................55
Writing to a File ....................................................................................57Parameters for fwrite() ....................................................................57File Formats ....................................................................................58
Closing a File ........................................................................................58Reading from a File ..............................................................................59
Opening a File for Reading: fopen() ..............................................60Knowing When to Stop: feof() ........................................................60Reading a Line at a Time: fgets(), fgetss(), and fgetcsv() ..............60Reading the Whole File: readfile(), fpassthru(), file() ....................61Reading a Character: fgetc() ..........................................................62Reading an Arbitrary Length: fread() ..............................................63
Other Useful File Functions ................................................................63Checking Whether a File Is There: file_exists() ............................63Knowing How Big a File Is: filesize() ............................................63Deleting a File: unlink() ..................................................................63Navigating Inside a File: rewind(), fseek(), and ftell() ..................64
File Locking ..........................................................................................65Doing It a Better Way: Database Management Systems ......................66
Problems with Using Flat Files ......................................................66How RDBMSs Solve These Problems ............................................67
Further Reading ....................................................................................67Next ......................................................................................................67
3 Using Arrays 69What Is an Array? ................................................................................70Numerically Indexed Arrays ................................................................71
Initializing Numerically Indexed Arrays ........................................71Accessing Array Contents ..............................................................72Using Loops to Access the Array ....................................................73
00 7842 FM 3/6/01 3:38 PM Page vii
PHP AND MYSQL WEB DEVELOPMENTviii
Associative Arrays ................................................................................73Initializing an Associative Array ....................................................73Accessing the Array Elements ........................................................73Using Loops with each() and list() ..................................................74
Multidimensional Arrays ......................................................................75Sorting Arrays ......................................................................................79
Using sort() ......................................................................................79Using asort() and ksort() to Sort Associative Arrays ......................79Sorting in Reverse ..........................................................................80
Sorting Multidimensional Arrays ........................................................80User Defined Sorts ..........................................................................80Reverse User Sorts ..........................................................................82
Reordering Arrays ................................................................................83Using shuffle() ................................................................................83Using array_reverse() ......................................................................84
Loading Arrays from Files ....................................................................85Other Array Manipulations ..................................................................88
Navigating Within an Array: each, current(), reset(),end(), next(), pos(), and prev() ....................................................88
Applying Any Function to Each Element in an Array:array_walk() ..................................................................................89
Counting Elements in an Array: count(), sizeof(), and array_count_values() ....................................................................90
Converting Arrays to Scalar Variables: extract() ............................91Further Reading ....................................................................................92Next ......................................................................................................92
4 String Manipulation and Regular Expressions 93Example Application: Smart Form Mail ..............................................94Formatting Strings ................................................................................96
Trimming Strings: chop(), ltrim(), and trim() ................................96Formatting Strings for Presentation ................................................97Formatting Strings for Storage: AddSlashes() and StripSlashes() 100
Joining and Splitting Strings with String Functions ..........................101Using explode(), implode(), and join() ........................................102Using strtok() ................................................................................102Using substr() ................................................................................103
Comparing Strings ..............................................................................104String Ordering: strcmp(),strcasecmp(), and strnatcmp() ............104Testing String Length with strlen() ..............................................105
Matching and Replacing Substrings with String Functions ..............105Finding Strings in Strings: strstr(), strchr(), strrchr(), stristr() ......106Finding the Position of a Substring: strpos(), strrpos() ................107Replacing Substrings: str_replace(), substr_replace() ..................108
00 7842 FM 3/6/01 3:38 PM Page viii
CONTENTSix
Introduction to Regular Expressions ..................................................109The Basics ....................................................................................109Character Sets and Classes ............................................................110Repetition ......................................................................................111Subexpressions ..............................................................................111Counted Subexpressions ................................................................112Anchoring to the Beginning or End of a String ............................112Branching ......................................................................................112Matching Literal Special Characters ............................................112Summary of Special Characters ....................................................113Putting It All Together for the Smart Form ..................................113
Finding Substrings with Regular Expressions ....................................114Replacing Substrings with Regular Expressions ................................115Splitting Strings with Regular Expressions ........................................115Comparison of String Functions and Regular Expression
Functions ..........................................................................................116Further Reading ..................................................................................116Next ....................................................................................................116
5 Reusing Code and Writing Functions 117Why Reuse Code? ..............................................................................118
Cost ................................................................................................118Reliability ......................................................................................119Consistency ....................................................................................119
Using require() and include() ............................................................119Using require() ..............................................................................119File Name Extensions and Require() ............................................120PHP Tags and require() ................................................................121
Using require() for Web Site Templates ............................................121Using auto_prepend_file and auto_append_file ............................126Using include() ..............................................................................127
Using Functions in PHP ....................................................................129Calling Functions ..........................................................................129Call to Undefined Function ..........................................................131Case and Function Names ............................................................132
Why Should You Define Your Own Functions? ................................132Basic Function Structure ....................................................................132
Naming Your Function ..................................................................133Parameters ..........................................................................................134Scope ..................................................................................................136Pass by Reference Versus Pass by Value ............................................138Returning from Functions ..................................................................140
00 7842 FM 3/6/01 3:38 PM Page ix
PHP AND MYSQL WEB DEVELOPMENTx
Returning Values from Functions ......................................................141Code Blocks ..................................................................................142
Recursion ............................................................................................143Further Reading ..................................................................................145Next ....................................................................................................145
6 Object-Oriented PHP 147Object-Oriented Concepts ..................................................................148
Classes and Objects ......................................................................148Polymorphism ................................................................................149Inheritance ....................................................................................150
Creating Classes, Attributes, Operations in PHP ..............................150Structure of a Class ......................................................................151Constructors ..................................................................................151
Instantiation ........................................................................................152Using Class Attributes ........................................................................152Calling Class Operations ....................................................................154Implementing Inheritance in PHP ......................................................155
Overriding ......................................................................................156Multiple Inheritance ......................................................................157
Designing Classes ..............................................................................158Writing the Code for Your Class ........................................................159Next ....................................................................................................168
PART II Using MySQL 169
7 Designing Your Web Database 171Relational Database Concepts ............................................................172
Tables ............................................................................................173Columns ........................................................................................173Rows ..............................................................................................173Values ............................................................................................173Keys ..............................................................................................173Schemas ........................................................................................175Relationships ................................................................................175
How to Design Your Web Database ....................................................176Think About the Real World Objects You Are Modeling ............176Avoid Storing Redundant Data ....................................................176Use Atomic Column Values ..........................................................178Choose Sensible Keys ..................................................................179Think About the Questions You Want to Ask the Database ..........179Avoid Designs with Many Empty Attributes ................................179Summary of Table Types ..............................................................180
00 7842 FM 3/6/01 3:38 PM Page x
CONTENTSxi
Web Database Architecture ................................................................180Architecture ..................................................................................180
Further Reading ..................................................................................182Next ....................................................................................................182
8 Creating Your Web Database 183A Note on Using the MySQL Monitor ..............................................185How to Log In to MySQL ..................................................................185Creating Databases and Users ............................................................187
Creating the Database ....................................................................187Users and Privileges ..........................................................................187Introduction to MySQL’s Privilege System ........................................188
Principle of Least Privilege ..........................................................188Setting Up Users: The GRANT Command ..................................188Types and Levels of Privilege ......................................................190The REVOKE Command ..............................................................192Examples Using GRANT and REVOKE ......................................192
Setting Up a User for the Web ............................................................193Logging Out As root ......................................................................193
Using the Right Database ..................................................................193Creating Database Tables ....................................................................194
What the Other Keywords Mean ..................................................196Understanding the Column Types ................................................196Looking at the Database with SHOW and DESCRIBE ................198
MySQL Identifiers ..............................................................................199Column Data Types ............................................................................200
Numeric Types ..............................................................................201Further Reading ..................................................................................206Next ....................................................................................................206
9 Working with Your MySQL Database 207What Is SQL? ....................................................................................208Inserting Data into the Database ........................................................209Retrieving Data from the Database ....................................................211
Retrieving Data with Specific Criteria ..........................................212Retrieving Data from Multiple Tables ..........................................214Retrieving Data in a Particular Order ............................................219Grouping and Aggregating Data ..................................................220Choosing Which Rows to Return ..................................................222
Updating Records in the Database ....................................................223Altering Tables After Creation ............................................................223Deleting Records from the Database ..................................................225Dropping Tables ..................................................................................226
00 7842 FM 3/6/01 3:38 PM Page xi
PHP AND MYSQL WEB DEVELOPMENT
Dropping a Whole Database ..............................................................226Further Reading ..................................................................................226Next ....................................................................................................226
10 Accessing Your MySQL Database from the Web with PHP 227
How Web Database Architectures Work ............................................228The Basic Steps in Querying a Database
from the Web ....................................................................................232Checking and Filtering Input Data ....................................................232Setting Up a Connection ....................................................................234Choosing a Database to Use ..............................................................235Querying the Database ........................................................................235Retrieving the Query Results ..............................................................236Disconnecting from the Database ......................................................238Putting New Information in the Database ..........................................238Other Useful PHP-MySQL Functions ................................................241
Freeing Up Resources ..................................................................241Creating and Deleting Databases ..................................................242
Other PHP-Database Interfaces ..........................................................242Further Reading ..................................................................................242Next ....................................................................................................243
11 Advanced MySQL 245Understanding the Privilege System in Detail ....................................246
The user Table ..............................................................................247The db and host Tables ..................................................................248The tables_priv and columns_priv Tables ....................................249Access Control: How MySQL Uses the Grant Tables ..................250Updating Privileges: When Do Changes Take Effect? ..................251
Making Your MySQL Database Secure ............................................251MySQL from the Operating System’s Point of View ..................252Passwords ......................................................................................252User Privileges ..............................................................................253Web Issues ....................................................................................253
Getting More Information About Databases ......................................254Getting Information with SHOW ..................................................254Getting Information About Columns with DESCRIBE ................257Understanding How Queries Work with EXPLAIN ....................257
Speeding Up Queries with Indexes ....................................................261General Optimization Tips ..................................................................261
Design Optimization ......................................................................261Permissions ....................................................................................261
xii
00 7842 FM 3/6/01 3:38 PM Page xii
CONTENTS
Table Optimization ........................................................................262Using Indexes ................................................................................262Use Default Values ........................................................................262Use Persistent Connections ..........................................................262Other Tips ......................................................................................262
Different Table Types ..........................................................................263Loading Data from a File ..................................................................263Further Reading ..................................................................................264Next ....................................................................................................264
PART III E-commerce and Security 265
12 Running an E-commerce Site 267What Do You Want to Achieve? ........................................................268Types of Commercial Web Sites ........................................................268
Online Brochures ..........................................................................269Taking Orders for Goods or Services ............................................271Providing Services and Digital Goods ..........................................275Adding Value to Goods or Services ..............................................276Cutting Costs ................................................................................276
Risks and Threats ................................................................................277Crackers ........................................................................................277Failing to Attract Sufficient Business ............................................278Computer Hardware Failure ..........................................................278Power, Communication, Network, or Shipping Failures ..............278Extensive Competition ..................................................................278Software Errors ..............................................................................279Evolving Governmental Policies and Taxes ..................................279System Capacity Limits ................................................................279
Deciding on a Strategy ......................................................................280Next ....................................................................................................280
13 E-commerce Security Issues 281How Important Is Your Information? ................................................282Security Threats ..................................................................................283
Exposure of Confidential Data ......................................................283Loss or Destruction of Data ..........................................................285Modification of Data ....................................................................286Denial of Service ..........................................................................287Errors in Software ........................................................................288Repudiation ....................................................................................289
Balancing Usability, Performance, Cost, and Security ......................290Creating a Security Policy ..................................................................291
xiii
00 7842 FM 3/6/01 3:38 PM Page xiii
PHP AND MYSQL WEB DEVELOPMENT
Authentication Principles ....................................................................291Using Authentication ..........................................................................292Encryption Basics ..............................................................................293Private Key Encryption ......................................................................294Public Key Encryption ........................................................................295Digital Signatures ..............................................................................296Digital Certificates ..............................................................................297Secure Web Servers ............................................................................298Auditing and Logging ........................................................................299Firewalls ..............................................................................................300Backing Up Data ................................................................................301
Backing Up General Files ............................................................301Backing Up and Restoring Your MySQL Database ......................301
Physical Security ................................................................................302Next ....................................................................................................302
14 Implementing Authentication with PHP and MySQL 303Identifying Visitors ............................................................................304Implementing Access Control ............................................................305
Storing Passwords ........................................................................308Encrypting Passwords ..................................................................310Protecting Multiple Pages ............................................................312
Basic Authentication ..........................................................................312Using Basic Authentication in PHP ....................................................314Using Basic Authentication with Apache’s .htaccess Files ................316Using Basic Authentication with IIS ..................................................319Using mod_auth_mysql Authentication ............................................321
Installing mod_auth_mysql ..........................................................322Did It Work? ..................................................................................323Using mod_auth_mysql ................................................................323
Creating Your Own Custom Authentication ......................................324Further Reading ..................................................................................324Next ....................................................................................................325
15 Implementing Secure Transactions with PHP and MySQL 327Providing Secure Transactions ..........................................................328
The User’s Machine ......................................................................329The Internet ..................................................................................330Your System ..................................................................................331
Using Secure Sockets Layer (SSL) ....................................................332Screening User Input ..........................................................................336Providing Secure Storage ..................................................................336Why Are You Storing Credit Card Numbers? ....................................338
xiv
00 7842 FM 3/6/01 3:38 PM Page xiv
CONTENTS
Using Encryption in PHP ..................................................................338Further Reading ..................................................................................347Next ....................................................................................................347
PART IV Advanced PHP Techniques 349
16 Interacting with the File System and the Server 351Introduction to File Upload ................................................................352
HTML for File Upload ..................................................................353Writing the PHP to Deal with the File ..........................................354Common Problems ........................................................................358
Using Directory Functions ..................................................................358Reading from Directories ..............................................................358Getting Info About the Current Directory ....................................360Creating and Deleting Directories ................................................360
Interacting with the File System ........................................................361Get File Info ..................................................................................361Changing File Properties ..............................................................364Creating, Deleting, and Moving Files ..........................................364
Using Program Execution Functions ..................................................365Interacting with the Environment: getenv() and putenv() ..................367Further Reading ..................................................................................368Next ....................................................................................................368
17 Using Network and Protocol Functions 369Overview of Protocols ........................................................................370Sending and Reading Email ..............................................................371Using Other Web Services ..................................................................371Using Network Lookup Functions ....................................................374Using FTP ..........................................................................................378
Using FTP to Back Up or Mirror a File ........................................378Uploading Files ............................................................................385Avoiding Timeouts ........................................................................385Using Other FTP Functions ..........................................................386
Generic Network Communications with cURL ................................387Further Reading ..................................................................................389Next ....................................................................................................390
18 Managing the Date and Time 391Getting the Date and Time from PHP ................................................392
Using the date() Function ..............................................................392Dealing with UNIX Time Stamps ................................................394Using the getdate() Function ........................................................395Validating Dates ............................................................................396
xv
00 7842 FM 3/6/01 3:38 PM Page xv
PHP AND MYSQL WEB DEVELOPMENT
Converting Between PHP and MySQL Date Formats ......................396Date Calculations ................................................................................398Using the Calendar Functions ............................................................399Further Reading ..................................................................................400Next ....................................................................................................400
19 Generating Images 401Setting Up Image Support in PHP ......................................................402Image Formats ....................................................................................403
JPEG ..............................................................................................403PNG ..............................................................................................403WBMP ..........................................................................................403GIF ................................................................................................404
Creating Images ..................................................................................404Creating a Canvas Image ..............................................................405Drawing or Printing Text onto the Image ....................................406Outputting the Final Graphic ........................................................408Cleaning Up ..................................................................................410
Using Automatically Generated Images in Other Pages ....................410Using Text and Fonts to Create Images ..............................................410
Setting Up the Base Canvas ..........................................................414Fitting the Text onto the Button ....................................................415Positioning the Text ......................................................................418Writing the Text onto the Button ..................................................419Finishing Up ..................................................................................419
Drawing Figures and Graphing Data ..................................................419Other Image Functions ......................................................................428Further Reading ..................................................................................428Next ....................................................................................................428
20 Using Session Control in PHP 429What Session Control Is ....................................................................430Basic Session Functionality ................................................................430
What Is a Cookie? ........................................................................431Setting Cookies from PHP ............................................................431Using Cookies with Sessions ........................................................432Storing the Session ID ..................................................................432
Implementing Simple Sessions ..........................................................433Starting a Session ..........................................................................433Registering Session Variables ........................................................433Using Session Variables ................................................................434Deregistering Variables and Destroying the Session ....................434
xvi
00 7842 FM 3/6/01 3:38 PM Page xvi
CONTENTS
Simple Session Example ....................................................................435Configuring Session Control ..............................................................437Implementing Authentication with Session Control ..........................438Further Reading ..................................................................................445Next ....................................................................................................445
21 Other Useful Features 447Using Magic Quotes ..........................................................................448Evaluating Strings: eval() ..................................................................449Terminating Execution: die and exit ..................................................450Serialization ........................................................................................450Getting Information About the PHP Environment ............................451
Finding Out What Extensions Are Loaded ..................................451Identifying the Script Owner ........................................................452Finding Out When the Script Was Modified ................................452
Loading Extensions Dynamically ......................................................453Temporarily Altering the Runtime Environment ................................453Source Highlighting ............................................................................454Next ....................................................................................................455
PART V Building Practical PHP and MySQL Projects 457
22 Using PHP and MySQL for Large Projects 459Applying Software Engineering to Web Development ......................460Planning and Running a Web Application Project ............................461Reusing Code ......................................................................................462Writing Maintainable Code ................................................................463
Coding Standards ..........................................................................463Breaking Up Code ........................................................................466Using a Standard Directory Structure ..........................................467Documenting and Sharing In-House Functions ............................467
Implementing Version Control ............................................................467Choosing a Development Environment ..............................................469Documenting Your Projects ................................................................470Prototyping ..........................................................................................471Separating Logic and Content ............................................................471Optimizing Code ................................................................................472
Using Simple Optimizations ........................................................472Using Zend Products ....................................................................473
Testing ................................................................................................474Further Reading ..................................................................................475Next ....................................................................................................475
xvii
00 7842 FM 3/6/01 3:38 PM Page xvii
PHP AND MYSQL WEB DEVELOPMENT
23 Debugging 477Programming Errors ..........................................................................478
Syntax Errors ................................................................................478Runtime Errors ..............................................................................480Logic Errors ..................................................................................485
Variable Debugging Aid ....................................................................486Error Reporting Levels ......................................................................489Altering the Error Reporting Settings ................................................490Triggering Your Own Errors ..............................................................492Handling Errors Gracefully ................................................................492Remote Debugging ............................................................................494Next ....................................................................................................495
24 Building User Authentication and Personalization 497The Problem ........................................................................................498Solution Components ..........................................................................499
User Identification and Personalization ........................................499Storing Bookmarks ........................................................................500Recommending Bookmarks ..........................................................500
Solution Overview ..............................................................................500Implementing the Database ................................................................502Implementing the Basic Site ..............................................................504Implementing User Authentication ....................................................506
Registering ....................................................................................507Logging In ....................................................................................513Logging Out ..................................................................................517Changing Passwords ......................................................................518Resetting Forgotten Passwords ......................................................521
Implementing Bookmark Storage and Retrieval ................................526Adding Bookmarks ........................................................................526Displaying Bookmarks ..................................................................529Deleting Bookmarks ......................................................................530
Implementing Recommendations ......................................................532Wrapping Up and Possible Extensions ..............................................537Next ....................................................................................................537
25 Building a Shopping Cart 539The Problem ........................................................................................540Solution Components ..........................................................................540
Building an Online Catalog ..........................................................540Tracking a User’s Purchases While She Shops ............................541Payment ........................................................................................541Administration Interface ................................................................542
xviii
00 7842 FM 3/6/01 3:38 PM Page xviii
CONTENTS
Solution Overview ..............................................................................542Implementing the Database ................................................................546Implementing the Online Catalog ......................................................548
Listing Categories ..........................................................................551Listing Books in a Category ..........................................................553Showing Book Details ..................................................................555
Implementing the Shopping Cart ........................................................556Using the show_cart.php Script ....................................................557Viewing the Cart ............................................................................560Adding Items to the Cart ..............................................................563Saving the Updated Cart ..............................................................565Printing a Header Bar Summary ..................................................566Checking Out ................................................................................566
Implementing Payment ......................................................................572Implementing an Administration Interface ........................................575Extending the Project ..........................................................................584Using an Existing System ..................................................................584Next ....................................................................................................585
26 Building a Content Management System 587The Problem ........................................................................................588Solution Requirements ........................................................................588Editing Content ..................................................................................589
Getting Content into the System ..................................................589Databases Versus File Storage ......................................................591Document Structure ......................................................................592
Using Metadata ..................................................................................592Formatting the Output ........................................................................593Image Manipulation ............................................................................594Solution Design/Overview ..................................................................596Designing the Database ......................................................................598Implementation ..................................................................................599
Front End ......................................................................................599Back End ......................................................................................603Searching ......................................................................................611Editor Screen ................................................................................614
Extending the Project ..........................................................................615
27 Building a Web-Based Email Service 617The Problem ........................................................................................618Solution Components ..........................................................................619Solution Overview ..............................................................................620Setting Up the Database ....................................................................622
xix
00 7842 FM 3/6/01 3:38 PM Page xix
PHP AND MYSQL WEB DEVELOPMENT
Script Architecture ..............................................................................623Logging In and Out ............................................................................629Setting Up Accounts ..........................................................................632
Creating a New Account ..............................................................634Modifying an Existing Account ....................................................636Deleting an Account ......................................................................636
Reading Mail ......................................................................................637Selecting an Account ....................................................................637Viewing Mailbox Contents ............................................................640Reading a Mail Message ..............................................................643Viewing Message Headers ............................................................647Deleting Mail ................................................................................648
Sending Mail ......................................................................................649Sending a New Message ..............................................................649Replying To or Forwarding Mail ..................................................651
Extending the Project ..........................................................................652Next ....................................................................................................653
28 Building a Mailing List Manager 655The Problem ........................................................................................656Solution Components ..........................................................................657
Setting Up a Database of Lists and Subscribers ..........................657File Upload ........................................................................................657Sending Mail with Attachments ........................................................658Solution Overview ..............................................................................658Setting Up the Database ....................................................................660Script Architecture ..............................................................................663Implementing Login ..........................................................................672
Creating a New Account ..............................................................673Logging In ....................................................................................675
Implementing User Functions ............................................................678Viewing Lists ................................................................................679Viewing List Information ..............................................................684Viewing List Archives ..................................................................686Subscribing and Unsubscribing ....................................................687Changing Account Settings ..........................................................689Changing Passwords ......................................................................689Logging Out ..................................................................................692
Implementing Administrative Functions ............................................693Creating a New List ......................................................................693Uploading a New Newsletter ........................................................695Handling Multiple File Upload ....................................................698
xx
00 7842 FM 3/6/01 3:38 PM Page xx
CONTENTS
Previewing the Newsletter ............................................................703Sending the Message ....................................................................704
Extending the Project ..........................................................................709Next ....................................................................................................709
29 Building Web Forums 711The Problem ........................................................................................712Solution Components ..........................................................................712Solution Overview ..............................................................................714Designing the Database ......................................................................716Viewing the Tree of Articles ..............................................................718
Expanding and Collapsing ............................................................721Displaying the Articles ..................................................................724Using the treenode Class ..............................................................725
Viewing Individual Articles ................................................................731Adding New Articles ..........................................................................734Extensions ..........................................................................................741Using an Existing System ..................................................................741Next ....................................................................................................742
30 Generating Personalized Documents in Portable Format (PDF) 743
The Problem ........................................................................................744Evaluating Document Formats ..........................................................745
Paper ..............................................................................................745ASCII ............................................................................................745HTML ............................................................................................745Word Processor Formats ..............................................................746Rich Text Format ..........................................................................746PostScript ......................................................................................747Portable Document Format ..........................................................748
Solution Components ..........................................................................749Question and Answer System ........................................................749Document Generation Software ....................................................749
Solution Overview ..............................................................................752Asking the Questions ....................................................................753Grading the Answers ....................................................................755Generating an RTF Certificate ......................................................758Generating a PDF Certificate from a Template ............................762Generating a PDF Document Using PDFlib ................................765A Hello World Script for PDFlib ..................................................766Generating Our Certificate with PDFlib ......................................770
xxi
00 7842 FM 3/6/01 3:38 PM Page xxi
PHP AND MYSQL WEB DEVELOPMENT
Problems with Headers ......................................................................777Extending the Project ..........................................................................778Further Reading ..................................................................................778
PART VI Appendixes 779
A Installing PHP 4 and MySQL 781Running PHP as a CGI Interpreter or Module ..................................782Installing Apache, PHP, and MySQL Under UNIX ..........................783
Apache and mod_SSL ..................................................................787httpd.conf File—Snippets ..............................................................790Is SSL Working? ............................................................................792
Installing Apache, PHP, and MySQL Under Windows ......................793Installing MySQL Under Windows ..............................................793Installing Apache Under Windows ................................................795Differences Between Apache for Windows and UNIX ................798Installing PHP for Windows ..........................................................799Installation Notes for Microsoft IIS ..............................................800Installation Notes for Microsoft PWS ..........................................802
Other Configurations ..........................................................................802
B Web Resources 803PHP Resources ....................................................................................804MySQL and SQL Specific Resources ................................................806Apache Resources ..............................................................................806Web Development ..............................................................................806
Index 807
xxii
00 7842 FM 3/6/01 3:38 PM Page xxii
About the AuthorsLaura Thomson is a lecturer in Web programming in the Department of Computer Science atRMIT University in Melbourne, Australia. She is also a partner in the award-winning Webdevelopment firm Tangled Web Design. Laura has previously worked for Telstra and theBoston Consulting Group. She holds a Bachelor of Applied Science (Computer Science)degree and a Bachelor of Engineering (Computer Systems Engineering) degree with honors,and is currently completing her Ph.D. in adaptive Web sites. In her spare time, she enjoyssleeping. Laura can be contacted at [email protected].
Luke Welling is a lecturer in software engineering and e-commerce in the School of Electricaland Computer Systems Engineering at RMIT University in Melbourne, Australia. He is also apartner in Tangled Web Design. He holds a Bachelor of Applied Science (Computer Science)degree and is currently completing a master’s degree in Genetic Algorithms for CommunicationNetwork Design. In his spare time, he attempts to perfect his insomnia. Luke can be contactedat [email protected].
About the ContributorsIsrael Denis Jr. is a freelance consultant working on e-commerce projects throughout theworld. He specializes in integrating ERP packages such as SAP and Lawson with custom Websolutions. He obtained a master’s degree in Electrical Engineering from Georgia Tech inAtlanta, Georgia in 1998. He is the author of numerous articles about Linux, Apache, PHP, andMySQL and can be reached via email at [email protected].
Chris Newman is a consultant programmer specializing in the development of dynamicInternet applications. He has extensive commercial experience in using PHP and MySQL toproduce a wide range of applications for an international client base. A graduate of KeeleUniversity, he lives in Stoke-on-Trent, England, where he runs Lightwood Consultancy Ltd.More information on Lightwood Consultancy Ltd can be found at http://www.lightwood.net, and Newman can be contacted at [email protected].
00 7842 FM 3/6/01 3:38 PM Page xxiii
DedicationTo our Mums and Dads.
AcknowledgmentsWe would like to thank the team at Sams for all their hard work. In particular, we would like tothank Shelley Johnston Markanday without whose dedication and patience this book would nothave been possible. We would also like to thank Israel Denis Jr. and Chris Newman for theirvaluable contributions.
We appreciate immensely the work done by the PHP and MySQL development teams. Theirwork has made our lives easier for a number of years now, and continues to do so on a dailybasis.
We thank Adrian Close at eSec for saying “You can build that in PHP” back in 1998. We alsothank James Woods and all the staff at Law Partners for giving us such interesting work to testthe boundaries of PHP with.
Finally, we would like to thank our family and friends for putting up with us while we havebeen antisocial for the better part of a year. Specifically, thank you for your support to ourfamily members: Julie, Robert, Martin, Lesley, Adam, Paul, Sandi, James, and Archer.
00 7842 FM 3/6/01 3:38 PM Page xxiv
Tell Us What You Think!As the reader of this book, you are our most important critic and commentator. We value youropinion and want to know what we’re doing right, what we could do better, what areas you’dlike to see us publish in, and any other words of wisdom you’re willing to pass our way.
You can email or write me directly to let me know what you did or didn’t like about thisbook—as well as what we can do to make our books stronger.
Please note that I cannot help you with technical problems related to the topic of this book,and that due to the high volume of mail I receive, I might not be able to reply to every message.
When you write, please be sure to include this book’s title and author as well as your nameand phone or email address. I will carefully review your comments and share them with theauthor and editors who worked on the book.
E-mail: [email protected]
Mail: Mark TaberAssociate PublisherSams Publishing201 West 103rd StreetIndianapolis, IN 46290 USA
00 7842 FM 3/6/01 3:38 PM Page xxv
00 7842 FM 3/6/01 3:38 PM Page xxvi
IntroductionWelcome to PHP and MySQL Web Development. Within its pages, you will find distilledknowledge from our experiences using PHP and MySQL, two of the hottest Web developmenttools around.
In this introduction, we’ll cover
• Why you should read this book
• What you will be able to achieve using this book
• What PHP and MySQL are and why they’re great
• An overview of the new features of PHP 4
• How this book is organized
Let’s get started.
Why You Should Read This BookThis book will teach you how to create interactive Web sites from the simplest order formthrough to complex secure e-commerce sites. What’s more, you’ll learn how to do it using OpenSource technologies.
This book is aimed at readers who already know at least the basics of HTML and have donesome programming in a modern programming language before, but have not necessarily pro-grammed for the Internet or used a relational database. If you are a beginning programmer, youshould still find this book useful, but it might take you a little longer to digest. We’ve tried notto leave out any basic concepts, but we do cover them at speed. The typical reader of this bookis someone who wants to master PHP and MySQL for the purpose of building a large or com-mercial Web site. You might already be working in another Web development language; if so,this book should get you up to speed quickly.
We wrote this book because we were tired of finding books on PHP that were basically a func-tion reference. These books are useful, but they don’t help when your boss or client has said“Go build me a shopping cart.” We have done our best to make every example useful. Many ofthe code samples can be directly used in your Web site, and many others can be used withminor modifications.
What You Will Be Able to Achieve Using This BookReading this book will enable you to build real-world, dynamic Web sites. If you’ve built Websites using plain HTML, you will realize the limitations of this approach. Static content from apure HTML Web site is just that—static. It stays the same unless you physically update it. Yourusers can’t interact with the site in any meaningful fashion.
01 7842 intro 3/6/01 3:33 PM Page 1
PHP AND MYSQL WEB DEVELOPMENT
Using a language such as PHP and a database such as MySQL allows you to make your sitesdynamic: to have them be customizable and contain real-time information.
We have deliberately focused this book on real-world applications, even in the introductory chap-ters. We’ll begin by looking at a simple online ordering system, and work our way through thevarious parts of PHP and MySQL.
We will then discuss aspects of electronic commerce and security as they relate to building a real-world Web site, and show you how to implement these aspects in PHP and MySQL.
In the final section of this book, we will talk about how to approach real-world projects, and takeyou through the design, planning, and building of the following seven projects:
• User authentication and personalization
• Shopping carts
• Content management systems
• Web-based email
• Mailing list managers
• Web forums
• Document generation
Any of these projects should be usable as is, or can be modified to suit your needs. We chose thembecause we believe they represent seven of the most common Web-based applications built byprogrammers. If your needs are different, this book should help you along the way to achievingyour goals.
What Is PHP?PHP is a server-side scripting language designed specifically for the Web. Within an HTML page,you can embed PHP code that will be executed each time the page is visited. Your PHP code isinterpreted at the Web server and generates HTML or other output that the visitor will see.
PHP was conceived in 1994 and was originally the work of one man, Rasmus Lerdorf. It wasadopted by other talented people and has gone through three major rewrites to bring us the broad,mature product we see today. As of January 2001, it was in use on nearly five million domainsworldwide, and this number is growing rapidly. You can see the current number at http://www.php.net/usage.php
PHP is an Open Source product. You have access to the source code. You can use it, alter it, andredistribute it all without charge.
PHP originally stood for Personal Home Page, but was changed in line with the GNU recursivenaming convention (GNU = Gnu’s Not Unix) and now stands for PHP Hypertext Preprocessor.
The current major version of PHP is 4. This version has seen some major improvements to thelanguage, discussed in the next section.
2
01 7842 intro 3/6/01 3:33 PM Page 2
INTRODUCTION
The home page for PHP is available at http://www.php.net
The home page for Zend is at http://www.zend.com
What’s New In PHP Version 4?If you have used PHP before, you will notice a few important improvements in version 4. In thisnew version
• PHP 4 is much faster than previous versions because it uses the new Zend Engine. If youneed even higher performance, you can obtain the Zend Optimizer, Zend Cache, or ZendCompiler from http://www.zend.com.
• You have always been able to use PHP as an efficient module for the Apache server. Withthis new version, you can install PHP as an ISAPI module for Microsoft’s InternetInformation Server.
• Session support is now built in. In previous versions, you needed to install the PHPlib add-on for session control or write your own.
What Is MySQL?MySQL (pronounced My-Ess-Que-Ell) is a very fast, robust, relational database management sys-tem (RDBMS). A database enables you to efficiently store, search, sort, and retrieve data. TheMySQL server controls access to your data to ensure that multiple users can work with it concur-rently, to provide fast access to it, and ensure that only authorized users can obtain access. Hence,MySQL is a multi-user, multi-threaded server. It uses SQL (Structured Query Language), the stan-dard database query language worldwide. MySQL has been publicly available since 1996, but hasa development history going back to 1979. It has now won the Linux Journal Readers’ ChoiceAward three years running.
MySQL is now available under an Open Source license, but commercial licenses are also availableif required.
Why Use PHP and MySQL?When setting out to build an e-commerce site, there are many different products that you could use.
You will need to choose hardware for the Web server, an operating system, Web server software, adatabase management system, and a programming or scripting language.
Some of these choices will be dependent on the others. For example, not all operating systems willrun on all hardware, not all scripting languages can connect to all databases, and so on.
In this book, we do not pay much attention to your hardware, operating system, or Web serversoftware. We don’t need to. One of the nice features of PHP is that it is available for MicrosoftWindows, for many versions of UNIX, and with any fully-functional Web server. MySQL is similarly versatile.
3
01 7842 intro 3/6/01 3:33 PM Page 3
PHP AND MYSQL WEB DEVELOPMENT
To demonstrate this, the examples in this book have been written and tested on two popular setups:
• Linux using the Apache Web server
• Microsoft Windows 2000 using Microsoft Internet Information Server (IIS)
Whatever hardware, operating system, and Web server you choose, we believe you should seri-ously consider using PHP and MySQL.
Some of PHP’s StrengthsSome of PHP’s main competitors are Perl, Microsoft Active Server Pages (ASP), Java ServerPages (JSP), and Allaire Cold Fusion.
In comparison to these products, PHP has many strengths including the following:
• High performance
• Interfaces to many different database systems
• Built-in libraries for many common Web tasks
• Low cost
• Ease of learning and use
• Portability
• Availability of source code
A more detailed discussion of these strengths follows.
PerformancePHP is very efficient. Using a single inexpensive server, you can serve millions of hits per day.Benchmarks published by Zend Technologies (http://www.zend.com) show PHP outperformingits competition.
Database IntegrationPHP has native connections available to many database systems. In addition to MySQL, you candirectly connect to PostgreSQL, mSQL, Oracle, dbm, filePro, Hyperwave, Informix, InterBase,and Sybase databases, among others.
Using the Open Database Connectivity Standard (ODBC), you can connect to any database thatprovides an ODBC driver. This includes Microsoft products, and many others.
Built-in LibrariesBecause PHP was designed for use on the Web, it has many built-in functions for performingmany useful Web-related tasks. You can generate GIF images on-the-fly, connect to other net-work services, send email, work with cookies, and generate PDF documents, all with just a fewlines of code.
4
01 7842 intro 3/6/01 3:33 PM Page 4
INTRODUCTION
CostPHP is free. You can download the latest version at any time from http://www.php.net forno charge.
Learning PHPThe syntax of PHP is based on other programming languages, primarily C and Perl. If you alreadyknow C or Perl, or a C-like language such as C++ or Java, you will be productive using PHPalmost immediately.
PortabilityPHP is available for many different operating systems. You can write PHP code on the free Unix-like operating systems such as Linux and FreeBSD, commercial Unix versions such as Solaris andIRIX, or on different versions of Microsoft Windows.
Your code will usually work without modification on a different system running PHP.
Source CodeYou have access to the source code of PHP. Unlike commercial, closed-source products, if there issomething you want modified or added to the language, you are free to do this.
You do not need to wait for the manufacturer to release patches. You don’t need to worry about themanufacturer going out of business or deciding to stop supporting a product.
Some of MySQL’s StrengthsSome of MySQL’s main competitors are PostgreSQL, Microsoft SQL Server, and Oracle.
MySQL has many strengths, including high performance, low cost, easy to configure and learn,portable, and the source code is available.
A more detailed discussion of these strengths follows.
PerformanceMySQL is undeniably fast. You can see the developers’ benchmark page athttp://web.mysql.com/benchmark.html. Many of these benchmarks show MySQL to be ordersof magnitude faster than the competition.
Low CostMySQL is available at no cost, under an Open Source license, or at low cost under a commerciallicense if required for your application.
5
01 7842 intro 3/6/01 3:33 PM Page 5
PHP AND MYSQL WEB DEVELOPMENT
Ease of UseMost modern databases use SQL. If you have used another RDBMS, you should have no troubleadapting to this one. MySQL is also easier to set up than many similar products.
PortabilityMySQL can be used on many different UNIX systems as well as under Microsoft Windows.
Source CodeAs with PHP, you can obtain and modify the source code for MySQL.
How Is This Book Organized?This book is divided into five main sections.
Part I, “Using PHP,” gives an overview of the main parts of the PHP language with examples.Each of the examples will be a real-world example used in building an e-commerce site, ratherthan “toy” code. We’ll kick this section off with Chapter 1, “PHP Crash Course.” If you’ve alreadyused PHP, you can whiz through this section. If you are new to PHP or new to programming, youmight want to spend a little more time on it.
Part II, “Using MySQL,” discusses the concepts and design involved in using relational databasesystems such as MySQL, using SQL, connecting your MySQL database to the world with PHP,and advanced MySQL topics, such as security and optimization.
Part III, “E-Commerce and Security,” covers some of the general issues involved in developing ane-commerce site using any language. The most important of these issues is security. We then dis-cuss how you can use PHP and MySQL to authenticate your users and securely gather, transmit,and store data.
Part IV, “Advanced PHP Techniques,” offers detailed coverage of some of the major built-in func-tions in PHP. We have selected groups of functions that are likely to be useful when building an e-commerce site. You will learn about interaction with the server, interaction with the network,image generation, date and time manipulation, and session variables.
Part V, “Building Practical PHP and MySQL Projects,” deals with practical real-world issues suchas managing large projects and debugging, and provides sample projects that demonstrate thepower and versatility of PHP and MySQL.
FinallyWe hope you enjoy this book, and enjoy learning about PHP and MySQL as much as we didwhen we first began using these products. They are really a pleasure to use. Soon, you’ll beable to join the thousands of Web developers who use these robust, powerful tools to easilybuild dynamic, real-time Web sites.
6
01 7842 intro 3/6/01 3:33 PM Page 6
IN THIS PART1 PHP Crash Course 9
2 Storing and Retrieving Data 49
3 Using Arrays 69
4 String Manipulation and Regular Expressions 93
5 Reusing Code and Writing Functions 117
6 Object-Oriented PHP 147
Using PHPPART
I
02 7842 part 1 3/6/01 3:42 PM Page 7
02 7842 part 1 3/6/01 3:42 PM Page 8
CHAPTER
1PHP Crash Course
03 7842 CH01 3/6/01 3:39 PM Page 9
Using PHP
PART I10
This chapter gives you a quick overview of PHP syntax and language constructs. If you arealready a PHP programmer, it might fill some gaps in your knowledge. If you have a back-ground using C, ASP, or another programming language, it will help you get up to speedquickly.
In this book, you’ll learn how to use PHP by working through lots of real world examples,taken from our experience in building e-commerce sites. Often programming textbooks teachbasic syntax with very simple examples. We have chosen not to do that. We recognize thatoften what you want to do is get something up and running, to understand how the language isused, rather than ploughing through yet another syntax and function reference that’s no betterthan the online manual.
Try the examples out—type them in or load them from the CD-ROM, change them, breakthem, and learn how to fix them again.
In this chapter, we’ll begin with the example of an online product order form to learn howvariables, operators, and expressions are used in PHP. We will also cover variable types andoperator precedence. You will learn how to access form variables and how to manipulate themby working out the total and tax on a customer order.
We will then develop the online order