Tải bản đầy đủ (.pdf) (984 trang)

php and mysql web development by luke welling and laura thompson

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (10.58 MB, 984 trang )

“I’ve never purchased a better
programming book… This book proved to
be the most informative, easiest to follow,
and had the best examples of any other
computer-related book I have ever
purchased.The text is very easy to follow!”
—Nick Landman
“…the Sams book by Welling &
Thomson is the only one which I have
found to be indispensable.The writing is
clear and straightforward but never wastes
my time.The book is extremely well laid
out.The chapters are the right length and
chapter titles quickly take you where you
want to go.”
—Wright Sullivan, President,A&E
Engineering, Inc., Greer South Carolina
“I just wanted to tell you that I think the
book PHP and MySQL Web Development
rocks! It’s logically structured, just the right
difficulty level for me (intermediate),
interesting and easy to read, and, of course,
full of valuable information!”
—CodE-E, Austria
“There are several good introductory
books on PHP, but Welling & Thomson is an
excellent handbook for those who wish to
build up complex and reliable systems. It’s
obvious that the authors have a strong back-
ground in the development of professional
applications and they teach not only


the language itself, but also how to use it
with good software engineering practices.”
—Javier Garcia, senior telecom engineer,
Telefonica R&D Labs, Madrid
“I picked up this book two days ago
and I am half way finished. I just can’t put
it down.The layout and flow is perfect.
Everything is presented in such a way so
that the information is very palatable. I am
able to immediately grasp all the concepts.
The examples have also been wonderful.
I just had to take some time out to express
to you how pleased I have been with
this book.”
—Jason B. Lancaster
“This book has proven a trusty
companion, with an excellent crash course
in PHP and superb coverage of MySQL as
used for Web applications. It also features
several complete applications that are great
examples of how to construct modular,
scalable applications with PHP.Whether
you are a PHP newbie or a veteran in
search of a better desk-side reference, this
one is sure to please!”
—WebDynamic
“The true PHP/MySQL bible, PHP
and MySQL Web Development by Luke
Welling and Laura Thomson, made me
realize that programming and databases are

now available to the commoners. Again, I
know 1/10000th of what there is to know,
and already I’m enthralled.”
—Tim Luoma,TnTLuoma.com
“Welling and Thomson’s book is a good
reference for those who want to get to
grips with practical projects straight off the
bat. It includes webmail, shopping cart,
session control, and web-forum/weblog
applications as a matter of course, and
begins with a sturdy look at PHP first,
moving to MySQL once the basics
are covered.”
—twilight30 on Slashdot
00 6728 fm 9/2/04 1:15 PM Page i
“This book is absolutely excellent, to
say the least…. Luke Welling and Laura
Thomson give the best in-depth explana-
tions I’ve come across on such things as
regular expressions, classes and objects,
sessions etc. I really feel this book filled in a
lot of gaps for me with things I didn’t quite
understand….This book jumps right into
the functions and features most commonly
used with PHP, and from there it continues
in describing real-world projects, MySQL
integration, and security issues from a proj-
ect manager’s point of view. I found every
bit of this book to be well organized and
easy to understand.”

—notepad on codewalkers.com
“A top-notch reference for
programmers using PHP and MySQL.
Highly recommended.”
—The Internet Writing Journal
“This book rocks! I am an experienced
programmer, so I didn’t need a lot of help
with PHP syntax; after all, it’s very close to
C/C++. I don’t know a thing about
databases, though, so when I wanted to
develop a book review engine (among
other projects) I wanted a solid reference
to using MySQL with PHP. I have
O’Reilly’s mSQL and MySQL book, and
it’s probably a better pure-SQL reference,
but this book has earned a place on my
reference shelf…Highly recommended.”
—Paul Robichaux
“One of the best programming guides
I’ve ever read.”
—jackofsometrades from Lahti, Finland
“This is a well-written book for learn-
ing how to build Internet applications with
two of the most popular open-source Web
development technologies….The projects
are the real jewel of the book. Not only are
the projects described and constructed in a
logical, component-based manner, but the
selection of projects represents an excellent
cross-section of common components that

