PHP and MySQL® Web Development

Fourth Edition

Luke Welling
Laura Thomson

Image Addison-Wesley

Upper Saddle River, NJ • Boston • Indianapolis • San Francisco
New York • Toronto • Montreal • London • Munich • Paris • Madrid
Cape Town • Sydney • Tokyo • Singapore • Mexico City

PHP and MySQL® Web Development, Fourth Edition
Copyright © 2009 by Pearson Education, Inc.

All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. 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 authors assume no responsibility for errors or omissions. Neither is any liability assumed for damages resulting from the use of the information contained herein.

            Library of Congress Cataloging-in-Publication Data
Welling, Luke, 1972-
   PHP and MySQL Web development / Luke Welling, Laura Thomson. - 4th
ed.
     p. cm.
   ISBN 978-0-672-32916-6 (pbk. w/cd)
   1.  PHP (Computer program language) 2.  SQL (Computer program language)
3.  MySQL (Electronic resource) 4.  Web sites-Design. I. Thomson,

Laura. II. Title.
  QA76.73.P224W45 2008
005.2’762-dc22

2008036492

Printed in the United States of America

First Printing: September 2008

ISBN-10: 0-672-32916-6
ISBN-13: 978-0-672-32916-6

Trademarks

All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Pearson Education, Inc. 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 arising from the information contained in this book or from the use of the CD-ROM or programs accompanying it.

Bulk Sales

Pearson Education, Inc. 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
   [email protected]

For sales outside the U.S., please contact

   International Sales
   [email protected]

Acquisitions Editor
Mark Taber

Development Editor
Michael Thurston

Managing Editor
Patrick Kanouse

Project Editor
Jennifer Gallant

Copy Editor
Barbara Hacha

Indexer
Tim Wright

Proofreader
Kathy Ruiz

Technical Editor
Tim Boronczyk

Publishing Coordinator
Vanessa Evans

Multimedia Developer
Dan Scherf

Book Designer
Gary Adair

Composition
Bronkella Publishing

Image

To our Mums and Dads

Image

Contents at a Glance

Introduction

I Using PHP

1 PHP Crash Course

2 Storing and Retrieving Data

3 Using Arrays

4 String Manipulation and Regular Expressions

5 Reusing Code and Writing Functions

6 Object-Oriented PHP

7 Error and Exception Handling

II Using MySQL

8 Designing Your Web Database

9 Creating Your Web Database

10 Working with Your MySQL Database

11 Accessing Your MySQL Database from the Web with PHP

12 Advanced MySQL Administration

13 Advanced MySQL Programming

III E-commerce and Security

14 Running an E-commerce Site

15 E-commerce Security Issues

16 Web Application Security

17 Implementing Authentication with PHP and MySQL

18 Implementing Secure Transactions with PHP and MySQL

IV Advanced PHP Techniques

19 Interacting with the File System and the Server

20 Using Network and Protocol Functions

21 Managing the Date and Time

22 Generating Images

23 Using Session Control in PHP

24 Other Useful Features

 V Building Practical PHP and MySQL Projects

25 Using PHP and MySQL for Large Projects

26 Debugging

27 Building User Authentication and Personalization

28 Building a Shopping Cart

29 Building a Web-Based Email Service

30 Building a Mailing List Manager

31 Building Web Forums

32 Generating Personalized PDF Documents

33 Connecting to Web Services with XML and SOAP

34 Building Web 2.0 Applications with Ajax

VI Appendixes

A Installing PHP and MySQL

B Web Resources

Index

Table of Contents

Introduction

I Using PHP

1 PHP Crash Course

Before You Begin: Accessing PHP

Creating a Sample Application: Bob’s Auto Parts

Creating the Order Form

Processing the Form

Embedding PHP in HTML

PHP Tags

PHP Statements

Whitespace

Comments

Adding Dynamic Content

Calling Functions

Using the date() Function

Accessing Form Variables

Short, Medium, and Long Variables

String Concatenation

Variables and Literals

Understanding Identifiers

Examining Variable Types

PHP’s Data Types

Type Strength

Type Casting

Variable Variables

Declaring and Using Constants

Understanding Variable Scope

Using Operators

Arithmetic Operators

String Operators

Assignment Operators

Comparison Operators

Logical Operators

Bitwise Operators

Other Operators

Working Out the Form Totals

Understanding Precedence and Associativity

Using Variable Functions

Testing and Setting Variable Types

Testing Variable Status

Reinterpreting Variables

Making Decisions with Conditionals

if Statements

Code Blocks

else Statements

elseif Statements

switch Statements

Comparing the Different Conditionals

Repeating Actions Through Iteration

while Loops

for and foreach Loops

do…while Loops

Breaking Out of a Control Structure or Script

Employing Alternative Control Structure Syntax

Using declare

Next

2 Storing and Retrieving Data

Saving Data for Later

Storing and Retrieving Bob’s Orders

Processing Files

Opening a File

Choosing File Modes

Using fopen() to Open a File

Opening Files Through FTP or HTTP

Addressing Problems Opening Files

Writing to a File

Parameters for fwrite()

File Formats

Closing a File

Reading from a File

Opening a File for Reading: fopen()

Knowing When to Stop: feof()

Reading a Line at a Time: fgets(), fgetss(), and fgetcsv()

Reading the Whole File: readfile(), fpassthru(), and file()

Reading a Character: fgetc()

