Luke Welling and Laura Thomson
201 West 103rd St., Indianapolis, Indiana, 46290 USA
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-
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
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
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
PHP AND MYSQL WEB DEVELOPMENT
vi
Accessing Form Variables 19
Form Variables 19
String Concatenation 20
Variables and Literals 21
Identifiers 21
switch Statements 41
Comparing the Different Conditionals 42
Iteration: Repeating Actions 43
while Loops 44
for Loops 45
do while Loops 46
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
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
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
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
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
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
CONTENTS
Table Optimization 262
Using Indexes 262
Use Default Values 262
Use Persistent Connections 262
Other Tips 262
Different Table Types 263
Errors in Software 288
Repudiation 289
Balancing Usability, Performance, Cost, and Security 290
Creating a Security Policy 291
xiii
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
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
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
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
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
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
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
Handling Multiple File Upload 698
xx
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
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
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 [email protected].
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 [email protected].
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 [email protected].
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: [email protected]
Mail: Mark Taber
Associate Publisher
Sams Publishing
201 West 103rd Street
Indianapolis, IN 46290 USA