are built into many web sites.”
—Craig Cecil
“The book takes an easy, step-by-step
approach to introduce even the clueless
programmer to the language of PHP. On
top of that, I often find myself referring
back to it in my Web design efforts. I’m still
learning new things about PHP, but this
book gave me a solid foundation from
which to start and continues to help me to
this day.”
—Stephen Ward
“This book is one of few that really
touched me and made me ‘love’ it. I can’t
put it in my bookshelf; I must put it in a
touchable place on my working bench as I
always like to refer from it. Its structure is
good, wordings are simple and straight for-
ward, and examples are clear and step by
step. Before I read it, I knew nothing of
PHP and MySQL. After reading it, I have
the confidence and skill to develop any
complicated Web application.”
—Power Wong
“This book is God…. I highly recom-
mend this book to anyone who wants to
jump in the deep end with database driven
Web application programming. I wish more
computer books were organized this way.”
—Sean C Schertell

00 6728 fm 9/2/04 1:15 PM Page ii
PHP and MySQL
Web Development
Sams Publishing, 800 East 96th Street, Indianapolis, Indiana 46240
DEVELOPER’S
LIBRARY
Luke Welling
Laura Thomson
Third Edition
00 6728 fm 9/2/04 1:15 PM Page iii
PHP and MySQL Web Development
Third Edition
Copyright  2005 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 informa-
tion contained herein.Although every precaution has been taken in the
preparation of this book, the publisher and authors 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-32672-8
Library of Congress Catalog Card Number: 2003099244
Printed in the United States of America
First Printing: October 2004
07 06 05 04 4321
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.
Wa r ning 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
arising from the information contained in this book or from the use of the
CD-ROM or programs accompanying it.
Bulk Sales
Sams Publishing offers excellent discounts on this book when ordered in
quantity for bulk purchases or special sales. For more information, please
contact
U.S. Corporate and Government Sales
1-800-382-3419

For sales outside the U.S., please contact
International Sales
1-317-428-3341

Acquisitions Editor
Shelley Johnston
Development Editor
Scott Meyers
Managing Editor
Charlotte Clapp
Copy Editor
Chuck Hutchinson
Indexer
Mandie Frank
Proofreader

Paula Lowell
Technical Editors
Sara Golemon
Chris Newman
Media Specialist
Dan Scherf
Design
Gary Adair
Page Layout
Cheryl Lynch
Michelle Mitchell
00 6728 fm 9/2/04 1:15 PM Page iv

To our Mums and Dads

00 6728 fm 9/2/04 1:15 PM Page v
Contents at a Glance
Introduction 1
I Using PHP
1 PHP Crash Course 11
2 Storing and Retrieving Data 57
3 Using Arrays 79
4 String Manipulation and Regular Expressions 105
5 Reusing Code and Writing Functions 129
6 Object-Oriented PHP 157
7 Exception Handling 191
II Using MySQL
8 Designing Your Web Database 205
9 Creating Your Web Database 217
10 Working with Your MySQL Database 241

11 Accessing Your MySQL Database from the Web
with PHP 265
12 Advanced MySQL Administration 285
13 Advanced MySQL Programming 307
III E-commerce and Security
14 Running an E-commerce Site 323
15 E-commerce Security Issues 337
16 Implementing Authentication with PHP and
MySQL 357
17 Implementing Secure Transactions with PHP and
MySQL 379
00 6728 fm 9/2/04 1:15 PM Page vi
IV Advanced PHP Techniques
18 Interacting with the File System and the Server
401
19 Using Network and Protocol Functions 419
20 Managing the Date and Time 439
21 Generating Images 451
22 Using Session Control in PHP 479
23 Other Useful Features 495
V Building Practical PHP and MySQL Projects
24 Using PHP and MySQL for Large Projects 507
25 Debugging 523
26 Building User Authentication and Personalization
541
27 Building a Shopping Cart 579
28 Building a Content Management System 625
29 Building a Web-Based Email Service 657
30 Building a Mailing List Manager 695
31 Building Web Forums 751