Reading an Arbitrary Length: fread()

Using Other Useful File Functions

Checking Whether a File Is There: file_exists()

Determining How Big a File Is: filesize()

Deleting a File: unlink()

Navigating Inside a File: rewind(), fseek(), and ftell()

Locking Files

A Better Way: Database Management Systems

Problems with Using Flat Files

How RDBMSs Solve These Problems

Further Reading

Next

3 Using Arrays

What Is an Array?

Numerically Indexed Arrays

Initializing Numerically Indexed Arrays

Accessing Array Contents

Using Loops to Access the Array

Arrays with Different Indices

Initializing an Array

Accessing the Array Elements

Using Loops

Array Operators

Multidimensional Arrays

Sorting Arrays

Using sort()

Using asort() and ksort() to Sort Arrays

Sorting in Reverse

Sorting Multidimensional Arrays

User-Defined Sorts

Reverse User Sorts

Reordering Arrays

Using shuffle()

Using array_reverse()

Loading Arrays from Files

Performing Other Array Manipulations

Navigating Within an Array: each(), current(), reset(), end(), next(), pos(), and prev()

Applying Any Function to Each Element in an Array: array_walk()

Counting Elements in an Array: count(), sizeof(), and array_count_values()

Converting Arrays to Scalar Variables: extract()

Further Reading

Next

4 String Manipulation and Regular Expressions

Creating a Sample Application: Smart Form Mail

Formatting Strings

Trimming Strings: chop(), ltrim(), and trim()

Formatting Strings for Presentation

Formatting Strings for Storage: addslashes() and stripslashes()

Joining and Splitting Strings with String Functions

Using explode(), implode(), and join()

Using strtok()

Using substr()

Comparing Strings

Performing String Ordering: strcmp(), strcasecmp(), and strnatcmp()

Testing String Length with strlen()

Matching and Replacing Substrings with String Functions

Finding Strings in Strings: strstr(), strchr(), strrchr(), and stristr()

Finding the Position of a Substring: strpos() and strrpos()

Replacing Substrings: str_replace() and substr_replace()

Introducing Regular Expressions

The Basics

Character Sets and Classes

Repetition

Subexpressions

Counted Subexpressions

Anchoring to the Beginning or End of a String

Branching

Matching Literal Special Characters

Reviewing the Special Characters

Putting It All Together for the Smart Form

Finding Substrings with Regular Expressions

Replacing Substrings with Regular Expressions

Splitting Strings with Regular Expressions

Further Reading

Next

5 Reusing Code and Writing Functions

The Advantages of Reusing Code

Cost

Reliability

Consistency

Using require() and include()

Filename Extensions and require()

Using require() for Website Templates

Using auto_prepend_file and auto_append_file

Using Functions in PHP

Calling Functions

Calling an Undefined Function

Understanding Case and Function Names

Defining Your Own Functions

Examining Basic Function Structure

Naming Your Function

Using Parameters

Understanding Scope

Passing by Reference Versus Passing by Value

Using the return Keyword

Returning Values from Functions

Implementing Recursion

Namespaces

Further Reading

Next

6 Object-Oriented PHP

Understanding Object-Oriented Concepts

Classes and Objects

Polymorphism

Inheritance

Creating Classes, Attributes, and Operations in PHP

Structure of a Class

Constructors

Destructors

Instantiating Classes

Using Class Attributes

Controlling Access with private and public

Calling Class Operations

Implementing Inheritance in PHP

Controlling Visibility Through Inheritance with private and protected

Overriding

Preventing Inheritance and Overriding with final

Understanding Multiple Inheritance

Implementing Interfaces

Designing Classes

Writing the Code for Your Class

Understanding Advanced Object-Oriented Functionality in PHP

Using Per-Class Constants

Implementing Static Methods

Checking Class Type and Type Hinting

Late Static Bindings

Cloning Objects

Using Abstract Classes

Overloading Methods with__call()

Using __autoload()

Implementing Iterators and Iteration

Converting Your Classes to Strings

Using the Reflection API

Next

7 Error and Exception Handling

Exception Handling Concepts

The Exception Class

User-Defined Exceptions

Exceptions in Bob’s Auto Parts

Exceptions and PHP’s Other Error Handling Mechanisms

Further Reading

Next

II Using MySQL

8 Designing Your Web Database

Relational Database Concepts

Tables

Columns

Rows

Values

Keys

Schemas

Relationships

Designing Your Web Database

Think About the Real-World Objects You Are Modeling

Avoid Storing Redundant Data

Use Atomic Column Values

Choose Sensible Keys

Think About What You Want to Ask the Database

Avoid Designs with Many Empty Attributes

Summary of Table Types

Web Database Architecture

Further Reading

Next

9 Creating Your Web Database

Using the MySQL Monitor

Logging In to MySQL

Creating Databases and Users

Setting Up Users and Privileges

Introducing MySQL’s Privilege System

Principle of Least Privilege

User Setup: The GRANT Command

Types and Levels of Privileges

The REVOKE Command

Examples Using GRANT and REVOKE

Setting Up a User for the Web

Using the Right Database

Creating Database Tables

Understanding What the Other Keywords Mean

Understanding the Column Types

Looking at the Database with SHOW and DESCRIBE

Creating Indexes

Understanding MySQL Identifiers

Choosing Column Data Types

Numeric Types

Date and Time Types

String Types

Further Reading

Next

10 Working with Your MySQL Database

