Loading ...
Global Do...
News & Politics
4
0
Try Now
Log In
Pricing
Luke Welling and Laura Thomson 201 West 103rd St., Indianapolis, Indiana, 46290 USA PHP and MySQL Web Development 0 0 7 8 4 2 F M 3 / 6 / 0 1 3 : 3 8 P M P a g e i PHP and MySQL Web Development Copyright © 2001 by Sams Publishing All rights reserved. No part of this book shall be reproduced, stored in a retrieval 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 information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Neither is any liability assumed for damages resulting from the use of 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 Trademarks All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Sams Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark. Warning and Disclaimer Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The information provided is on an “as is” basis. The authors and the publisher shall have neither liability nor responsibility 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 EDITOR Shelley Johnston Markanday DEVELOPMENT EDITOR Scott D. Meyers MANAGING EDITOR Charlotte Clapp COPY EDITOR Rhonda Tinch-Mize INDEXER Kelly Castell PROOFREADERS Kathy Bidwell Tony Reitz TECHNICAL EDITORS Israel Denis Chris Newman TEAM COORDINATOR Amy Patton SOFTWARE DEVELOPMENT SPECIALIST Dan Scherf INTERIOR DESIGN Anne Jones COVER DESIGN Anne Jones PRODUCTION Ayanna Lacey Heather Hiatt Miller Stacey Richwine-DeRome 0 0 7 8 4 2 F M 3 / 6 / 0 1 3 : 3 8 P M P a g e i i Overview Introduction 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 0 0 7 8 4 2 F M 3 / 6 / 0 1 3 : 3 8 P M P a g e i i i 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 0 0 7 8 4 2 F M 3 / 6 / 0 1 3 : 3 8 P M P a g e i v Contents Introduction 1 Who Should Read This Book? ..............................................................1 What Is PHP? ..........................................................................................1 What Is MySQL? ....................................................................................2 Why Use PHP and MySQL? ..................................................................2 Some of PHP’s Strengths ........................................................................3 Performance ......................................................................................3 Database Integration ..........................................................................3 Built-In Libraries ..............................................................................4 Cost ....................................................................................................4 Learning PHP ....................................................................................4 Portability ..........................................................................................4 Source Code ......................................................................................4 Some of MySQL’s Strengths ..................................................................4 Performance ......................................................................................5 Low Cost ..........................................................................................5 Ease of Use ........................................................................................5 Portability ..........................................................................................5 Source Code ......................................................................................5 How Is This Book Organized? ..............................................................5 What’s New in PHP Version 4? ..............................................................6 Finally ....................................................................................................6 PART I Using PHP 7 1 PHP Crash Course 9 Using PHP ............................................................................................11 Sample Application: Bob’s Auto Parts ................................................11 The Order Form ..............................................................................11 Processing the Form ........................................................................13 Embedding PHP in HTML ..................................................................13 Using PHP Tags ..............................................................................14 PHP Tag Styles ................................................................................15 PHP Statements ..............................................................................15 Whitespace ......................................................................................16 Comments ........................................................................................16 Adding Dynamic Content ....................................................................17 Calling Functions ............................................................................18 The date() Function ........................................................................18 0 0 7 8 4 2 F M 3 / 6 / 0 1 3 : 3 8 P M P a g e v PHP AND MYSQL WEB DEVELOPMENT vi Accessing Form Variables ....................................................................19 Form Variables ................................................................................19 String Concatenation ......................................................................20 Variables and Literals ......................................................................21 Identifiers ..............................................................................................21 User-Declared Variables ......................................................................22 Assigning Values to Variables ..............................................................22 Variable Types ......................................................................................22 PHP’s Data Types ............................................................................22 Type Strength ..................................................................................23 Type Casting ....................................................................................23 Variable Variables ............................................................................23 Constants ..............................................................................................24 Variable Scope ......................................................................................25 Operators ..............................................................................................25 Arithmetic Operators ......................................................................26 String Operators ..............................................................................27 Assignment Operators ....................................................................27 Comparison Operators ....................................................................29 Logical Operators ............................................................................30 Bitwise Operators ............................................................................31 Other Operators ..............................................................................32 Using Operators: Working Out the Form Totals ..................................33 Precedence and Associativity: Evaluating Expressions ........................34 Variable Functions ................................................................................36 Testing and Setting Variable Types ................................................36 Testing Variable Status ....................................................................37 Reinterpreting Variables ..................................................................37 Control Structures ................................................................................38 Making Decisions with Conditionals ..................................................38 if Statements ....................................................................................38 Code Blocks ....................................................................................38 A Side Note: Indenting Your Code ................................................39 else Statements ................................................................................39 elseif Statements ..............................................................................40 switch Statements ............................................................................41 Comparing the Different Conditionals ............................................42 Iteration: Repeating Actions ................................................................43 while Loops ....................................................................................44 for Loops ........................................................................................45 do..while Loops ..............................................................................46 0 0 7 8 4 2 F M 3 / 6 / 0 1 3 : 3 8 P M P a g e v i CONTENTS vii Breaking Out of a Control Structure or Script ....................................47 Next: Saving the Customer’s Order ......................................................47 2 Storing and Retrieving Data 49 Saving Data for Later ..........................................................................50 Storing and Retrieving Bob’s Orders ..................................................50 Overview of File Processing ................................................................52 Opening a File ......................................................................................52 File Modes ......................................................................................52 Using fopen() to Open a File ..........................................................53 Opening Files for FTP or HTTP ....................................................54 Problems Opening Files ..................................................................55 Writing to a File ....................................................................................57 Parameters for fwrite() ....................................................................57 File Formats ....................................................................................58 Closing a File ........................................................................................58 Reading from a File ..............................................................................59 Opening a File for Reading: fopen() ..............................................60 Knowing When to Stop: feof() ........................................................60 Reading a Line at a Time: fgets(), fgetss(), and fgetcsv() ..............60 Reading the Whole File: readfile(), fpassthru(), file() ....................61 Reading a Character: fgetc() ..........................................................62 Reading an Arbitrary Length: fread() ..............................................63 Other Useful File Functions ................................................................63 Checking Whether a File Is There: file_exists() ............................63 Knowing How Big a File Is: filesize() ............................................63 Deleting a File: unlink() ..................................................................63 Navigating Inside a File: rewind(), fseek(), and ftell() ..................64 File Locking ..........................................................................................65 Doing It a Better Way: Database Management Systems ......................66 Problems with Using Flat Files ......................................................66 How RDBMSs Solve These Problems ............................................67 Further Reading ....................................................................................67 Next ......................................................................................................67 3 Using Arrays 69 What Is an Array? ................................................................................70 Numerically Indexed Arrays ................................................................71 Initializing Numerically Indexed Arrays ........................................71 Accessing Array Contents ..............................................................72 Using Loops to Access the Array ....................................................73 0 0 7 8 4 2 F M 3 / 6 / 0 1 3 : 3 8 P M P a g e v i i PHP AND MYSQL WEB DEVELOPMENT viii Associative Arrays ................................................................................73 Initializing an Associative Array ....................................................73 Accessing the Array Elements ........................................................73 Using Loops with each() and list() ..................................................74 Multidimensional Arrays ......................................................................75 Sorting Arrays ......................................................................................79 Using sort() ......................................................................................79 Using asort() and ksort() to Sort Associative Arrays ......................79 Sorting in Reverse ..........................................................................80 Sorting Multidimensional Arrays ........................................................80 User Defined Sorts ..........................................................................80 Reverse User Sorts ..........................................................................82 Reordering Arrays ................................................................................83 Using shuffle() ................................................................................83 Using array_reverse() ......................................................................84 Loading Arrays from Files ....................................................................85 Other 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() ............................91 Further Reading ....................................................................................92 Next ......................................................................................................92 4 String Manipulation and Regular Expressions 93 Example Application: Smart Form Mail ..............................................94 Formatting Strings ................................................................................96 Trimming Strings: chop(), ltrim(), and trim() ................................96 Formatting Strings for Presentation ................................................97 Formatting Strings for Storage: AddSlashes() and StripSlashes() 100 Joining and Splitting Strings with String Functions ..........................101 Using explode(), implode(), and join() ........................................102 Using strtok() ................................................................................102 Using substr() ................................................................................103 Comparing Strings ..............................................................................104 String Ordering: strcmp(),strcasecmp(), and strnatcmp() ............104 Testing String Length with strlen() ..............................................105 Matching and Replacing Substrings with String Functions ..............105 Finding Strings in Strings: strstr(), strchr(), strrchr(), stristr() ......106 Finding the Position of a Substring: strpos(), strrpos() ................107 Replacing Substrings: str_replace(), substr_replace() ..................108 0 0 7 8 4 2 F M 3 / 6 / 0 1 3 : 3 8 P M P a g e v i i i CONTENTS ix Introduction to Regular Expressions ..................................................109 The Basics ....................................................................................109 Character Sets and Classes ............................................................110 Repetition ......................................................................................111 Subexpressions ..............................................................................111 Counted Subexpressions ................................................................112 Anchoring to the Beginning or End of a String ............................112 Branching ......................................................................................112 Matching Literal Special Characters ............................................112 Summary of Special Characters ....................................................113 Putting It All Together for the Smart Form ..................................113 Finding Substrings with Regular Expressions ....................................114 Replacing Substrings with Regular Expressions ................................115 Splitting Strings with Regular Expressions ........................................115 Comparison of String Functions and Regular Expression Functions ..........................................................................................116 Further Reading ..................................................................................116 Next ....................................................................................................116 5 Reusing Code and Writing Functions 117 Why Reuse Code? ..............................................................................118 Cost ................................................................................................118 Reliability ......................................................................................119 Consistency ....................................................................................119 Using require() and include() ............................................................119 Using require() ..............................................................................119 File Name Extensions and Require() ............................................120 PHP Tags and require() ................................................................121 Using require() for Web Site Templates ............................................121 Using auto_prepend_file and auto_append_file ............................126 Using include() ..............................................................................127 Using Functions in PHP ....................................................................129 Calling Functions ..........................................................................129 Call to Undefined Function ..........................................................131 Case and Function Names ............................................................132 Why Should You Define Your Own Functions? ................................132 Basic Function Structure ....................................................................132 Naming Your Function ..................................................................133 Parameters ..........................................................................................134 Scope ..................................................................................................136 Pass by Reference Versus Pass by Value ............................................138 Returning from Functions ..................................................................140 0 0 7 8 4 2 F M 3 / 6 / 0 1 3 : 3 8 P M P a g e i x PHP AND MYSQL WEB DEVELOPMENT x Returning Values from Functions ......................................................141 Code Blocks ..................................................................................142 Recursion ............................................................................................143 Further Reading ..................................................................................145 Next ....................................................................................................145 6 Object-Oriented PHP 147 Object-Oriented Concepts ..................................................................148 Classes and Objects ......................................................................148 Polymorphism ................................................................................149 Inheritance ....................................................................................150 Creating Classes, Attributes, Operations in PHP ..............................150 Structure of a Class ......................................................................151 Constructors ..................................................................................151 Instantiation ........................................................................................152 Using Class Attributes ........................................................................152 Calling Class Operations ....................................................................154 Implementing Inheritance in PHP ......................................................155 Overriding ......................................................................................156 Multiple Inheritance ......................................................................157 Designing Classes ..............................................................................158 Writing the Code for Your Class ........................................................159 Next ....................................................................................................168 PART II Using MySQL 169 7 Designing Your Web Database 171 Relational Database Concepts ............................................................172 Tables ............................................................................................173 Columns ........................................................................................173 Rows ..............................................................................................173 Values ............................................................................................173 Keys ..............................................................................................173 Schemas ........................................................................................175 Relationships ................................................................................175 How to Design Your Web Database ....................................................176 Think About the Real World Objects You Are Modeling ............176 Avoid Storing Redundant Data ....................................................176 Use Atomic Column Values ..........................................................178 Choose Sensible Keys ..................................................................179 Think About the Questions You Want to Ask the Database ..........179 Avoid Designs with Many Empty Attributes ................................179 Summary of Table Types ..............................................................180 0 0 7 8 4 2 F M 3 / 6 / 0 1 3 : 3 8 P M P a g e x CONTENTS xi Web Database Architecture ................................................................180 Architecture ..................................................................................180 Further Reading ..................................................................................182 Next ....................................................................................................182 8 Creating Your Web Database 183 A Note on Using the MySQL Monitor ..............................................185 How to Log In to MySQL ..................................................................185 Creating Databases and Users ............................................................187 Creating the Database ....................................................................187 Users and Privileges ..........................................................................187 Introduction to MySQL’s Privilege System ........................................188 Principle of Least Privilege ..........................................................188 Setting Up Users: The GRANT Command ..................................188 Types and Levels of Privilege ......................................................190 The REVOKE Command ..............................................................192 Examples Using GRANT and REVOKE ......................................192 Setting Up a User for the Web ............................................................193 Logging Out As root ......................................................................193 Using the Right Database ..................................................................193 Creating Database Tables ....................................................................194 What the Other Keywords Mean ..................................................196 Understanding the Column Types ................................................196 Looking at the Database with SHOW and DESCRIBE ................198 MySQL Identifiers ..............................................................................199 Column Data Types ............................................................................200 Numeric Types ..............................................................................201 Further Reading ..................................................................................206 Next ....................................................................................................206 9 Working with Your MySQL Database 207 What Is SQL? ....................................................................................208 Inserting Data into the Database ........................................................209 Retrieving Data from the Database ....................................................211 Retrieving Data with Specific Criteria ..........................................212 Retrieving Data from Multiple Tables ..........................................214 Retrieving Data in a Particular Order ............................................219 Grouping and Aggregating Data ..................................................220 Choosing Which Rows to Return ..................................................222 Updating Records in the Database ....................................................223 Altering Tables After Creation ............................................................223 Deleting Records from the Database ..................................................225 Dropping Tables ..................................................................................226 0 0 7 8 4 2 F M 3 / 6 / 0 1 3 : 3 8 P M P a g e x i PHP AND MYSQL WEB DEVELOPMENT Dropping a Whole Database ..............................................................226 Further Reading ..................................................................................226 Next ....................................................................................................226 10 Accessing Your MySQL Database from the Web with PHP 227 How Web Database Architectures Work ............................................228 The Basic Steps in Querying a Database from the Web ....................................................................................232 Checking and Filtering Input Data ....................................................232 Setting Up a Connection ....................................................................234 Choosing a Database to Use ..............................................................235 Querying the Database ........................................................................235 Retrieving the Query Results ..............................................................236 Disconnecting from the Database ......................................................238 Putting New Information in the Database ..........................................238 Other Useful PHP-MySQL Functions ................................................241 Freeing Up Resources ..................................................................241 Creating and Deleting Databases ..................................................242 Other PHP-Database Interfaces ..........................................................242 Further Reading ..................................................................................242 Next ....................................................................................................243 11 Advanced MySQL 245 Understanding the Privilege System in Detail ....................................246 The user Table ..............................................................................247 The db and host Tables ..................................................................248 The tables_priv and columns_priv Tables ....................................249 Access Control: How MySQL Uses the Grant Tables ..................250 Updating Privileges: When Do Changes Take Effect? ..................251 Making Your MySQL Database Secure ............................................251 MySQL from the Operating System’s Point of View ..................252 Passwords ......................................................................................252 User Privileges ..............................................................................253 Web Issues ....................................................................................253 Getting More Information About Databases ......................................254 Getting Information with SHOW ..................................................254 Getting Information About Columns with DESCRIBE ................257 Understanding How Queries Work with EXPLAIN ....................257 Speeding Up Queries with Indexes ....................................................261 General Optimization Tips ..................................................................261 Design Optimization ......................................................................261 Permissions ....................................................................................261 xii 0 0 7 8 4 2 F M 3 / 6 / 0 1 3 : 3 8 P M P a g e x i i CONTENTS Table Optimization ........................................................................262 Using Indexes ................................................................................262 Use Default Values ........................................................................262 Use Persistent Connections ..........................................................262 Other Tips ......................................................................................262 Different Table Types ..........................................................................263 Loading Data from a File ..................................................................263 Further Reading ..................................................................................264 Next ....................................................................................................264 PART III E-commerce and Security 265 12 Running an E-commerce Site 267 What Do You Want to Achieve? ........................................................268 Types of Commercial Web Sites ........................................................268 Online Brochures ..........................................................................269 Taking Orders for Goods or Services ............................................271 Providing Services and Digital Goods ..........................................275 Adding Value to Goods or Services ..............................................276 Cutting Costs ................................................................................276 Risks and Threats ................................................................................277 Crackers ........................................................................................277 Failing to Attract Sufficient Business ............................................278 Computer Hardware Failure ..........................................................278 Power, Communication, Network, or Shipping Failures ..............278 Extensive Competition ..................................................................278 Software Errors ..............................................................................279 Evolving Governmental Policies and Taxes ..................................279 System Capacity Limits ................................................................279 Deciding on a Strategy ......................................................................280 Next ....................................................................................................280 13 E-commerce Security Issues 281 How Important Is Your Information? ................................................282 Security Threats ..................................................................................283 Exposure of Confidential Data ......................................................283 Loss or Destruction of Data ..........................................................285 Modification of Data ....................................................................286 Denial of Service ..........................................................................287 Errors in Software ........................................................................288 Repudiation ....................................................................................289 Balancing Usability, Performance, Cost, and Security ......................290 Creating a Security Policy ..................................................................291 xiii 0 0 7 8 4 2 F M 3 / 6 / 0 1 3 : 3 8 P M P a g e x i i i PHP AND MYSQL WEB DEVELOPMENT Authentication Principles ....................................................................291 Using Authentication ..........................................................................292 Encryption Basics ..............................................................................293 Private Key Encryption ......................................................................294 Public Key Encryption ........................................................................295 Digital Signatures ..............................................................................296 Digital Certificates ..............................................................................297 Secure Web Servers ............................................................................298 Auditing and Logging ........................................................................299 Firewalls ..............................................................................................300 Backing Up Data ................................................................................301 Backing Up General Files ............................................................301 Backing Up and Restoring Your MySQL Database ......................301 Physical Security ................................................................................302 Next ....................................................................................................302 14 Implementing Authentication with PHP and MySQL 303 Identifying Visitors ............................................................................304 Implementing Access Control ............................................................305 Storing Passwords ........................................................................308 Encrypting Passwords ..................................................................310 Protecting Multiple Pages ............................................................312 Basic Authentication ..........................................................................312 Using Basic Authentication in PHP ....................................................314 Using Basic Authentication with Apache’s .htaccess Files ................316 Using Basic Authentication with IIS ..................................................319 Using mod_auth_mysql Authentication ............................................321 Installing mod_auth_mysql ..........................................................322 Did It Work? ..................................................................................323 Using mod_auth_mysql ................................................................323 Creating Your Own Custom Authentication ......................................324 Further Reading ..................................................................................324 Next ....................................................................................................325 15 Implementing Secure Transactions with PHP and MySQL 327 Providing Secure Transactions ..........................................................328 The User’s Machine ......................................................................329 The Internet ..................................................................................330 Your System ..................................................................................331 Using Secure Sockets Layer (SSL) ....................................................332 Screening User Input ..........................................................................336 Providing Secure Storage ..................................................................336 Why Are You Storing Credit Card Numbers? ....................................338 xiv 0 0 7 8 4 2 F M 3 / 6 / 0 1 3 : 3 8 P M P a g e x i v CONTENTS Using Encryption in PHP ..................................................................338 Further Reading ..................................................................................347 Next ....................................................................................................347 PART IV Advanced PHP Techniques 349 16 Interacting with the File System and the Server 351 Introduction to File Upload ................................................................352 HTML for File Upload ..................................................................353 Writing the PHP to Deal with the File ..........................................354 Common Problems ........................................................................358 Using Directory Functions ..................................................................358 Reading from Directories ..............................................................358 Getting Info About the Current Directory ....................................360 Creating and Deleting Directories ................................................360 Interacting with the File System ........................................................361 Get File Info ..................................................................................361 Changing File Properties ..............................................................364 Creating, Deleting, and Moving Files ..........................................364 Using Program Execution Functions ..................................................365 Interacting with the Environment: getenv() and putenv() ..................367 Further Reading ..................................................................................368 Next ....................................................................................................368 17 Using Network and Protocol Functions 369 Overview of Protocols ........................................................................370 Sending and Reading Email ..............................................................371 Using Other Web Services ..................................................................371 Using Network Lookup Functions ....................................................374 Using FTP ..........................................................................................378 Using FTP to Back Up or Mirror a File ........................................378 Uploading Files ............................................................................385 Avoiding Timeouts ........................................................................385 Using Other FTP Functions ..........................................................386 Generic Network Communications with cURL ................................387 Further Reading ..................................................................................389 Next ....................................................................................................390 18 Managing the Date and Time 391 Getting the Date and Time from PHP ................................................392 Using the date() Function ..............................................................392 Dealing with UNIX Time Stamps ................................................394 Using the getdate() Function ........................................................395 Validating Dates ............................................................................396 xv 0 0 7 8 4 2 F M 3 / 6 / 0 1 3 : 3 8 P M P a g e x v PHP AND MYSQL WEB DEVELOPMENT Converting Between PHP and MySQL Date Formats ......................396 Date Calculations ................................................................................398 Using the Calendar Functions ............................................................399 Further Reading ..................................................................................400 Next ....................................................................................................400 19 Generating Images 401 Setting Up Image Support in PHP ......................................................402 Image Formats ....................................................................................403 JPEG ..............................................................................................403 PNG ..............................................................................................403 WBMP ..........................................................................................403 GIF ................................................................................................404 Creating Images ..................................................................................404 Creating a Canvas Image ..............................................................405 Drawing or Printing Text onto the Image ....................................406 Outputting the Final Graphic ........................................................408 Cleaning Up ..................................................................................410 Using Automatically Generated Images in Other Pages ....................410 Using Text and Fonts to Create Images ..............................................410 Setting Up the Base Canvas ..........................................................414 Fitting the Text onto the Button ....................................................415 Positioning the Text ......................................................................418 Writing the Text onto the Button ..................................................419 Finishing Up ..................................................................................419 Drawing Figures and Graphing Data ..................................................419 Other Image Functions ......................................................................428 Further Reading ..................................................................................428 Next ....................................................................................................428 20 Using Session Control in PHP 429 What Session Control Is ....................................................................430 Basic Session Functionality ................................................................430 What Is a Cookie? ........................................................................431 Setting Cookies from PHP ............................................................431 Using Cookies with Sessions ........................................................432 Storing the Session ID ..................................................................432 Implementing Simple Sessions ..........................................................433 Starting a Session ..........................................................................433 Registering Session Variables ........................................................433 Using Session Variables ................................................................434 Deregistering Variables and Destroying the Session ....................434 xvi 0 0 7 8 4 2 F M 3 / 6 / 0 1 3 : 3 8 P M P a g e x v i CONTENTS Simple Session Example ....................................................................435 Configuring Session Control ..............................................................437 Implementing Authentication with Session Control ..........................438 Further Reading ..................................................................................445 Next ....................................................................................................445 21 Other Useful Features 447 Using Magic Quotes ..........................................................................448 Evaluating Strings: eval() ..................................................................449 Terminating Execution: die and exit ..................................................450 Serialization ........................................................................................450 Getting Information About the PHP Environment ............................451 Finding Out What Extensions Are Loaded ..................................451 Identifying the Script Owner ........................................................452 Finding Out When the Script Was Modified ................................452 Loading Extensions Dynamically ......................................................453 Temporarily Altering the Runtime Environment ................................453 Source Highlighting ............................................................................454 Next ....................................................................................................455 PART V Building Practical PHP and MySQL Projects 457 22 Using PHP and MySQL for Large Projects 459 Applying Software Engineering to Web Development ......................460 Planning and Running a Web Application Project ............................461 Reusing Code ......................................................................................462 Writing Maintainable Code ................................................................463 Coding Standards ..........................................................................463 Breaking Up Code ........................................................................466 Using a Standard Directory Structure ..........................................467 Documenting and Sharing In-House Functions ............................467 Implementing Version Control ............................................................467 Choosing a Development Environment ..............................................469 Documenting Your Projects ................................................................470 Prototyping ..........................................................................................471 Separating Logic and Content ............................................................471 Optimizing Code ................................................................................472 Using Simple Optimizations ........................................................472 Using Zend Products ....................................................................473 Testing ................................................................................................474 Further Reading ..................................................................................475 Next ....................................................................................................475 xvii 0 0 7 8 4 2 F M 3 / 6 / 0 1 3 : 3 8 P M P a g e x v i i PHP AND MYSQL WEB DEVELOPMENT 23 Debugging 477 Programming Errors ..........................................................................478 Syntax Errors ................................................................................478 Runtime Errors ..............................................................................480 Logic Errors ..................................................................................485 Variable Debugging Aid ....................................................................486 Error Reporting Levels ......................................................................489 Altering the Error Reporting Settings ................................................490 Triggering Your Own Errors ..............................................................492 Handling Errors Gracefully ................................................................492 Remote Debugging ............................................................................494 Next ....................................................................................................495 24 Building User Authentication and Personalization 497 The Problem ........................................................................................498 Solution Components ..........................................................................499 User Identification and Personalization ........................................499 Storing Bookmarks ........................................................................500 Recommending Bookmarks ..........................................................500 Solution Overview ..............................................................................500 Implementing the Database ................................................................502 Implementing the Basic Site ..............................................................504 Implementing User Authentication ....................................................506 Registering ....................................................................................507 Logging In ....................................................................................513 Logging Out ..................................................................................517 Changing Passwords ......................................................................518 Resetting Forgotten Passwords ......................................................521 Implementing Bookmark Storage and Retrieval ................................526 Adding Bookmarks ........................................................................526 Displaying Bookmarks ..................................................................529 Deleting Bookmarks ......................................................................530 Implementing Recommendations ......................................................532 Wrapping Up and Possible Extensions ..............................................537 Next ....................................................................................................537 25 Building a Shopping Cart 539 The Problem ........................................................................................540 Solution Components ..........................................................................540 Building an Online Catalog ..........................................................540 Tracking a User’s Purchases While She Shops ............................541 Payment ........................................................................................541 Administration Interface ................................................................542 xviii 0 0 7 8 4 2 F M 3 / 6 / 0 1 3 : 3 8 P M P a g e x v i i i CONTENTS Solution Overview ..............................................................................542 Implementing the Database ................................................................546 Implementing the Online Catalog ......................................................548 Listing Categories ..........................................................................551 Listing Books in a Category ..........................................................553 Showing Book Details ..................................................................555 Implementing the Shopping Cart ........................................................556 Using the show_cart.php Script ....................................................557 Viewing the Cart ............................................................................560 Adding Items to the Cart ..............................................................563 Saving the Updated Cart ..............................................................565 Printing a Header Bar Summary ..................................................566 Checking Out ................................................................................566 Implementing Payment ......................................................................572 Implementing an Administration Interface ........................................575 Extending the Project ..........................................................................584 Using an Existing System ..................................................................584 Next ....................................................................................................585 26 Building a Content Management System 587 The Problem ........................................................................................588 Solution Requirements ........................................................................588 Editing Content ..................................................................................589 Getting Content into the System ..................................................589 Databases Versus File Storage ......................................................591 Document Structure ......................................................................592 Using Metadata ..................................................................................592 Formatting the Output ........................................................................593 Image Manipulation ............................................................................594 Solution Design/Overview ..................................................................596 Designing the Database ......................................................................598 Implementation ..................................................................................599 Front End ......................................................................................599 Back End ......................................................................................603 Searching ......................................................................................611 Editor Screen ................................................................................614 Extending the Project ..........................................................................615 27 Building a Web-Based Email Service 617 The Problem ........................................................................................618 Solution Components ..........................................................................619 Solution Overview ..............................................................................620 Setting Up the Database ....................................................................622 xix 0 0 7 8 4 2 F M 3 / 6 / 0 1 3 : 3 8 P M P a g e x i x PHP AND MYSQL WEB DEVELOPMENT Script Architecture ..............................................................................623 Logging In and Out ............................................................................629 Setting Up Accounts ..........................................................................632 Creating a New Account ..............................................................634 Modifying an Existing Account ....................................................636 Deleting an Account ......................................................................636 Reading Mail ......................................................................................637 Selecting an Account ....................................................................637 Viewing Mailbox Contents ............................................................640 Reading a Mail Message ..............................................................643 Viewing Message Headers ............................................................647 Deleting Mail ................................................................................648 Sending Mail ......................................................................................649 Sending a New Message ..............................................................649 Replying To or Forwarding Mail ..................................................651 Extending the Project ..........................................................................652 Next ....................................................................................................653 28 Building a Mailing List Manager 655 The Problem ........................................................................................656 Solution Components ..........................................................................657 Setting Up a Database of Lists and Subscribers ..........................657 File Upload ........................................................................................657 Sending Mail with Attachments ........................................................658 Solution Overview ..............................................................................658 Setting Up the Database ....................................................................660 Script Architecture ..............................................................................663 Implementing Login ..........................................................................672 Creating a New Account ..............................................................673 Logging In ....................................................................................675 Implementing User Functions ............................................................678 Viewing Lists ................................................................................679 Viewing List Information ..............................................................684 Viewing List Archives ..................................................................686 Subscribing and Unsubscribing ....................................................687 Changing Account Settings ..........................................................689 Changing Passwords ......................................................................689 Logging Out ..................................................................................692 Implementing Administrative Functions ............................................693 Creating a New List ......................................................................693 Uploading a New Newsletter ........................................................695 Handling Multiple File Upload ....................................................698 xx 0 0 7 8 4 2 F M 3 / 6 / 0 1 3 : 3 8 P M P a g e x x CONTENTS Previewing the Newsletter ............................................................703 Sending the Message ....................................................................704 Extending the Project ..........................................................................709 Next ....................................................................................................709 29 Building Web Forums 711 The Problem ........................................................................................712 Solution Components ..........................................................................712 Solution Overview ..............................................................................714 Designing the Database ......................................................................716 Viewing the Tree of Articles ..............................................................718 Expanding and Collapsing ............................................................721 Displaying the Articles ..................................................................724 Using the treenode Class ..............................................................725 Viewing Individual Articles ................................................................731 Adding New Articles ..........................................................................734 Extensions ..........................................................................................741 Using an Existing System ..................................................................741 Next ....................................................................................................742 30 Generating Personalized Documents in Portable Format (PDF) 743 The Problem ........................................................................................744 Evaluating Document Formats ..........................................................745 Paper ..............................................................................................745 ASCII ............................................................................................745 HTML ............................................................................................745 Word Processor Formats ..............................................................746 Rich Text Format ..........................................................................746 PostScript ......................................................................................747 Portable Document Format ..........................................................748 Solution Components ..........................................................................749 Question and Answer System ........................................................749 Document Generation Software ....................................................749 Solution Overview ..............................................................................752 Asking the Questions ....................................................................753 Grading the Answers ....................................................................755 Generating an RTF Certificate ......................................................758 Generating a PDF Certificate from a Template ............................762 Generating a PDF Document Using PDFlib ................................765 A Hello World Script for PDFlib ..................................................766 Generating Our Certificate with PDFlib ......................................770 xxi 0 0 7 8 4 2 F M 3 / 6 / 0 1 3 : 3 8 P M P a g e x x i PHP AND MYSQL WEB DEVELOPMENT Problems with Headers ......................................................................777 Extending the Project ..........................................................................778 Further Reading ..................................................................................778 PART VI Appendixes 779 A Installing PHP 4 and MySQL 781 Running PHP as a CGI Interpreter or Module ..................................782 Installing Apache, PHP, and MySQL Under UNIX ..........................783 Apache and mod_SSL ..................................................................787 httpd.conf File—Snippets ..............................................................790 Is SSL Working? ............................................................................792 Installing Apache, PHP, and MySQL Under Windows ......................793 Installing MySQL Under Windows ..............................................793 Installing Apache Under Windows ................................................795 Differences Between Apache for Windows and UNIX ................798 Installing PHP for Windows ..........................................................799 Installation Notes for Microsoft IIS ..............................................800 Installation Notes for Microsoft PWS ..........................................802 Other Configurations ..........................................................................802 B Web Resources 803 PHP Resources ....................................................................................804 MySQL and SQL Specific Resources ................................................806 Apache Resources ..............................................................................806 Web Development ..............................................................................806 Index 807 xxii 0 0 7 8 4 2 F M 3 / 6 / 0 1 3 : 3 8 P M P a g e x x i i About the Authors Laura Thomson is a lecturer in Web programming in the Department of Computer Science at RMIT University in Melbourne, Australia. She is also a partner in the award-winning Web development firm Tangled Web Design. Laura has previously worked for Telstra and the Boston 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 enjoys sleeping. Laura can be contacted at laura@tangledweb.com.au. Luke Welling is a lecturer in software engineering and e-commerce in the School of Electrical and Computer Systems Engineering at RMIT University in Melbourne, Australia. He is also a partner 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 Communication Network Design. In his spare time, he attempts to perfect his insomnia. Luke can be contacted at luke@tangledweb.com.au. About the Contributors Israel Denis Jr. is a freelance consultant working on e-commerce projects throughout the world. He specializes in integrating ERP packages such as SAP and Lawson with custom Web solutions. He obtained a master’s degree in Electrical Engineering from Georgia Tech in Atlanta, Georgia in 1998. He is the author of numerous articles about Linux, Apache, PHP, and MySQL and can be reached via email at idenis@ureach.com. Chris Newman is a consultant programmer specializing in the development of dynamic Internet applications. He has extensive commercial experience in using PHP and MySQL to produce a wide range of applications for an international client base. A graduate of Keele University, 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 chris@lightwood.net. 0 0 7 8 4 2 F M 3 / 6 / 0 1 3 : 3 8 P M P a g e x x i i i Dedication To our Mums and Dads. Acknowledgments We would like to thank the team at Sams for all their hard work. In particular, we would like to thank Shelley Johnston Markanday without whose dedication and patience this book would not have been possible. We would also like to thank Israel Denis Jr. and Chris Newman for their valuable contributions. We appreciate immensely the work done by the PHP and MySQL development teams. Their work has made our lives easier for a number of years now, and continues to do so on a daily basis. We thank Adrian Close at eSec for saying “You can build that in PHP” back in 1998. We also thank James Woods and all the staff at Law Partners for giving us such interesting work to test the boundaries of PHP with. Finally, we would like to thank our family and friends for putting up with us while we have been antisocial for the better part of a year. Specifically, thank you for your support to our family members: Julie, Robert, Martin, Lesley, Adam, Paul, Sandi, James, and Archer. 0 0 7 8 4 2 F M 3 / 6 / 0 1 3 : 3 8 P M P a g e x x i v Tell Us What You Think! As the reader of this book, you are our most important critic and commentator. We value your opinion and want to know what we’re doing right, what we could do better, what areas you’d like 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 this book—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 name and phone or email address. I will carefully review your comments and share them with the author and editors who worked on the book. E-mail: webdev@samspublishing.com Mail: Mark Taber Associate Publisher Sams Publishing 201 West 103rd Street Indianapolis, IN 46290 USA 0 0 7 8 4 2 F M 3 / 6 / 0 1 3 : 3 8 P M P a g e x x v 0 0 7 8 4 2 F M 3 / 6 / 0 1 3 : 3 8 P M P a g e x x v i Introduction Welcome to PHP and MySQL Web Development. Within its pages, you will find distilled knowledge from our experiences using PHP and MySQL, two of the hottest Web development tools 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 Book This book will teach you how to create interactive Web sites from the simplest order form through to complex secure e-commerce sites. What’s more, you’ll learn how to do it using Open Source technologies. This book is aimed at readers who already know at least the basics of HTML and have done some 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, you should still find this book useful, but it might take you a little longer to digest. We’ve tried not to leave out any basic concepts, but we do cover them at speed. The typical reader of this book is 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 of the code samples can be directly used in your Web site, and many others can be used with minor modifications. What You Will Be Able to Achieve Using This Book Reading this book will enable you to build real-world, dynamic Web sites. If you’ve built Web sites using plain HTML, you will realize the limitations of this approach. Static content from a pure HTML Web site is just that—static. It stays the same unless you physically update it. Your users can’t interact with the site in any meaningful fashion. 0 1 7 8 4 2 i n t r o 3 / 6 / 0 1 3 : 3 3 P M P a g e 1 PHP AND MYSQL WEB DEVELOPMENT Using a language such as PHP and a database such as MySQL allows you to make your sites dynamic: 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 the various 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 take you 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 them because we believe they represent seven of the most common Web-based applications built by programmers. If your needs are different, this book should help you along the way to achieving your 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 is interpreted 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 was adopted 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 domains worldwide, 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, and redistribute it all without charge. PHP originally stood for Personal Home Page, but was changed in line with the GNU recursive naming 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 the language, discussed in the next section. 2 0 1 7 8 4 2 i n t r o 3 / 6 / 0 1 3 : 3 3 P M P a g e 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 this new version • PHP 4 is much faster than previous versions because it uses the new Zend Engine. If you need even higher performance, you can obtain the Zend Optimizer, Zend Cache, or Zend Compiler from http://www.zend.com. • You have always been able to use PHP as an efficient module for the Apache server. With this new version, you can install PHP as an ISAPI module for Microsoft’s Internet Information 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. The MySQL 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 has a development history going back to 1979. It has now won the Linux Journal Readers’ Choice Award three years running. MySQL is now available under an Open Source license, but commercial licenses are also available if 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, a database management system, and a programming or scripting language. Some of these choices will be dependent on the others. For example, not all operating systems will run 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 server software. We don’t need to. One of the nice features of PHP is that it is available for Microsoft Windows, for many versions of UNIX, and with any fully-functional Web server. MySQL is similarly versatile. 3 0 1 7 8 4 2 i n t r o 3 / 6 / 0 1 3 : 3 3 P M P a g e 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 Strengths Some of PHP’s main competitors are Perl, Microsoft Active Server Pages (ASP), Java Server Pages (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. Performance PHP 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 outperforming its competition. Database Integration PHP has native connections available to many database systems. In addition to MySQL, you can directly 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 that provides an ODBC driver. This includes Microsoft products, and many others. Built-in Libraries Because PHP was designed for use on the Web, it has many built-in functions for performing many 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 few lines of code. 4 0 1 7 8 4 2 i n t r o 3 / 6 / 0 1 3 : 3 3 P M P a g e 4 INTRODUCTION Cost PHP is free. You can download the latest version at any time from http://www.php.net for no charge. Learning PHP The syntax of PHP is based on other programming languages, primarily C and Perl. If you already know C or Perl, or a C-like language such as C++ or Java, you will be productive using PHP almost immediately. Portability PHP 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 and IRIX, or on different versions of Microsoft Windows. Your code will usually work without modification on a different system running PHP. Source Code You have access to the source code of PHP. Unlike commercial, closed-source products, if there is something 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 the manufacturer going out of business or deciding to stop supporting a product. Some of MySQL’s Strengths Some 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. Performance MySQL is undeniably fast. You can see the developers’ benchmark page at http://web.mysql.com/benchmark.html. Many of these benchmarks show MySQL to be orders of magnitude faster than the competition. Low Cost MySQL is available at no cost, under an Open Source license, or at low cost under a commercial license if required for your application. 5 0 1 7 8 4 2 i n t r o 3 / 6 / 0 1 3 : 3 3 P M P a g e 5 PHP AND MYSQL WEB DEVELOPMENT Ease of Use Most modern databases use SQL. If you have used another RDBMS, you should have no trouble adapting to this one. MySQL is also easier to set up than many similar products. Portability MySQL can be used on many different UNIX systems as well as under Microsoft Windows. Source Code As 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, rather than “toy” code. We’ll kick this section off with Chapter 1, “PHP Crash Course.” If you’ve already used PHP, you can whiz through this section. If you are new to PHP or new to programming, you might want to spend a little more time on it. Part II, “Using MySQL,” discusses the concepts and design involved in using relational database systems 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 an e-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 such as managing large projects and debugging, and provides sample projects that demonstrate the power and versatility of PHP and MySQL. Finally We hope you enjoy this book, and enjoy learning about PHP and MySQL as much as we did when we first began using these products. They are really a pleasure to use. Soon, you’ll be able to join the thousands of Web developers who use these robust, powerful tools to easily build dynamic, real-time Web sites. 6 0 1 7 8 4 2 i n t r o 3 / 6 / 0 1 3 : 3 3 P M P a g e 6 IN THIS PART 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 Using PHP PART I 0 2 7 8 4 2 p a r t 1 3 / 6 / 0 1 3 : 4 2 P M P a g e 7 0 2 7 8 4 2 p a r t 1 3 / 6 / 0 1 3 : 4 2 P M P a g e 8 CHAPTER 1 PHP Crash Course 0 3 7 8 4 2 C H 0 1 3 / 6 / 0 1 3 : 3 9 P M P a g e 9 Using PHP PART I 10 This chapter gives you a quick overview of PHP syntax and language constructs. If you are already 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 speed quickly. 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 teach basic syntax with very simple examples. We have chosen not to do that. We recognize that often what you want to do is get something up and running, to understand how the language is used, rather than ploughing through yet another syntax and function reference that’s no better than the online manual. Try the examples out—type them in or load them from the CD-ROM, change them, break them, and learn how to fix them again. In this chapter, we’ll begin with the example of an online product order form to learn how variables, operators, and expressions are used in PHP. We will also cover variable types and operator precedence. You will learn how to access form variables and how to manipulate them by working out the total and tax on a customer order. We will then develop the online order form example by using our PHP script to validate the input data. We’ll examine the concept of Boolean values and give examples of using if, else, the ?: operator, and the switch statement. Finally, we’ll explore looping by writing some PHP to generate repetitive HTML tables. Key topics you will learn in this chapter include • Embedding PHP in HTML • Adding dynamic content • Accessing form variables • Identifiers • User declared variables • Variable types • Assigning values to variables • Constants • Variable scope • Operators and precedence • Expressions • Variable functions • Making decisions with if, else, and switch • Iteration: while, do, and for loops 0 3 7 8 4 2 C H 0 1 3 / 6 / 0 1 3 : 3 9 P M P a g e 1 0 Using PHP In order to work through the examples in this chapter and the rest of the book, you will need access to a Web server with PHP installed. To get the most from the examples and case studies, you should run them and try changing them. To do this, you’ll need a testbed where you can experiment. If PHP is not installed on your machine, you will need to begin by installing it, or getting your system administrator to install it for you. You can find instructions for doing so in Appendix A, “Installing PHP 4 and MySQL.” Everything you need to install PHP under UNIX or Windows NT can be found on the accompanying CD-ROM. Sample Application: Bob’s Auto Parts One of the most common applications of any server side scripting language is processing HTML forms. You’ll start learning PHP by implementing an order form for Bob’s Auto Parts, a fictional spare parts company. All the code for the Bob’s examples used in this chapter is in the directory called chapter1 on the CD-ROM. The Order Form Right now, Bob’s HTML programmer has gotten as far as setting up an order form for the parts that Bob sells. The order form is shown in Figure 1.1. This is a relatively simple order form, similar to many you have probably seen while surfing. The first thing Bob would like to be able to do is know what his customer ordered, work out the total of the customer’s order, and how much sales tax is payable on the order. PHP Crash Course CHAPTER 1 1 PHPCRASHCOURSE11 FIGURE 1.1 Bob’s initial order form only records products and quantities. 0 3 7 8 4 2 C H 0 1 3 / 6 / 0 1 3 : 3 9 P M P a g e 1 1 Part of the HTML for this is shown in Listing 1.1. There are two important things to notice in this code. LISTING 1.1 orderform.html—HTML for Bob’s Basic Order Form <form action=”processorder.php” method=post> <table border=0> <tr bgcolor=#cccccc> <td width=150>Item</td> <td width=15>Quantity</td> </tr> <tr> <td>Tires</td> <td align=center><input type=”text” name=”tireqty” size=3 maxlength=3></td> </tr> <tr> <td>Oil</td> <td align=center><input type=”text” name=”oilqty” size=3 maxlength=3></td> </tr> <tr> <td>Spark Plugs</td> <td align=center><input type=”text” name=”sparkqty” size=3 maxlength=3></td> </tr> <tr> <td colspan=2 align=center><input type=submit value=”Submit Order”></td> </tr> </table> </form> The first thing to notice is that we have set the form’s action to be the name of the PHP script that will process the customer’s order. (We’ll write this script next.) In general, the value of the ACTION attribute is the URL that will be loaded when the user presses the submit button. The data the user has typed in the form will be sent to this URL via the method specified in the METHOD attribute, either GET (appended to the end of the URL) or POST (sent as a separate packet). The second thing you should notice is the names of the form fields—tireqty, oilqty, and sparkqty. We’ll use these names again in our PHP script. Because of this, it’s important to give your form fields meaningful names that you can easily remember when you begin writing the PHP script. Some HTML editors will generate field names like field23 by default. These are difficult to remember. Your life as a PHP programmer will be easier if these names reflect the data that is typed into the field. Using PHP PART I 12 0 3 7 8 4 2 C H 0 1 3 / 6 / 0 1 3 : 3 9 P M P a g e 1 2 You might want to consider adopting a coding standard for field names so that all field names throughout your site use the same format. This makes it easier to remember whether, for exam- ple, you abbreviated a word in a field name, or put in underscores as spaces. Processing the Form To process the form, we’ll need to create the script mentioned in the ACTION attribute of the FORM tag called processorder.php. Open your text editor and create this file. Type in the fol- lowing code: <html> <head> <title>Bob’s Auto Parts - Order Results</title> </head> <body> <h1>Bob’s Auto Parts</h1> <h2>Order Results</h2> </body> </html> Notice, how everything we’ve typed so far is just plain HTML. It’s now time to add some sim- ple PHP code to our script. Embedding PHP in HTML Under the <h2> heading in your file, add the following lines: <? echo “<p>Order processed.”; ?> Save the file and load it in your browser by filling out Bob’s form and clicking the Submit but- ton. You should see something similar to the output shown in Figure 1.2. Notice how the PHP code we wrote was embedded inside a normal-looking HTML file. Try viewing the source from your browser. You should see this code: <html> <head> <title>Bob’s Auto Parts - Order Results</title> </head> <body> <h1>Bob’s Auto Parts</h1> <h2>Order Results</h2> <p>Order processed.</p></body> </html> PHP Crash Course CHAPTER 1 1 PHPCRASHCOURSE13 0 3 7 8 4 2 C H 0 1 3 / 6 / 0 1 3 : 3 9 P M P a g e 1 3 FIGURE 1.2 Text passed to PHP’s echo construct is echoed to the browser. None of the raw PHP is visible. This is because the PHP interpreter has run through the script and replaced it with the output from the script. This means that from PHP we can produce clean HTML viewable with any browser—in other words, the user’s browser does not need to understand PHP. This illustrates the concept of server-side scripting in a nutshell. The PHP has been interpreted and executed on the Web server, as distinct from JavaScript and other client-side technologies that are interpreted and executed within a Web browser on a user’s machine. The code that we now have in this file consists of four things: • HTML • PHP tags • PHP statements • Whitespace We can also add • Comments Most of the lines in the example are just plain HTML. Using PHP Tags The PHP code in the previous example began with <? and ended with ?>. This is similar to all HTML tags because they all begin with a less than (<) symbol and end with a greater than (>) symbol. These symbols are called PHP tags that tell the Web server where the PHP code starts and finishes. Any text between the tags will be interpreted as PHP. Any text outside these tags will be treated as normal HTML. The PHP tags allow us to escape from HTML. Using PHP PART I 14 0 3 7 8 4 2 C H 0 1 3 / 6 / 0 1 3 : 3 9 P M P a g e 1 4 Different tag styles are available. This is the short style. If you have some problems running this script, it might be because short tags are not enabled in your PHP installation. Let’s look at this in more detail. PHP Tag Styles There are actually four different styles of PHP tags we can use. Each of the following frag- ments of code is equivalent. • Short style <? echo “<p>Order processed.”; ?> This is the tag style that will be used in this book. It is the default tag that PHP develop- ers use to code PHP. This style of tag is the simplest and follows the style of an SGML (Standard Generalized Markup Language) processing instruction. To use this type of tag—which is the shortest to type—you either need to enable short tags in your config file, or compile PHP with short tags enabled. You can find more information on how to do this in Appendix A. • XML style <?php echo “<p>Order processed.”; ?> This style of tag can be used with XML (Extensible Markup Language) documents. If you plan to serve XML on your site, you should use this style of tag. • SCRIPT style <SCRIPT LANGUAGE=’php’> echo “<p>Order processed.”; </SCRIPT> This style of tag is the longest and will be familiar if you’ve used JavaScript or VBScript. It can be used if you are using an HTML editor that gives you problems with the other tag styles. • ASP style <% echo “<p>Order processed.”; %> This style of tag is the same as used in Active Server Pages (ASP). It can be used if you have enabled the asp_tags configuration setting. You might want to use this style of tag if you are using an editor that is geared towards ASP or if you already program in ASP. PHP Statements We tell the PHP interpreter what to do by having PHP statements between our opening and closing tags. In this example, we used only one type of statement: echo “<p>Order processed.”; PHP Crash Course CHAPTER 1 1 PHPCRASHCOURSE15 0 3 7 8 4 2 C H 0 1 3 / 6 / 0 1 3 : 3 9 P M P a g e 1 5 As you have probably guessed, using the echo construct has a very simple result; it prints (or echoes) the string passed to it to the browser. In Figure 1.2, you can see the result is that the text “Order processed.” appears in the browser window. You will notice that a semicolon appears at the end of the echo statement. This is used to sepa- rate statements in PHP much like a period is used to separate sentences in English. If you have programmed in C or Java before, you will be familiar with using the semicolon in this way. Leaving the semicolon off is a common syntax error that is easily made. However, it’s equally easy to find and to correct. Whitespace Spacing characters such as new lines (carriage returns), spaces and tabs are known as white- space. I would combine the paragraph above and the one below and form one cohesive para- graph explaining how spacing characters (whitespace) is ignored in PHP and HTML. As you probably already know, browsers ignore whitespace in HTML. So does the PHP engine. Consider these two HTML fragments: <h1>Welcome to Bob’s Auto Parts!</h1><p>What would you like to order today? and <h1>Welcome to Bob’s Auto Parts!</h1> <p>What would you like to order today? These two snippets of HTML code produce identical output because they appear the same to the browser. However, you can and are encouraged to use whitespace in your HTML as an aid to humans—to enhance the readability of your HTML code. The same is true for PHP. There is no need to have any whitespace between PHP statements, but it makes the code easier to read if we put each statement on a separate line. For example, echo “hello”; echo “world”; and echo “hello”;echo “world”; are equivalent, but the first version is easier to read. Comments Comments are exactly that: Comments in code act as notes to people reading the code. Comments can be used to explain the purpose of the script, who wrote it, why they wrote it the Using PHP PART I 16 0 3 7 8 4 2 C H 0 1 3 / 6 / 0 1 3 : 3 9 P M P a g e 1 6 way they did, when it was last modified, and so on. You will generally find comments in all but the simplest PHP scripts. The PHP interpreter will ignore any text in a comment. Essentially the PHP parser skips over the comments that are equivalent to whitespace. PHP supports C, C++, and shell script style comments. This is a C-style, multiline comment that might appear at the start of our PHP script: /* Author: Bob Smith Last modified: April 10 This script processes the customer orders. */ Multiline comments should begin with a /* and end with */. As in C, multiline comments can- not be nested. You can also use single line comments, either in the C++ style: echo “<p>Order processed.”; // Start printing order or in the shell script style: echo “<p>Order processed.”; # Start printing order With both of these styles, everything after the comment symbol (# or //) is a comment until we reach the end of the line or the ending PHP tag, whichever comes first. Adding Dynamic Content So far, we haven’t used PHP to do anything we couldn’t have done with plain HTML. The main reason for using a server-side scripting language is to be able to provide dynamic content to a site’s users. This is an important application because content that changes accord- ing to a user’s needs or over time will keep visitors coming back to a site. PHP allows us to do this easily. Let’s start with a simple example. Replace the PHP in processorder.php with the following code: <? echo “<p>Order processed at “; echo date(“H:i, jS F”); echo “<br>”; ?> In this code, we are using PHP’s built-in date() function to tell the customer the date and time when his order was processed. This will be different each time the script is run. The output of running the script on one occasion is shown in Figure 1.3. PHP Crash Course CHAPTER 1 1 PHPCRASHCOURSE17 0 3 7 8 4 2 C H 0 1 3 / 6 / 0 1 3 : 3 9 P M P a g e 1 7