32 Generating Personalized Documents in Portable
Document Format (PDF) 783
33 Connecting to Web Services with XML and SOAP
819
VI Appendixes
A Installing PHP and MySQL 867
B Web Resources 889
Index 893
00 6728 fm 9/2/04 1:15 PM Page vii
Table of Contents
Introduction 1
I Using PHP
1 PHP Crash Course 11
Using PHP 12
Creating a Sample Application: Bob’s Auto Parts 12
Creating the Order Form 12
Processing the Form 14
Embedding PHP in HTML 15
Use of PHP Tags 16
PHP Tag Styles 16
PHP Statements 17
Whitespace 18
Comments 18
Adding Dynamic Content 19
Calling Functions 20
Using the
date() Function 20
Accessing Form Variables 21
Form Variables 21
String Concatenation 24

Va r iables and Literals 25
Understanding Identifiers 26
Creating User-Declared Variables 26
Assigning Values to Variables 26
Examining Variable Types 27
PHP’s Data Types 27
Type Strength 27
Type Casting 28
Va r iable Variables 28
Declaring and Using Constants 29
Understanding Variable Scope 29
00 6728 fm 9/2/04 1:15 PM Page viii
Using Operators 30
Arithmetic Operators 31
String Operators 32
Assignment Operators 32
Comparison Operators 34
Logical Operators 36
Bitwise Operators 36
Other Operators 37
Using Operators:Working Out the Form Totals 39
Understanding Precedence and Associativity:
Evaluating Expressions 40
Using Variable Functions 42
Testing and Setting Variable Types 42
Testing Variable Status 43
Reinterpreting Variables 44
Implementing Control Structures 44
Making Decisions with Conditionals 44
if Statements 44

Code Blocks 45
else Statements 45
elseif Statements 46
switch Statements 47
Comparing the Different Conditionals 49
Repeating Actions Through Iteration 49
while Loops 51
for and foreach Loops 52
do while Loops 53
Breaking Out of a Control Structure or Script 54
Employing Alternative Control Structure Syntax 54
Using declare 55
Next: Saving the Customer’s Order 55
2 Storing and Retrieving Data 57
Saving Data for Later 57
Storing and Retrieving Bob’s Orders 58
Processing Files 59
00 6728 fm 9/2/04 1:15 PM Page ix
x
Contents
Opening a File 59
Choosing File Modes 59
Using fopen() to Open a File 60
Opening Files Through FTP or HTTP 62
Addressing Problems Opening Files 63
Writing to a File 65
Parameters for fwrite() 66
File Formats 66
Closing a File 67
Reading from a File 69

Opening a File for Reading:
fopen() 70
Knowing When to Stop:
feof() 71
Reading a Line at a Time: fgets(), fgetss(),
and
fgetcsv() 71
Reading the Whole File:
readfile(),
fpassthru(),and file() 72
Reading a Character:
fgetc() 73
Reading an Arbitrary Length:
fread() 73
Using Other Useful File Functions 74
Checking Whether a File Is There:
file_exists() 74
Determining How Big a File Is:
filesize()
74
Deleting a File: unlink() 74
Navigating Inside a File:
rewind(), fseek(),
and
ftell() 74
Locking Files 76
Doing It a Better Way: Database Management
Systems 77
Problems with Using Flat Files 77
How RDBMSs Solve These Problems 78

Further Reading 78
Next 78
3 Using Arrays 79
What Is an Array? 79
Numerically Indexed Arrays 80
Initializing Numerically Indexed Arrays 80
Accessing Array Contents 81
Using Loops to Access the Array 82
00 6728 fm 9/2/04 1:15 PM Page x
xi
Contents
Arrays with Different Indices 83
Initializing an Array 83
Accessing the Array Elements 83
Using Loops 83
Array Operators 85
Multidimensional Arrays 86
Sorting Arrays 90
Using sort() 90
Using asort() and ksort() to Sort Arrays
91
Sorting in Reverse 91
Sorting Multidimensional Arrays 91
User-Defined Sorts 91
Reverse User Sorts 93
Reordering Arrays 94
Using shuffle() 94
Using
array_reverse() 96
Loading Arrays from Files 96