What Is SQL?

Inserting Data into the Database

Retrieving Data from the Database

Retrieving Data with Specific Criteria

Retrieving Data from Multiple Tables

Retrieving Data in a Particular Order

Grouping and Aggregating Data

Choosing Which Rows to Return

Using Subqueries

Updating Records in the Database

Altering Tables After Creation

Deleting Records from the Database

Dropping Tables

Dropping a Whole Database

Further Reading

Next

11 Accessing Your MySQL Database from the Web with PHP

How Web Database Architectures Work

Querying a Database from the Web

Checking and Filtering Input Data

Setting Up a Connection

Choosing a Database to Use

Querying the Database

Retrieving the Query Results

Disconnecting from the Database

Putting New Information in the Database

Using Prepared Statements

Using Other PHP-Database Interfaces

Using a Generic Database Interface: PEAR MDB2

Further Reading

Next

12 Advanced MySQL Administration

Understanding the Privilege System in Detail

The user Table

The db and host Tables

The tables_priv, columns_priv, and procs priv Tables

Access Control: How MySQL Uses the Grant Tables

Updating Privileges: When Do Changes Take Effect?

Making Your MySQL Database Secure

MySQL from the Operating System’s Point of View

Passwords

User Privileges

Web Issues

Getting More Information About Databases

Getting Information with SHOW

Getting Information About Columns with DESCRIBE

Understanding How Queries Work with EXPLAIN

Optimizing Your Database

Design Optimization

Permissions

Table Optimization

Using Indexes

Using Default Values

Other Tips

Backing Up Your MySQL Database

Restoring Your MySQL Database

Implementing Replication

Setting Up the Master

Performing the Initial Data Transfer

Setting Up the Slave or Slaves

Further Reading

Next

13 Advanced MySQL Programming

The LOAD DATA INFILE Statement

Storage Engines

Transactions

Understanding Transaction Definitions

Using Transactions with InnoDB

Foreign Keys

Stored Procedures

Basic Example

Local Variables

Cursors and Control Structures

Further Reading

Next

III E-commerce and Security

14 Running an E-commerce Site

Deciding What You Want to Achieve

Considering the Types of Commercial Websites

Publishing Information Using Online Brochures

Taking Orders for Goods or Services

Providing Services and Digital Goods

Adding Value to Goods or Services

Cutting Costs

Understanding Risks and Threats

Crackers

Failure to Attract Sufficient Business

Computer Hardware Failure

Power, Communication, Network, or Shipping Failures

Extensive Competition

Software Errors

Evolving Governmental Policies and Taxes

System Capacity Limits

Choosing a Strategy

Next

15 E-commerce Security Issues

How Important Is Your Information?

Security Threats

Exposure of Confidential Data

Loss or Destruction of Data

Modification of Data

Denial of Service

Errors in Software

Repudiation

Usability, Performance, Cost, and Security

Creating a Security Policy

Authentication Principles

Encryption Basics

Private Key Encryption

Public Key Encryption

Digital Signatures

Digital Certificates

Secure Web Servers

Auditing and Logging

Firewalls

Data Backups

Backing Up General Files

Backing Up and Restoring Your MySQL Database

Physical Security

Next

16 Web Application Security

Strategies for Dealing with Security

Start with the Right Mindset

Balancing Security and Usability

Monitoring Security

Our Basic Approach

Identifying the Threats We Face

Access to or Modification of Sensitive Data

Loss or Destruction of Data

Denial of Service

Malicious Code Injection

Compromised Server

Understanding Who We’re Dealing With

Crackers

Unwitting Users of Infected Machines

Disgruntled Employees

Hardware Thieves

Ourselves

Securing Your Code

Filtering User Input

Escaping Output

Code Organization

What Goes in Your Code

File System Considerations

Code Stability and Bugs

Execution Quotes and exec

Securing Your Web Server and PHP

Keep Software Up-to-Date

Browse the php.ini file

Web Server Configuration

Commercially Hosted Web Applications

Database Server Security

Users and the Permissions System

Sending Data to the Server

Connecting to the Server

Running the Server

Protecting the Network

Install Firewalls

Use a DMZ

Prepare for DoS and DDoS Attacks

Computer and Operating System Security

Keep the Operating System Up-to-Date

Run Only What Is Necessary

Physically Secure the Server

Disaster Planning

Next

17 Implementing Authentication with PHP and MySQL

Identifying Visitors

Implementing Access Control

Storing Passwords

Encrypting Passwords

Protecting Multiple Pages

Using Basic Authentication

Using Basic Authentication in PHP

Using Basic Authentication with Apache’s .htaccess Files

Using mod_auth_mysql Authentication

Installing mod_auth_mysql

Using mod_auth_mysql

Creating Your Own Custom Authentication

Further Reading

Next

18 Implementing Secure Transactions with PHP and MySQL

Providing Secure Transactions

The User’s Machine

The Internet

Your System

Using Secure Sockets Layer (SSL)

Screening User Input

Providing Secure Storage

Storing Credit Card Numbers

Using Encryption in PHP

Installing GPG

Testing GPG

Further Reading

Next

IV Advanced PHP Techniques

19 Interacting with the File System and the Server

Uploading Files

HTML for File Upload

Writing the PHP to Deal with the File

Avoiding Common Upload Problems

Using Directory Functions

Reading from Directories

Getting Information About the Current Directory

Creating and Deleting Directories

