Luke Welling and Laura Thomson 201 West 103rd St., Indianapolis, Indiana, 46290 USA PHP and MySQL Web Development 00 7842 FM 3/6/01 3:38 PM Page i PHP and MySQL Web 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 00 7842 FM 3/6/01 3:38 PM Page ii Overview Introduction 1 P ART 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 P ART 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 P ART 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 P ART IV Advanced PHP Techniques 16 Interacting with the File System and the Server 351 17 Using Network and Protocol Functions 369 18 Managing the Date and Time 391 19 Generating Images 401 20 Using Session Control in PHP 429 21 Other Useful Features 447 00 7842 FM 3/6/01 3:38 PM Page iii PART V Building Practical PHP and MySQL Projects 22 Using PHP and MySQL for Large Projects 459 23 Debugging 477 24 Building User Authentication and Personalization 497 25 Building a Shopping Cart 539 26 Building a Content Management System 587 27 Building a Web-Based Email Service 617 28 Building a Mailing List Manager 655 29 Building Web Forums 711 30 Generating Personalized Documents in Portable Document Format (PDF) 743 P ART VI A Installing PHP 4 and MySQL 781 B Web Resources 803 Index 807 00 7842 FM 3/6/01 3:38 PM Page iv 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 00 7842 FM 3/6/01 3:38 PM Page 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 00 7842 FM 3/6/01 3:38 PM Page vi 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 00 7842 FM 3/6/01 3:38 PM Page vii 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 00 7842 FM 3/6/01 3:38 PM Page viii 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 00 7842 FM 3/6/01 3:38 PM Page ix 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 00 7842 FM 3/6/01 3:38 PM Page x . 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(). 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. Thomson 2 01 West 10 3rd St., Indianapolis, Indiana, 46290 USA PHP and MySQL Web Development 00 7842 FM 3/6/ 01 3:38 PM Page i PHP and MySQL Web Development Copyright © 20 01 by Sams Publishing All