Performing Other Array Manipulations 100
Navigating Within an Array:
each(),
current(), reset(), end(), next(), pos(),
and
prev() 100
Applying Any Function to Each Element in an
Array:
array_walk() 101
Counting Elements in an Array:
count(),
sizeof(),and array_count_values() 102
Converting Arrays to Scalar Variables: extract()
103
Further Reading 104
Next 104
4 String Manipulation and Regular
Expressions 105
Creating a Sample Application: Smart Form Mail 105
Formatting Strings 107
Tr imming Strings: chop(), ltrim(), and
trim() 108
Formatting Strings for Presentation 108
Formatting Strings for Storage: addslashes()
and stripslashes() 112
00 6728 fm 9/2/04 1:15 PM Page xi
xii
Contents
Joining and Splitting Strings with String Functions
113

Using explode(), implode(),and join()
114
Using strtok() 114
Using substr() 115
Comparing Strings 116
Performing String Ordering: strcmp(),
strcasecmp(), and strnatcmp() 116
Testing String Length with strlen() 117
Matching and Replacing Substrings with String
Functions 117
Finding Strings in Strings: strstr(), strchr(),
strrchr(),and stristr() 118
Finding the Position of a Substring: strpos()
and strrpos() 118
Replacing Substrings:
str_replace() and
substr_replace() 119
Introducing Regular Expressions 121
The Basics 121
Character Sets and Classes 121
Repetition 123
Subexpressions 123
Counted Subexpressions 123
Anchoring to the Beginning or End
of a String 123
Branching 124
Matching Literal Special Characters 124
Reviewing the Special Characters 124
Putting It All Together for the Smart Form 125
Finding Substrings with Regular Expressions 126

Replacing Substrings with Regular Expressions 127
Splitting Strings with Regular Expressions 127
Comparing String Functions and Regular Expression
Functions 127
Further Reading 128
Next 128
00 6728 fm 9/2/04 1:15 PM Page xii
xiii
Contents
5 Reusing Code and Writing Functions 129
Reusing Code 129
Cost 130
Reliability 130
Consistency 130
Using require() and include() 130
require() 131
Filename Extensions and require() 132
PHP Tags and require() 132
Using require() for Website Templates 133
Using
include() 138
Using
require_once() and include_once()
138
Using
auto_prepend_file and
auto_append_file 138
Using Functions in PHP 139
Calling Functions 139
Calling an Undefined Function 141

Understanding Case and Function Names 142
Understanding Why You Should Define Your Own
Functions 142
Examining Basic Function Structure 142
Naming Your Function 143
Using Parameters 144
Understanding Scope 146
Passing by Reference Versus Passing by Value 149
Returning from Functions 150
Returning Values from Functions 151
Code Blocks 152
Implementing Recursion 153
Further Reading 155
Next 155
6 Object-Oriented PHP 157
Understanding Object-Oriented Concepts 158
Classes and Objects 158
Polymorphism 159
Inheritance 160
00 6728 fm 9/2/04 1:15 PM Page xiii
xiv
Contents
Creating Classes,Attributes, and Operations
in PHP 160
Structure of a Class 160
Constructors 161
Destructors 161
Instantiating Classes 162
Using Class Attributes 162
Controlling Access with private and public 164

Calling Class Operations 165
Implementing Inheritance in PHP 166
Controlling Visibility Through Inheritance with
private and protected 167
Overriding 168
Preventing Inheritance and Overriding with
final 170
Understanding Multiple Inheritance 171
Implementing Interfaces 171
Designing Classes 172
Writing the Code for Your Class 173
Understanding Advanced and New Object-Oriented
Functionality in PHP 181
Note: PHP4 Versus PHP5 182
Using Per-Class Constants 182
Implementing Static Methods 182
Checking Class Type and Type Hinting 183
Cloning Objects 184
Using Abstract Classes 184
Overloading Methods with
__call() 184
Using
__autoload() 185
Implementing Iterators and Iteration 186
Converting Your Classes to Strings 188
Using the Reflection API 188
Next 190
7 Exception Handling 191
Exception Handling Concepts 191
The Exception Class 193

00 6728 fm 9/2/04 1:15 PM Page xiv
xv
Contents
User-Defined Exceptions 194
Exceptions in Bob’s Auto Parts 197
Exceptions and PHP’s Other Error Handling
Mechanisms 200
Further Reading 201
Next 201
II Using MySQL
8 Designing Your Web Database 205
Relational Database Concepts 206
Tables 206
Columns 207
Rows 207
Values 207
Keys 207
Schemas 208
Relationships 209
How to Design Your Web Database 209
Think About the Real-World Objects You Are
Modeling 209
Avoid Storing Redundant Data 210
Use Atomic Column Values 212
Choose Sensible Keys 213
Think About the Questions You Want to Ask the
Database 213
Avoid Designs with Many Empty
Attributes 213
Summary of Table Types 214

Web Database Architecture 214
Architecture 214
Further Reading 216
Next 216
9Creating Your Web Database 217
Using the MySQL Monitor 218
Logging In to MySQL 219
00 6728 fm 9/2/04 1:15 PM Page xv
xvi
Contents
Creating Databases and Users 220
Creating the Database 220
Setting Up Users and Privileges 221
Introducing MySQL’s Privilege System 221
Principle of Least Privilege 221
User Setup:The GRANT Command 221
Types and Levels of Privileges 223
The REVOKE Command 225
Examples Using GRANT and REVOKE 225
Setting Up a User for the Web 226
Logging Out as
root 227
Using the Right Database 227
Creating Database Tables 227
Understanding What the Other Keywords Mean
229
Understanding the Column Types 230
Looking at the Database with SHOW and
DESCRIBE 231
Creating Indexes 232

A Note on Table Types 233
Understanding MySQL Identifiers 233
Choosing Column Data Types 234
Numeric Types 235
Further Reading 239
Next 239
10 Working with Your MySQL Database 241
What Is SQL? 241
Inserting Data into the Database 242
Retrieving Data from the Database 244
Retrieving Data with Specific Criteria 246
Retrieving Data from Multiple Tables 247
Retrieving Data in a Particular Order 253
Grouping and Aggregating Data 254
Choosing Which Rows to Return 256
Using Subqueries 256
Updating Records in the Database 259
00 6728 fm 9/2/04 1:15 PM Page xvi
xvii
Contents
Altering Tables After Creation 259
Deleting Records from the Database 262
Dropping Tables 262
Dropping a Whole Database 262
Further Reading 263
Next 263
11 Accessing Your MySQL Database from the
Web with PHP 265
How Web Database Architectures Work 266
Querying a Database from the Web 269

Checking and Filtering Input Data 270
Setting Up a Connection 271
Choosing a Database to Use 272
Querying the Database 272
Retrieving the Query Results 273
Disconnecting from the Database 274
Putting New Information in the Database 275
Using Prepared Statements 278
Using Other PHP-Database Interfaces 280
Using a Generic Database Interface: PEAR DB 280
Further Reading 283
Next 283
12 Advanced MySQL Administration 285
Understanding the Privilege System in Detail 285
The
user Ta ble 286
The db and host Ta bles 288
The
tables_priv and columns_priv Ta bles
289
Access Control: How MySQL Uses the Grant
Tables 290
Updating Privileges:When Do Changes Take
Effect? 290
Making Your MySQL Database Secure 291
MySQL from the Operating System’s Point of
View 291
Passwords 291
00 6728 fm 9/2/04 1:15 PM Page xvii
xviii