Interacting with the File System

Getting File Information

Changing File Properties

Creating, Deleting, and Moving Files

Using Program Execution Functions

Interacting with the Environment: getenv() and putenv()

Further Reading

Next

20 Using Network and Protocol Functions

Examining Available Protocols

Sending and Reading Email

Using Data from Other Websites

Using Network Lookup Functions

Backing Up or Mirroring a File

Using FTP to Back Up or Mirror a File

Uploading Files

Avoiding Timeouts

Using Other FTP Functions

Further Reading

Next

21 Managing the Date and Time

Getting the Date and Time from PHP

Using the date() Function

Dealing with Unix Timestamps

Using the getdate() Function

Validating Dates with checkdate()

Formatting Timestamps

Converting Between PHP and MySQL Date Formats

Calculating Dates in PHP

Calculating Dates in MySQL

Using Microseconds

Using the Calendar Functions

Further Reading

Next

22 Generating Images

Setting Up Image Support in PHP

Understanding Image Formats

JPEG

PNG

WBMP

GIF

Creating Images

Creating a Canvas Image

Drawing or Printing Text on the Image

Outputting the Final Graphic

Cleaning Up

Using Automatically Generated Images in Other Pages

Using Text and Fonts to Create Images

Setting Up the Base Canvas

Fitting the Text onto the Button

Positioning the Text

Writing the Text onto the Button

Finishing Up

Drawing Figures and Graphing Data

Using Other Image Functions

Further Reading

Next

23 Using Session Control in PHP

What Is Session Control?

Understanding Basic Session Functionality

What Is a Cookie?

Setting Cookies from PHP

Using Cookies with Sessions

Storing the Session ID

Implementing Simple Sessions

Starting a Session

Registering Session Variables

Using Session Variables

Unsetting Variables and Destroying the Session

Creating a Simple Session Example

Configuring Session Control

Implementing Authentication with Session Control

Further Reading

Next

24 Other Useful Features

Evaluating Strings: eval()

Terminating Execution: die() and exit()

Serializing Variables and Objects

Getting Information About the PHP Environment

Finding Out What Extensions Are Loaded

Identifying the Script Owner

Finding Out When the Script Was Modified

Temporarily Altering the Runtime Environment

Highlighting Source Code

Using PHP on the Command Line

Next

V Building Practical PHP and MySQL Projects

25 Using PHP and MySQL for Large Projects

Applying Software Engineering to Web Development

Planning and Running a Web Application Project

Reusing Code

Writing Maintainable Code

Coding Standards

Breaking Up Code

Using a Standard Directory Structure

Documenting and Sharing In-House Functions

Implementing Version Control

Choosing a Development Environment

Documenting Your Projects

Prototyping

Separating Logic and Content

Optimizing Code

Using Simple Optimizations

Using Zend Products

Testing

Further Reading

Next

26 Debugging

Programming Errors

Syntax Errors

Runtime Errors

Logic Errors

Variable Debugging Aid

Error Reporting Levels

Altering the Error Reporting Settings

Triggering Your Own Errors

Handling Errors Gracefully

Next

27 Building User Authentication and Personalization

Solution Components

User Identification and Personalization

Storing Bookmarks

Recommending Bookmarks

Solution Overview

Implementing the Database

Implementing the Basic Site

Implementing User Authentication

Registering Users

Logging In

Logging Out

Changing Passwords

Resetting Forgotten Passwords

Implementing Bookmark Storage and Retrieval

Adding Bookmarks

Displaying Bookmarks

Deleting Bookmarks

Implementing Recommendations

Considering Possible Extensions

Next

28 Building a Shopping Cart

Solution Components

Building an Online Catalog

Tracking Users’ Purchases While They Shop

Implementing a Payment System

Building an Administration Interface

Solution Overview

Implementing the Database

Implementing the Online Catalog

Listing Categories

Listing Books in a Category

Showing Book Details

Implementing the Shopping Cart

Using the show_cart.php Script

Viewing the Cart

Adding Items to the Cart

Saving the Updated Cart

Printing a Header Bar Summary

Checking Out

Implementing Payment

Implementing an Administration Interface

Extending the Project

Using an Existing System

Next

29 Building a Web-Based Email Service

Solution Components

Mail Protocols: POP3 Versus IMAP

POP3 and IMAP Support in PHP

Solution Overview

Setting Up the Database

Examining the Script Architecture

Logging In and Out

Setting Up Accounts

Creating a New Account

Modifying an Existing Account

Deleting an Account

Reading Mail

Selecting an Account

Viewing Mailbox Contents

Reading a Mail Message

Viewing Message Headers

Deleting Mail

Sending Mail

Sending a New Message

Replying To or Forwarding Mail

Extending the Project

Next

30 Building a Mailing List Manager

Solution Components

Setting Up a Database of Lists and Subscribers

Uploading Newsletters

Sending Mail with Attachments

Solution Overview

Setting Up the Database

Defining the Script Architecture

Implementing Login

Creating a New Account

Logging In

Implementing User Functions

Viewing Lists

Viewing List Information

Viewing List Archives

Subscribing and Unsubscribing

Changing Account Settings

Changing Passwords

Logging Out

Implementing Administrative Functions

Creating a New List

Uploading a New Newsletter

Handling Multiple File Upload

Previewing the Newsletter

Sending the Message

Extending the Project

Next

31 Building Web Forums

Understanding the Process

