Luke Welling and Laura Thomson

  Luke Welling and Laura Thomson PHP and MySQL

   Web Development

  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.

  A CQUISITIONS E DITOR Shelley Johnston Markanday D EVELOPMENT E DITOR Scott D. Meyers M ANAGING E DITOR Charlotte Clapp C OPY E DITOR Rhonda Tinch-Mize

  I NDEXER Kelly Castell P ROOFREADERS Kathy Bidwell Tony Reitz T ECHNICAL E DITORS Israel Denis Chris Newman T EAM C OORDINATOR Amy Patton S OFTWARE D EVELOPMENT S PECIALIST Dan Scherf

  I NTERIOR D ESIGN Anne Jones C OVER D ESIGN Anne Jones P RODUCTION Ayanna Lacey Heather Hiatt Miller Stacey Richwine-DeRome

  Overview

1 Introduction

  P ART

  I Using PHP

  9

  1 PHP Crash Course

  49

  2 Storing and Retrieving Data

  69

  3 Using Arrays

  93

  4 String Manipulation and Regular Expressions 117

  5 Reusing Code and Writing Functions

147

  6 Object-Oriented PHP P ART

  II Using MySQL 171

  7 Designing Your Web Database 183

  8 Creating Your Web Database 207

  9 Working with Your MySQL Database 227

  

10 Accessing Your MySQL Database from the Web with PHP

245

  11 Advanced MySQL P ART

  III E-commerce and Security 267

  12 Running an E-commerce Site 281

  13 E-commerce Security Issues 303

  14 Implementing Authentication with PHP and MySQL 327

  

15 Implementing Secure Transactions with PHP and MySQL

P ART

  IV Advanced PHP Techniques 351

  16 Interacting with the File System and the Server 369

  17 Using Network and Protocol Functions 391

  18 Managing the Date and Time 401

  19 Generating Images 429

  20 Using Session Control in PHP

447

  21 Other Useful Features

  P ART

  V Building Practical PHP and MySQL Projects 459

  22 Using PHP and MySQL for Large Projects 477

  23 Debugging 497

  24 Building User Authentication and Personalization 539

  25 Building a Shopping Cart 587

  26 Building a Content Management System 617

  27 Building a Web-Based Email Service 655

  28 Building a Mailing List Manager 711

  29 Building Web Forums 743

  

30 Generating Personalized Documents in Portable Document Format (PDF)

P ART

  VI

781

  A Installing PHP 4 and MySQL 803

  B Web Resources 807

  Index

  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

  P ART

  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

  AND Y EB EVELOPMENT PHP M SQL W D 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

  ONTENTS C 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

  AND Y EB EVELOPMENT PHP M SQL W D 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

  ONTENTS C 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

  AND Y EB EVELOPMENT PHP M SQL W D 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 ART Next ....................................................................................................168

  P

  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

  ONTENTS C 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

  AND Y EB EVELOPMENT PHP M SQL W D 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

  ONTENTS C

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 ART Next ....................................................................................................264

  P

  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

  AND Y EB EVELOPMENT PHP M SQL W D 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

  C ONTENTS Using Encryption in PHP ..................................................................338 Further Reading ..................................................................................347 Next ....................................................................................................347

  P ART

  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

  PHP AND M Y SQL W EB D EVELOPMENT 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