Contents
User Privileges 292
Web Issues 293
Getting More Information About Databases 293
Getting Information with SHOW 293
Getting Information About Columns with
DESCRIBE 296
Understanding How Queries Work with
EXPLAIN 296
Speeding Up Queries with Indexes 301
Optimizing Your Database 301
Design Optimization 301
Permissions 301
Table Optimization 301
Using Indexes 302
Using Default Values 302
Other Tips 302
Backing Up Your MySQL Database 302
Restoring Your MySQL Database 303
Implementing Replication 303
Setting Up the Master 304
Performing the Initial Data Transfer 304
Setting Up the Slave or Slaves 305
Further Reading 306
Next 306
13 Advanced MySQL Programming 307
The LOAD DATA INFILE Statement 307
Storage Engines 308
Transactions 309
Understanding Transaction Definitions 309

Using Transactions with InnoDB 310
Foreign Keys 311
Stored Procedures 312
Basic Example 312
Local Variables 315
Cursors and Control Structures 315
00 6728 fm 9/2/04 1:15 PM Page xviii
xix
Contents
Further Reading 319
Next 319
III E-commerce and Security
14 Running an E-commerce Site 323
Deciding What You Want to Achieve 323
Considering the Types of Commercial Websites 323
Publishing Information Using Online Brochures
324
Taking Orders for Goods or Services 327
Providing Services and Digital Goods 330
Adding Value to Goods or Services 331
Cutting Costs 331
Understanding Risks and Threats 332
Crackers 333
Failure to Attract Sufficient Business 333
Computer Hardware Failure 333
Power, Communication, Network, or Shipping
Failures 334
Extensive Competition 334
Software Errors 334
Evolving Governmental Policies and Taxes 335

System Capacity Limits 335
Deciding on a Strategy 335
Next 335
15 E-commerce Security Issues 337
How Important Is Your Information? 338
Security Threats 338
Exposure of Confidential Data 339
Loss or Destruction of Data 340
Modification of Data 341
Denial of Service 342
Errors in Software 343
Repudiation 344
Usability, Performance, Cost, and Security 345
00 6728 fm 9/2/04 1:15 PM Page xix
xx
Contents
Security Policy Creation 345
Authentication Principles 346
Authentication 347
Encryption Basics 347
Private Key Encryption 349
Public Key Encryption 349
Digital Signatures 350
Digital Certificates 351
Secure Web Servers 352
Auditing and Logging 353
Firewalls 353
Data Backups 354
Backing Up General Files 354
Backing Up and Restoring Your MySQL

Database 354
Physical Security 355
Next 355
16 Implementing Authentication with PHP and
MySQL 357
Identifying Visitors 357
Implementing Access Control 358
Storing Passwords 361
Encrypting Passwords 364
Protecting Multiple Pages 365
Using Basic Authentication 366
Using Basic Authentication in PHP 367
Using Basic Authentication with Apache’s
.htaccess Files 369
Using Basic Authentication with IIS 373
Using mod_auth_mysql Authentication 375
Installing mod_auth_mysql 375
Did It Work? 376
Using mod_auth_mysql 376
Creating Your Own Custom Authentication 377
Further Reading 378
Next 378
00 6728 fm 9/2/04 1:15 PM Page xx
xxi
Contents
17 Implementing Secure Transactions with
PHP and MySQL 379
Providing Secure Transactions 379
The User’s Machine 380
The Internet 381

Your System 382
Using Secure Sockets Layer (SSL) 383
Screening User Input 387
Providing Secure Storage 387
Determining Whether to Store Credit Card Numbers
389
Using Encryption in PHP 389
Further Reading 397
Next 398
IV Advanced PHP Techniques
18 Interacting with the File System and the
Server 401
Uploading Files 401
HTML for File Upload 402
A Note on Security 403
Writing the PHP to Deal with the File 403
Common Problems 407
Using Directory Functions 408
Reading from Directories 408
Getting Information About the Current
Directory 410
Creating and Deleting Directories 410
Interacting with the File System 411
Getting File Information 411
Changing File Properties 414
Creating, Deleting, and Moving Files 414
Using Program Execution Functions 415
Interacting with the Environment:
getenv() and
putenv() 417

Further Reading 418
Next 418
00 6728 fm 9/2/04 1:15 PM Page xxi
xxii
Contents
19 Using Network and Protocol Functions 419
Examining Available Protocols 419
Sending and Reading Email 420
Using Other Websites 420
Using Network Lookup Functions 424
Using FTP 428
Using FTP to Back Up or Mirror a File 428
Uploading Files 435
Avoiding Timeouts 435
Using Other FTP Functions 436
Further Reading 437
Next 437
20 Managing the Date and Time 439
Getting the Date and Time from PHP 439
Using the date() Function 439
Dealing with Unix Timestamps 441
Using the getdate() Function 442
Validating Dates 443
Converting Between PHP and MySQL Date Formats
444
Calculating Dates in PHP 445
Calculating Dates in MySQL 446
Using Microseconds 448
Using the Calendar Functions 448
Further Reading 449

Next 449
21 Generating Images 451
Setting Up Image Support in PHP 452
Understanding Image Formats 452
JPEG 452
PNG 453
WBMP 453
GIF 453
00 6728 fm 9/2/04 1:15 PM Page xxii
xxiii
Contents
Creating Images 454
Creating a Canvas Image 455
Drawing or Printing Text on the Image 456
Outputting the Final Graphic 458
Cleaning Up 459
Using Automatically Generated Images in Other
Pages 459
Using Text and Fonts to Create Images 460
Setting Up the Base Canvas 463
Fitting the Text onto the Button 464
Positioning the Text 467
Writing the Text onto the Button 467
Finishing Up 468
Drawing Figures and Graphing Data 468
Using Other Image Functions 476
Further Reading 477
Next 477
22 Using Session Control in PHP 479
What Session Control Is 479

Understanding Basic Session Functionality 479
What Is a Cookie? 480
Setting Cookies from PHP 480
Using Cookies with Sessions 481
Storing the Session ID 481
Implementing Simple Sessions 482
Starting a Session 482
Registering Session Variables 482
Using Session Variables 483
Unsetting Variables and Destroying the Session
483
Creating a Simple Session Example 484
Configuring Session Control 486
Implementing Authentication with Session
Control 487
Further Reading 493
Next 494
00 6728 fm 9/2/04 1:15 PM Page xxiii
xxiv
Contents
23 Other Useful Features 495
Using Magic Quotes 495
Evaluating Strings: eval() 496
Te r minating Execution: die and exit 497
Serializing Variables and Objects 497
Getting Information About the PHP
Environment 499
Finding Out What Extensions Are Loaded 499
Identifying the Script Owner 500
Finding Out When the Script Was Modified

500
Loading Extensions Dynamically 500
Temporarily Altering the Runtime Environment 500
Highlighting Source Code 501
Using PHP on the Command Line 502
Next 503
V Building Practical PHP and MySQL
Projects
24 Using PHP and MySQL for
Large Projects 507
Applying Software Engineering to Web Develop-
ment 508
Planning and Running a Web Application Project 508
Reusing Code 509
Writing Maintainable Code 510
Coding Standards 510
Breaking Up Code 513
Using a Standard Directory Structure 514
Documenting and Sharing In-House
Functions 514
Implementing Version Control 514
Choosing a Development Environment 516
Documenting Your Projects 516
Prototyping 517
00 6728 fm 9/2/04 1:15 PM Page xxiv
xxv
Contents
Separating Logic and Content 518
Optimizing Code 518
Using Simple Optimizations 519

Using Zend Products 519
Testing 520
Further Reading 521
Next 521
25 Debugging 523
Programming Errors 523
Syntax Errors 524
Runtime Errors 525
Logic Errors 530
Va r iable Debugging Aid 531
Error Reporting Levels 533
Altering the Error Reporting Settings 534
Tr iggering Your Own Errors 536
Handling Errors Gracefully 536
Next 539
26 Building User Authentication and
Personalization 541
The Problem 541
Solution Components 542
User Identification and Personalization 542
Storing Bookmarks 543
Recommending Bookmarks 543
Solution Overview 543
Implementing the Database 545
Implementing the Basic Site 546
Implementing User Authentication 549
Registering 549
Logging In 556
Logging Out 560
Changing Passwords 561

Resetting Forgotten Passwords 563
00 6728 fm 9/2/04 1:15 PM Page xxv

×