Solution Components

Solution Overview

Designing the Database

Viewing the Tree of Articles

Expanding and Collapsing

Displaying the Articles

Using the treenode Class

Viewing Individual Articles

Adding New Articles

Adding Extensions

Using an Existing System

Next

32 Generating Personalized PDF Documents

Project Overview

Evaluating Document Formats

Solution Components

Question and Answer System

Document Generation Software

Solution Overview

Asking the Questions

Grading the Answers

Generating an RTF Certificate

Generating a PDF Certificate from a Template

Generating a PDF Document Using PDFlib

A Hello World Script for PDFlib

Generating a Certificate with PDFlib

Handling Problems with Headers

Extending the Project

Next

33 Connecting to Web Services with XML and SOAP

Project Overview: Working with XML and Web Services

Understanding XML

Understanding Web Services

Solution Components

Using Amazon’s Web Services Interfaces

Parsing XML: REST Responses

Using SOAP with PHP

Caching

Solution Overview

Core Application

Showing Books in a Category

Getting an AmazonResultSet Class

Using REST to Make a Request and Retrieve a Result

Using SOAP to Make a Request and Retrieve a Result

Caching the Data from a Request

Building the Shopping Cart

Checking Out to Amazon

Installing the Project Code

Extending the Project

Further Reading

34 Building Web 2.0 Applications with Ajax

What Is Ajax?

HTTP Requests and Responses

DHTML and XHTML

Cascading Style Sheets (CSS)

Client-Side Programming

Server-Side Programming

XML and XSLT

Fundamental Ajax

The XMLHTTPRequest Object

Communicating with the Server

Working with the Server Response

Putting It All Together

Adding Ajax Elements to Earlier Projects

Adding Ajax Elements to PHPbookmark

For More Information

Learning More about the Document Object Model (DOM)

JavaScript Libraries for Ajax Applications

Ajax Developer Websites

Appendixes

A Installing PHP and MySQL

Installing Apache, PHP, and MySQL Under Unix

Binary Installation

Source Installation

httpd.conf File: Snippets

Is PHP Support Working?

Is SSL Working?

Installing Apache, PHP, and MySQL Under Windows

Installing MySQL Under Windows

Installing Apache Under Windows

Installing PHP for Windows

Installing PEAR

Setting Up Other Configurations

B Web Resources

PHP Resources

MySQL and SQL Specific Resources

Apache Resources

Web Development

Index

Lead Authors

Laura Thomson is a senior software engineer at Mozilla Corporation. She was formerly a principal at both OmniTI and Tangled Web Design, and she has worked for RMIT University 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. In her spare time she enjoys riding horses, arguing about free and open source software, and sleeping.

Luke Welling is a web architect at OmniTI and regularly speaks on open source and web development topics at conferences such as OSCON, ZendCon, MySQLUC, PHPCon, OSDC, and LinuxTag. Prior to joining OmniTI, he worked for the web analytics company Hitwise.com, at the database vendor MySQL AB, and as an independent consultant at Tangled Web Design. He has taught computer science at RMIT University in Melbourne, Australia, and holds a Bachelor of Applied Science (Computer Science) degree. In his spare time, he attempts to perfect his insomnia.

Contributing Authors

Julie C. Meloni is the technical director for i2i Interactive (www.i2ii.com), a multimedia company located in Los Altos, California. She has been developing web-based applications since the Web first saw the light of day and remembers the excitement surrounding the first GUI web browser. She has authored numerous books and articles on web-based programming languages and database topics, including the bestselling Sams Teach Yourself PHP, MySQL, and Apache All in One.

Adam DeFields is a consultant specializing in web application development, project management, and instructional design. He lives in Grand Rapids, Michigan where he runs Emanation Systems, LLC, (www.emanationsystemsllc.com) a company he founded in 2002. He has been involved with web development projects using several different technologies, but has developed a strong preference toward PHP/MySQL-based projects.

Marc Wandschneider is a freelance software developer, author, and speaker who travels the globe working on interesting projects. In recent years, a lot of his attention has been focused on writing robust and scalable web applications, and in 2005 he wrote a book called Core Web Application Programming with PHP and MySQL. He was was previously the main developer of the SWiK (http://swik.net) open source community site. Marc currently lives in Beijing where he spends his time mangling the Chinese language and programming.

Acknowledgments

We would like to thank the team at Pearson for all their hard work. In particular, we would like to thank Shelley Johnston, without whose dedication and patience the first three editions of this book would not have been possible, and Mark Taber, who has taken over for the fourth edition.

We appreciate immensely the work done by the PHP and MySQL development teams. Their work has made our lives easier for a number of years now and continues to do so on a daily basis.

We thank Adrian Close at eSec for saying “You can build that in PHP” back in 1998. He said we would like PHP, and it seems he was right.

Finally, we would like to thank our family and friends for putting up with us while we have been repeatedly antisocial while working on books. Specifically, thank you for your support to our family members: Julie, Robert, Martin, Lesley, Adam, Paul, Archer, and Barton.

We Want to Hear from You!

As the reader of this book, you are our most important critic and commentator. We value your opinion and want to know what we’re doing right, what we could do better, what areas you’d like to see us publish in, and any other words of wisdom you’re willing to pass our way.

You can email or write me directly to let me know what you did or didn’t like about this book—as well as what we can do to make our books stronger.

Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able to reply to every message.

When you write, please be sure to include this book’s title and authors as well as your name and phone or email address. I will carefully review your comments and share them with the authors and editors who worked on the book.

Email:                    [email protected]

Mail:                     Mark Taber
                            Associate Publisher
                            Pearson Education, Inc.
                            800 East 96th Street
                            Indianapolis, IN 46240 USA

Reader Services

Visit our website and register this book at informit.com/register for convenient access to any updates, downloads, or errata that might be available for this book.

Introduction

WELCOME TO PHP AND MYSQL WEB DEVELOPMENT. Within its pages, you will find distilled knowledge from our experiences using PHP and MySQL, two of the hottest web development tools around.

    In this introduction, we cover

Image  Why you should read this book

Image  What you will be able to achieve using this book

Image  What PHP and MySQL are and why they’re great

Image  What’s changed in the latest versions of PHP and MySQL

Image  How this book is organized

Let’s get started.

Why You Should Read This Book

This book will teach you how to create interactive websites from the simplest order form through to complex, secure e-commerce sites or interactive Web 2.0 sites. What’s more, you’ll learn how to do it using open source technologies.

This book is aimed at readers who already know at least the basics of HTML and have done some programming in a modern programming language before but have not necessarily programmed for the Internet or used a relational database. If you are a beginning programmer, you should still find this book useful, but digesting it might take a little longer. We’ve tried not to leave out any basic concepts, but we do cover them at speed. The typical readers of this book want to master PHP and MySQL for the purpose of building a large or commercial website. You might already be working in another web development language; if so, this book should get you up to speed quickly.

We wrote the first edition of this book because we were tired of finding PHP books that were basically function references. These books are useful, but they don’t help when your boss or client has said, “Go build me a shopping cart.” In this book, we have done our best to make every example useful. You can use many of the code samples directly in your website, and you can use many others with only minor modifications.

What You Will Learn from This Book

Reading this book will enable you to build real-world, dynamic websites. If you’ve built websites using plain HTML, you realize the limitations of this approach. Static content from a pure HTML website is just that—static. It stays the same unless you physically update it. Your users can’t interact with the site in any meaningful fashion.

Using a language such as PHP and a database such as MySQL allows you to make your sites dynamic: to have them be customizable and contain real-time information.

We have deliberately focused this book on real-world applications, even in the introductory chapters. We begin by looking at a simple online ordering system and work our way through the various parts of PHP and MySQL.

We then discuss aspects of electronic commerce and security as they relate to building a real-world website and show you how to implement these aspects in PHP and MySQL.

In the final part of this book, we describe how to approach real-world projects and take you through the design, planning, and building of the following projects:

Image  User authentication and personalization

Image  Shopping carts

Image  Web-based email

Image  Mailing list managers

Image  Web forums

Image  PDF document generation

Image  Web services with XML and SOAP

Image  Web 2.0 application with Ajax

You should be able to use any of these projects as is, or you can modify them to suit your needs. We chose them because we believe they represent some the most common web-based applications built by programmers. If your needs are different, this book should help you along the way to achieving your goals.

What Is PHP?

PHP is a server-side scripting language designed specifically for the Web. Within an HTML page, you can embed PHP code that will be executed each time the page is visited. Your PHP code is interpreted at the web server and generates HTML or other output that the visitor will see.

PHP was conceived in 1994 and was originally the work of one man, Rasmus Lerdorf. It was adopted by other talented people and has gone through four major rewrites to bring us the broad, mature product we see today. As of November 2007, it was installed on more than 21 million domains worldwide, and this number is growing rapidly.  You can see the current number at http://www.php.net/usage.php.

PHP is an Open Source project, which means you have access to the source code and can use, alter, and redistribute it all without charge.

PHP originally stood for Personal Home Page but was changed in line with the GNU recursive naming convention (GNU = Gnu’s Not Unix) and now stands for PHP Hypertext Preprocessor.

The current major version of PHP is 5. This version saw a complete rewrite of the underlying Zend engine and some major improvements to the language.

The home page for PHP is available at http://www.php.net.

The home page for Zend Technologies is http://www.zend.com.

What Is MySQL?

MySQL (pronounced My-Ess-Que-Ell) is a very fast, robust, relational database management system (RDBMS). A database enables you to efficiently store, search, sort, and retrieve data. The MySQL server controls access to your data to ensure that multiple users can work with it concurrently, to provide fast access to it, and to ensure that only authorized users can obtain access. Hence, MySQL is a multiuser, multithreaded server. It uses Structured Query Language (SQL), the standard database query language. MySQL has been publicly available since 1996 but has a development history going back to 1979. It is the world’s most popular open source database and has won the Linux Journal Readers’ Choice Award on a number of occasions.

MySQL is available under a dual licensing scheme. You can use it under an open source license (the GPL) free as long as you are willing to meet the terms of that license. If you want to distribute a non-GPL application including MySQL, you can buy a commercial license instead.

Why Use PHP and MySQL?

When setting out to build a website, you could use many different products.

You need to choose the following:

Image  Hardware for the web server

Image  An operating system

Image  Web server software

Image  A database management system

Image  A programming or scripting language

Some of these choices are dependent on the others. For example, not all operating systems run on all hardware, not all web servers support all programming languages, and so on.

In this book, we do not pay much attention to hardware, operating systems, or web server software. We don’t need to. One of the best features of both PHP and MySQL is that they work with any major operating system and many of the minor ones.

The majority of PHP code can be written to be portable between operating systems and web servers. There are some PHP functions that specifically relate to the filesystem that are operating system dependent, but these are clearly marked as such in the manual and in this book.

Whatever hardware, operating system, and web server you choose, we believe you should seriously consider using PHP and MySQL.

Some of PHP’s Strengths

Some of PHP’s main competitors are Perl, Microsoft ASP.NET, Ruby (on Rails or otherwise), JavaServer Pages (JSP), and ColdFusion.

In comparison to these products, PHP has many strengths, including the following:

Image  Performance

Image  Scalability

Image  Interfaces to many different database systems

Image  Built-in libraries for many common web tasks

Image  Low cost

Image  Ease of learning and use

Image  Strong object-oriented support

Image  Portability

Image  Flexibility of development approach

Image  Availability of source code

Image  Availability of support and documentation

A more detailed discussion of these strengths follows.

Performance

PHP is very fast. Using a single inexpensive server, you can serve millions of hits per day. Benchmarks published by Zend Technologies (http://www.zend.com) show PHP outperforming its competition.

Scalability

PHP has what Rasmus Lerdorf frequently refers to as a “shared-nothing” architecture. This means that you can effectively and cheaply implement horizontal scaling with large numbers of commodity servers.

Database Integration

PHP has native connections available to many database systems. In addition to MySQL, you can directly connect to PostgreSQL, Oracle, dbm, FilePro, DB2, Hyperwave, Informix, InterBase, and Sybase databases, among others. PHP 5 also has a built-in SQL interface to a flat file, called SQLite.

Using the Open Database Connectivity Standard (ODBC), you can connect to any database that provides an ODBC driver. This includes Microsoft products and many others.

In addition to native libraries, PHP comes with a database access abstraction layer called PHP Database Objects (PDO), which allows consistent access and promotes secure coding practices.

Built-in Libraries

Because PHP was designed for use on the Web, it has many built-in functions for performing many useful web-related tasks. You can generate images on the fly, connect to web services and other network services, parse XML, send email, work with cookies, and generate PDF documents, all with just a few lines of code.

Cost

PHP is free. You can download the latest version at any time from http://www.php.net for no charge.

Ease of Learning PHP

The syntax of PHP is based on other programming languages, primarily C and Perl. If you already know C or Perl, or a C-like language such as C++ or Java, you will be productive using PHP almost immediately.

Object-Oriented Support

PHP version 5 has well-designed object-oriented features. If you learned to program in Java or C++, you will find the features (and generally the syntax) that you expect, such as inheritance, private and protected attributes and methods, abstract classes and methods, interfaces, constructors, and destructors. You will even find some less common features such as iterators. Some of this functionality was available in PHP versions 3 and 4, but the object-oriented support in version 5 is much more complete.

Portability

PHP is available for many different operating systems. You can write PHP code on free Unix-like operating systems such as Linux and FreeBSD, commercial Unix versions such as Solaris and IRIX, OS X, or on different versions of Microsoft Windows.

Well-written code will usually work without modification on a different system running PHP.

Flexibility of Development Approach

PHP allows you to implement simple tasks simply, and equally easily adapts to implementing large applications using a framework based on design patterns such as Model–View–Controller (MVC).

Source Code

You have access to PHP’s source code. With PHP, unlike commercial, closed-source products, if you want to modify something or add to the language, you are free to do so.

You do not need to wait for the manufacturer to release patches. You also don’t need to worry about the manufacturer going out of business or deciding to stop supporting a product.

Availability of Support and Documentation

Zend Technologies (www.zend.com), the company behind the engine that powers PHP, funds its PHP development by offering support and related software on a commercial basis.

The PHP documentation and community are mature and rich resources with a wealth of information to share.

What Is New in PHP 5?

You may have recently moved to PHP 5 from one of the PHP 4.x versions. As you would expect in a new major version, it has some significant changes. The Zend engine beneath PHP has been rewritten for this version. Major new features are as follows:

Image  Better object-oriented support built around a completely new object model (see Chapter 6, “Object-Oriented PHP”)

Image  Exceptions for scalable, maintainable error handling (see Chapter 7, “Error and Exception Handling”)

Image  SimpleXML for easy handling of XML data (see Chapter 33, “Connecting to Web Services with XML and SOAP”)

Other changes include moving some extensions out of the default PHP install and into the PECL library, improving streams support, and adding SQLite.

At the time of writing, PHP 5.2 was the current version, with PHP 5.3 on the near horizon. PHP 5.2 added a number of useful features including:

Image  The new input filtering extension for security purposes

Image  JSON extension for better JavaScript interoperability

Image  File upload progress tracking

Image  Better date and time handling

Image  Many upgraded client libraries, performance improvements (including better memory management in the Zend Engine), and bug fixes

Key Features of PHP 5.3

You may have heard about a new major release of PHP, called PHP 6.  At the time of this writing, PHP 6 is not in the release candidate stage, and hosting providers won’t be installing it for mass use for quite some time. However, some of the key features planned in PHP 6 have been back-ported to PHP 5.3, which is a minor version release and closer to passing acceptance testing and thus installation by hosting providers (of course, if you are your own server’s administrator, you can install any version you like).

Some of the new features in PHP 5.3 are listed below; additional information also appears throughout this book as appropriate:

Image  The addition of namespaces; for more information see http://www.php.net/language.namespaces

Image  The addition of the intl extension for application internationalization; for more information see http://www.php.net/manual/en/intro.intl.php

Image  The addition of the phar extension for creating self-contained PHP application archives; for more information see http://www.php.net/book.phar

Image  The addition of the fileinfo extension for enhanced ability to work with files; for more information see http://www.php.net/manual/en/book.fileinfo.php

Image  The addition of the sqlite3 extension for working with the SQLite Embeddable SQL Database Engine; for more information see http://www.php.net/manual/en/class.sqlite3.php

Image  The inclusion of support for the MySQLnd driver, a replacement for libmysql; for more information see http://forge.mysql.com/wiki/PHP_MYSQLND

While the list above contains some of the highly-touted features of PHP 5.3, the release also includes a significant number of bug fixes and maintenance performed on existing functionality, such as:

Image  Removing support for any version of Windows older than Windows 2000 (such as Windows 98 and NT4)

Image  Ensuring the PCRE, Reflection, and SPL extensions are always enabled

Image  Adding a few date and time functions for ease of date calculation and manipulation

Image  Improving the crypt(), hash(), and md5() functionality, as well as improving the OpenSSL extension

Image  Improving php.ini administration and handling, including better error reporting

Image  Continuing to fine-tune the Zend engine for better PHP runtime speed and memory usage

Some of MySQLs Strengths

MySQLs main competitors are PostgreSQL, Microsoft SQL Server, and Oracle.

MySQL has many strengths, including the following:

Image  High performance

Image  Low cost

Image  Ease of configuration and learning

Image  Portability

Image  Availability of source code

Image  Availability of support

A more detailed discussion of these strengths follows.

Performance

MySQL is undeniably fast. You can see the developers’ benchmark page at http://web.mysql.com/whymysql/benchmarks. Many of these benchmarks show MySQL to be orders of magnitude faster than the competition. In 2002, eWeek published a benchmark comparing five databases powering a web application. The best result was a tie between MySQL and the much more expensive Oracle.

Low Cost

MySQL is available at no cost under an open source license or at low cost under a commercial license. You need a license if you want to redistribute MySQL as part of an application and do not want to license your application under an Open Source license. If you do not intend to distribute your application—typical for most web applications, or are working on free or open source Software, you do not need to buy a license.

Ease of Use

Most modern databases use SQL. If you have used another RDBMS, you should have no trouble adapting to this one. MySQL is also easier to set up than many similar products.

Portability

MySQL can be used on many different Unix systems as well as under Microsoft Windows.

Source Code

As with PHP, you can obtain and modify the source code for MySQL. This point is not important to most users most of the time, but it provides you with excellent peace of mind, ensuring future continuity and giving you options in an emergency.

Availability of Support

Not all open source products have a parent company offering support, training, consulting, and certification, but you can get all of these benefits from MySQL AB (www.mysql.com).

What Is New in MySQL 5?

Major changes introduced for MySQL 5 include

Image  Views

Image  Stored procedures (see Chapter 13, “Advanced MySQL Programming”)

Image  Basic trigger support

Image  Cursor support

Other changes include more ANSI standard compliance and speed improvements.

If you are still using an early 4.x version or a 3.x version of the MySQL server, you should know that the following features were added to various versions from 4.0:

Image  Subquery support

Image  GIS types for storing geographical data

Image  Improved support for internationalization

Image  The transaction-safe storage engine InnoDB included as standard

Image  The MySQL query cache, which greatly improves the speed of repetitive queries as often run by web applications

This book was written using MySQL 5.1 (Beta Community Edition). This version also added support for

Image  Partitioning

Image  Row based replication

Image  Event scheduling

Image  Logging to tables

Image  Improvements to MySQL Cluster, information schema, backup processes, and many bug fixes

How Is This Book Organized?

This book is divided into five main parts:

Part I, “Using PHP,” provides an overview of the main parts of the PHP language with examples. Each example is a real-world example used in building an e-commerce site rather than “toy” code. We kick off this section with Chapter 1, “PHP Crash Course.” If you’ve already used PHP, you can whiz through this chapter. If you are new to PHP or new to programming, you might want to spend a little more time on it. Even if you are quite familiar with PHP but you are new to PHP 5, you will want to read Chapter 6, “Object-Oriented PHP,” because the object-oriented functionality has changed significantly.

Part II, “Using MySQL,” discusses the concepts and design involved in using relational database systems such as MySQL, using SQL, connecting your MySQL database to the world with PHP, and advanced MySQL topics, such as security and optimization.

Part III, “E-commerce and Security,” covers some of the general issues involved in developing a website using any language. The most important of these issues is security. We then discuss how you can use PHP and MySQL to authenticate your users and securely gather, transmit, and store data.

Part IV, “Advanced PHP Techniques,” offers detailed coverage of some of the major built-in functions in PHP. We have selected groups of functions that are likely to be useful when building a website. You will learn about interaction with the server, interaction with the network, image generation, date and time manipulation, and session variables.

Part V, “Building Practical PHP and MySQL Projects,” is our favorite section. It deals with practical real-world issues such as managing large projects and debugging, and provides sample projects that demonstrate the power and versatility of PHP and MySQL.

Finally

We hope you enjoy this book and enjoy learning about PHP and MySQL as much as we did when we first began using these products. They are really a pleasure to use. Soon, you’ll be able to join the many thousands of web developers who use these robust, powerful tools to easily build dynamic, real-time websites.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset