php and mysql - pearsoncmg.com › images › ... · php has native connections available to many...

89

Upload: others

Post on 28-May-2020

25 views

Category:

Documents


0 download

TRANSCRIPT

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

All rights reserved. No part of this book shall be reproduced, stored in aretrieval system, or transmitted by any means, electronic, mechanical, pho-tocopying, recording, or otherwise, without written permission from the pub-lisher. No patent liability is assumed with respect to the use of the infor-mation contained herein. Although every precaution has been taken in thepreparation of this book, the publisher and authors assume no responsibil-ity for errors or omissions. Neither is any liability assumed for damagesresulting from the use of the information contained herein.

Library of Congress Cataloging-in-Publication DataWelling, Luke, 1972-

PHP and MySQL Web development / Luke Welling, Laura Thomson. -- 4thed.

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 2008005.2'762--dc22

2008036492

Printed in the United States of America

First Printing: September 2008

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

TrademarksAll terms mentioned in this book that are known to be trademarks or serv-ice marks have been appropriately capitalized. Pearson Education, Inc.cannot attest to the accuracy of this information. Use of a term in thisbook should not be regarded as affecting the validity of any trademark orservice mark.

Warning and DisclaimerEvery effort has been made to make this book as complete and as accurateas possible, but no warranty or fitness is implied. The information providedis on an “as is” basis. The authors and the publisher shall have neither lia-bility nor responsibility to any person or entity with respect to any loss ordamages arising from the information contained in this book or from the useof the CD-ROM or programs accompanying it.

Bulk SalesPearson Education, Inc. offers excellent discounts on this book whenordered in quantity for bulk purchases or special sales. For more informa-tion, please contact

U.S. Corporate and Government [email protected]

For sales outside the U.S., please contact

International [email protected]

Acquisitions EditorMark Taber

Development EditorMichael Thurston

Managing EditorPatrick Kanouse

Project EditorJennifer Gallant

Copy EditorBarbara Hacha

IndexerTim Wright

ProofreaderKathy Ruiz

Technical EditorTim Boronczyk

Publishing CoordinatorVanessa Evans

Multimedia DeveloperDan Scherf

Book Designer Gary Adair

CompositionBronkella Publishing

Introduction

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

In this introduction, we covern Why you should read this bookn What you will be able to achieve using this bookn What PHP and MySQL are and why they’re greatn What’s changed in the latest versions of PHP and MySQLn How this book is organized

Let’s get started.

Why You Should Read This BookThis book will teach you how to create interactive websites from the simplest orderform through to complex, secure e-commerce sites or interactive Web 2.0 sites.What’smore, 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 andhave done some programming in a modern programming language before but have notnecessarily programmed for the Internet or used a relational database. If you are a begin-ning programmer, you should still find this book useful, but digesting it might take a lit-tle longer.We’ve tried not to leave out any basic concepts, but we do cover them atspeed.The typical readers of this book want to master PHP and MySQL for the purposeof building a large or commercial website.You might already be working in another webdevelopment 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 booksthat were basically function references.These books are useful, but they don’t help whenyour boss or client has said,“Go build me a shopping cart.” In this book, we have doneour best to make every example useful.You can use many of the code samples directly inyour website, and you can use many others with only minor modifications.

2 Introduction

What You Will Learn from This BookReading this book will enable you to build real-world, dynamic websites. If you’ve builtwebsites using plain HTML, you realize the limitations of this approach. Static contentfrom a pure HTML website is just that—static. It stays the same unless you physicallyupdate 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 makeyour 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 intro-ductory chapters.We begin by looking at a simple online ordering system and work ourway through the various parts of PHP and MySQL.

We then discuss aspects of electronic commerce and security as they relate to buildinga 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 andtake you through the design, planning, and building of the following projects:

n User authentication and personalizationn Shopping cartsn Web-based emailn Mailing list managersn Web forumsn PDF document generationn Web services with XML and SOAPn Web 2.0 application with Ajax

You should be able to use any of these projects as is, or you can modify them to suityour needs.We chose them because we believe they represent some the most commonweb-based applications built by programmers. If your needs are different, this bookshould 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 anHTML page, you can embed PHP code that will be executed each time the page is vis-ited.Your PHP code is interpreted at the web server and generates HTML or other out-put that the visitor will see.

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

3Introduction

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

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

The current major version of PHP is 5.This version saw a complete rewrite of theunderlying 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 managementsystem (RDBMS).A database enables you to efficiently store, search, sort, and retrievedata.The MySQL server controls access to your data to ensure that multiple users canwork with it concurrently, to provide fast access to it, and to ensure that only authorizedusers can obtain access. Hence, MySQL is a multiuser, multithreaded server. It usesStructured Query Language (SQL), the standard database query language. MySQL has beenpublicly available since 1996 but has a development history going back to 1979. It is theworld’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 opensource 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 com-mercial 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:

n Hardware for the web servern An operating systemn Web server softwaren A database management systemn 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, andso on.

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

4 Introduction

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

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

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

In comparison to these products, PHP has many strengths, including the following:n Performancen Scalabilityn Interfaces to many different database systemsn Built-in libraries for many common web tasksn Low costn Ease of learning and usen Strong object-oriented supportn Portabilityn Flexibility of development approachn Availability of source coden Availability of support and documentation

A more detailed discussion of these strengths follows.

PerformancePHP 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 out-performing its competition.

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

Database IntegrationPHP 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 SQLinterface to a flat file, called SQLite.

5Introduction

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

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

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

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

Ease of Learning PHPThe syntax of PHP is based on other programming languages, primarily C and Perl. Ifyou already know C or Perl, or a C-like language such as C++ or Java, you will be pro-ductive using PHP almost immediately.

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

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

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

Flexibility of Development ApproachPHP allows you to implement simple tasks simply, and equally easily adapts to imple-menting large applications using a framework based on design patterns such asModel–View–Controller (MVC).

6 Introduction

Source CodeYou have access to PHP’s source code.With PHP, unlike commercial, closed-sourceproducts, 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 needto worry about the manufacturer going out of business or deciding to stop supporting aproduct.

Availability of Support and DocumentationZend Technologies (www.zend.com), the company behind the engine that powers PHP,funds its PHP development by offering support and related software on a commercialbasis.

The PHP documentation and community are mature and rich resources with awealth 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 youwould expect in a new major version, it has some significant changes.The Zend enginebeneath PHP has been rewritten for this version. Major new features are as follows:

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

n Exceptions for scalable, maintainable error handling (see Chapter 7,“Error andException Handling”)

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

Other changes include moving some extensions out of the default PHP install and intothe 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 nearhorizon. PHP 5.2 added a number of useful features including:

n The new input filtering extension for security purposesn JSON extension for better JavaScript interoperabilityn File upload progress trackingn Better date and time handlingn Many upgraded client libraries, performance improvements (including better

memory management in the Zend Engine), and bug fixes

Key Features of PHP 5.3You may have heard about a new major release of PHP, called PHP 6. At the time ofthis writing, PHP 6 is not in the release candidate stage, and hosting providers won’t be

7Introduction

installing it for mass use for quite some time. However, some of the key features plannedin PHP 6 have been back-ported to PHP 5.3, which is a minor version release and clos-er to passing acceptance testing and thus installation by hosting providers (of course, ifyou 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 alsoappears throughout this book as appropriate:

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

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

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

n 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

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

n The inclusion of support for the MySQLnd driver, a replacement for libmysql; formore 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 releasealso includes a significant number of bug fixes and maintenance performed on existingfunctionality, such as:

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

n Ensuring the PCRE, Reflection, and SPL extensions are always enabledn Adding a few date and time functions for ease of date calculation and manipula-

tionn Improving the crypt(), hash(), and md5() functionality, as well as improving the

OpenSSL extensionn Improving php.ini administration and handling, including better error reportingn Continuing to fine-tune the Zend engine for better PHP runtime speed and

memory usage

Some of MySQLs StrengthsMySQLs main competitors are PostgreSQL, Microsoft SQL Server, and Oracle.MySQL has many strengths, including the following:

n High performancen Low cost

8 Introduction

n Ease of configuration and learningn Portabilityn Availability of source coden Availability of support

A more detailed discussion of these strengths follows.

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

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

Ease of UseMost modern databases use SQL. If you have used another RDBMS, you should have notrouble adapting to this one. MySQL is also easier to set up than many similar products.

PortabilityMySQL can be used on many different Unix systems as well as under MicrosoftWindows.

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

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

9Introduction

What Is New in MySQL 5?Major changes introduced for MySQL 5 include

n Viewsn Stored procedures (see Chapter 13,“Advanced MySQL Programming”)n Basic trigger supportn 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, youshould know that the following features were added to various versions from 4.0:

n Subquery supportn GIS types for storing geographical datan Improved support for internationalizationn The transaction-safe storage engine InnoDB included as standardn 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 alsoadded support for

n Partitioningn Row based replication n Event schedulingn Logging to tablesn 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 languagewith examples. Each example is a real-world example used in building an e-commercesite rather than “toy” code.We kick off this section with Chapter 1,“PHP CrashCourse.” If you’ve already used PHP, you can whiz through this chapter. If you are newto PHP or new to programming, you might want to spend a little more time on it. Evenif you are quite familiar with PHP but you are new to PHP 5, you will want to readChapter 6,“Object-Oriented PHP,” because the object-oriented functionality haschanged significantly.

10 Introduction

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

Part III,“E-commerce and Security,” covers some of the general issues involved indeveloping 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 andsecurely gather, transmit, and store data.

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

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

FinallyWe hope you enjoy this book and enjoy learning about PHP and MySQL as much aswe 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, pow-erful tools to easily build dynamic, real-time websites.

11Accessing Your MySQL Database

from the Web with PHP

PREVIOUSLY, IN OUR WORK WITH PHP,WE used a flat file to store and retrieve data.When we looked at this file in Chapter 2,“Storing and Retrieving Data,” we mentionedthat relational database systems make a lot of these storage and retrieval tasks easier, safer,and more efficient in a web application. Now, having worked with MySQL to create adatabase, we can begin connecting this database to a web-based front end.

In this chapter, we explain how to access the Book-O-Rama database from the Webusing PHP.You learn how to read from and write to the database and how to filterpotentially troublesome input data.

Key topics covered in this chapter includen How web database architectures workn Querying a database from the Web using the basic stepsn Setting up a connectionn Getting information about available databasesn Choosing a database to usen Querying the databasen Retrieving the query resultsn Disconnecting from the databasen Putting new information in the databasen Using prepared statementsn Using other PHP-database interfacesn Using a generic database interface: PEAR MDB2

268 Chapter 11 Accessing Your MySQL Database from the Web with PHP

How Web Database Architectures WorkIn Chapter 8,“Designing Your Web Database,” we outlined how web database architec-tures work. Just to remind you, here are the steps:

1. A user’s web browser issues an HTTP request for a particular web page. For exam-ple, the user might have requested a search for all the books written by MichaelMorgan at Book-O-Rama, using an HTML form.The search results page is calledresults.php.

2. The web server receives the request for results.php, retrieves the file, and passesit to the PHP engine for processing.

3. The PHP engine begins parsing the script. Inside the script is a command to con-nect to the database and execute a query (perform the search for books). PHPopens a connection to the MySQL server and sends on the appropriate query.

4. The MySQL server receives the database query, processes it, and sends the results—a list of books—back to the PHP engine.

5. The PHP engine finishes running the script.This usually involves formatting thequery results nicely in HTML. It then returns the resulting HTML to the webserver.

6. The web server passes the HTML back to the browser, where the user can see thelist of books she requested.

Now you have an existing MySQL database, so you can write the PHP code to performthe preceding steps. Begin with the search form.The code for this plain HTML form isshown in Listing 11.1.

Listing 11.1 search.html— Book-O-Rama’s Database Search Page

<html>

<head>

<title>Book-O-Rama Catalog Search</title>

</head>

<body>

<h1>Book-O-Rama Catalog Search</h1>

<form action="results.php" method="post">

Choose Search Type:<br />

<select name="searchtype">

<option value="author">Author</option>

<option value="title">Title</option>

<option value="isbn">ISBN</option>

</select>

<br />

Enter Search Term:<br />

<input name="searchterm" type=”"text" size="40"/><br />

269How Web Database Architectures Work

<input type="submit" name="submit" value="Search"/></form>

</body>

</html>

This HTML form is reasonably straightforward.The output of this HTML is shown inFigure 11.1.

Listing 11.1 Continued

Figure 11.1 The search form is quite general, so you can search for a bookby its title, author, or ISBN.

The script that will be called when the Search button is clicked is results.php. It islisted in full in Listing 11.2.Through the course of this chapter, we discuss what thisscript does and how it works.

Listing 11.2 results.php—This Script Retrieves Search Results from the MySQLDatabase and Formats Them for Display

<html>

<head>

<title>Book-O-Rama Search Results</title>

</head>

<body>

<h1>Book-O-Rama Search Results</h1>

<?php

// create short variable names

$searchtype=$_POST['searchtype'];

$searchterm=trim($_POST['searchterm']);

270 Chapter 11 Accessing Your MySQL Database from the Web with PHP

if (!$searchtype || !$searchterm) {

echo 'You have not entered search details. Please go back and try again.';

exit;

}

if (!get_magic_quotes_gpc()){

$searchtype = addslashes($searchtype);

$searchterm = addslashes($searchterm);

}

@ $db = new mysqli('localhost', 'bookorama', 'bookorama123', 'books');

if (mysqli_connect_errno()) {

echo 'Error: Could not connect to database. Please try again later.';

exit;

}

$query = "select * from books where ".$searchtype." like '%".$searchterm."%'";

$result = $db->query($query);

$num_results = $result->num_rows;

echo "<p>Number of books found: ".$num_results."</p>";

for ($i=0; $i <$num_results; $i++) {

$row = $result->fetch_assoc();

echo "<p><strong>".($i+1).". Title: ";

echo htmlspecialchars(stripslashes($row['title']));

echo "</strong><br />Author: ";

echo stripslashes($row['author']);

echo "<br />ISBN: ";

echo stripslashes($row['isbn']);

echo "<br />Price: ";

echo stripslashes($row['price']);

echo "</p>";

}

$result->free();

$db->close();

?>

</body>

</html>

Listing 11.2 Continued

271Querying a Database from the Web

Note that this script allows you to enter the MySQL wildcard characters % and _(underscore).This capability can be useful for the user, but you can escape these charac-ters if they will cause a problem for your application.

Figure 11.2 illustrates the results of using this script to perform a search.

Figure 11.2 The results of searching the database for books about Java arepresented in a web page using the results.php script.

Querying a Database from the WebIn any script used to access a database from the Web, you follow some basic steps:

1. Check and filter data coming from the user.

2. Set up a connection to the appropriate database.

3. Query the database.

4. Retrieve the results.

5. Present the results back to the user.

These are the steps we followed in the script results.php, so now let’s go through eachof them in turn.

Checking and Filtering Input DataYou begin the script by stripping any whitespace that the user might have inadvertentlyentered at the beginning or end of his search term.You do this by applying the functiontrim() to the value of $_POST['searchterm'] when giving it a shorter name:

$searchterm=trim($_POST['searchterm']);

272 Chapter 11 Accessing Your MySQL Database from the Web with PHP

The next step is to verify that the user has entered a search term and selected a searchtype. Note that you check whether the user entered a search term after trimming white-space from the ends of $searchterm. If you arrange these lines in the opposite order,you could encounter situations in which a user’s search term is not empty and thereforedoes not create an error message; instead, it is all whitespace, so it is deleted by trim():

if (!$searchtype || !$searchterm) {

echo "You have not entered search details. Please go back and try again.";

exit;

}

You check the $searchtype variable, even though in this case it’s coming from anHTML SELECT.You might ask why you should bother checking data that has to be filledin. It’s important to remember that there might be more than one interface to your data-base. For example,Amazon has many affiliates who use its search interface.Also, it’s sensi-ble to screen data in case of any security problems that can arise because of users comingfrom different points of entry.

When you plan to use any data input by a user, you need to filter it appropriately forany control characters.As you might remember, in Chapter 4,“String Manipulation andRegular Expressions,” we described the functions addslashes(), stripslashes(), andget_magic_quotes_gpc().You need to escape data when submitting any user input to adatabase such as MySQL.

In this case, you check the value of the get_magic_quotes_gpc() function. It tellsyou whether quoting is being done automatically. If it is not, you use addslashes() toescape the data:

if (!get_magic_quotes_gpc()) {

$searchtype = addslashes($searchtype);

$searchterm = addslashes($searchterm);

}

You also use stripslashes() on the data coming back from the database. If the magicquotes feature is turned on, the data will have slashes in it when it comes back from thedatabase, so you need to take them out.

Here you use the function htmlspecialchars() to encode characters that have spe-cial meanings in HTML.The current test data does not include any ampersands (&), lessthan (<), greater than (>), or double quotation mark (“) symbols, but many fine booktitles contain an ampersand. By using this function, you can eliminate future errors.

Setting Up a ConnectionThe PHP library for connecting to MySQL is called mysqli (the i stands for improved).When using the mysqli library in PHP, you can use either an object-oriented or proce-dural syntax.

273Querying a Database from the Web

You use the following line in the script to connect to the MySQL server:

@ $db = new mysqli('localhost', 'bookorama', 'bookorama123', 'books');

This line instantiates the mysqli class and creates a connection to host localhost withusername bookorama, and password bookorama123.The connection is set up to use thedatabase called books.

Using this object-oriented approach, you can now invoke methods on this object toaccess the database. If you prefer a procedural approach, mysqli allows for this, too.Toconnect in a procedural fashion, you use

@ $db = mysqli_connect('localhost', 'bookorama', 'bookorama123', 'books');

This function returns a resource rather than an object.This resource represents the con-nection to the database, and if you are using the procedural approach, you will need topass this resource in to all the other mysqli functions.This is very similar to the way thefile-handling functions, such as fopen(), work.

Most of the mysqli functions have an object-oriented interface and a proceduralinterface. Generally, the differences are that the procedural version function names startwith mysqli_ and require you to pass in the resource handle you obtained frommysqli_connect(). Database connections are an exception to this rule because they canbe made by the mysqli object’s constructor.

The result of your attempt at connection is worth checking because none of the rest ofcode will work without a valid database connection.You do this using the following code:

if (mysqli_connect_errno()) {

echo 'Error: Could not connect to database. Please try again later.';exit;

}

(This code is the same for the object-oriented and procedural versions.) Themysqli_connect_errno() function returns an error number on error, or zero on success.

Note that when you connect to the database, you begin the line of code with theerror suppression operator, @.This way, you can handle any errors gracefully. (This couldalso be done with exceptions, which we have not used in this simple example.)

Bear in mind that there is a limit to the number of MySQL connections that canexist at the same time.The MySQL parameter max_connections determines what thislimit is.The purpose of this parameter and the related Apache parameter MaxClients isto tell the server to reject new connection requests instead of allowing machineresources to be completely used up at busy times or when software has crashed.

You can alter both of these parameters from their default values by editing the con-figuration files.To set MaxClients in Apache, edit the httpd.conf file on your system.To set max_connections for MySQL, edit the file my.conf.

274 Chapter 11 Accessing Your MySQL Database from the Web with PHP

Choosing a Database to UseRemember that when you are using MySQL from a command-line interface, you needto tell it which database you plan to use with a command such as

use books;

You also need to do this when connecting from the Web.The database to use is specifiedas a parameter to the mysqli constructor or the mysqli_connect() function. If youwant to change the default database, you can do so with the mysqli_select_db() func-tion. It can be accessed as either

$db->select_db(dbname)

or as

mysqli_select_db(db_resource, db_name)

Here, you can see the similarity between the functions that we described before:Theprocedural version begins with mysqli_ and requires the extra database handleparameter.

Querying the DatabaseTo actually perform the query, you can use the mysqli_query() function. Before doingthis, however, it’s a good idea to set up the query you want to run:

$query = "select * from books where ".$searchtype." like '%".$searchterm."%'";

In this case, you search for the user-input value ($searchterm) in the field the user spec-ified ($searchtype). Notice the use of like for matching rather than equal: it’s usuallya good idea to be more tolerant in a database search.

TipRemember that the query you send to MySQL does not need a semicolon at the end of it, unlike a query you

type into the MySQL monitor.

You can now run the query:

$result = $db->query($query);

Or, if you want to use the procedural interface, you use

$result = mysqli_query($db, $query);

You pass in the query you want to run and, in the procedural interface, the database link(again, in this case $db).

The object-oriented version returns a result object; the procedural version returns aresult resource. (This is similar to the way the connection functions work.) Either way,

275Querying a Database from the Web

you store the result in a variable ($result) for later use.This function returns false onfailure.

Retrieving the Query ResultsA large variety of functions is available to break the results out of the result object oridentifier in different ways.The result object or identifier is the key to accessing the rowsreturned by the query.

In this example, you counted the number of rows returned and also used themysqli_fetch_assoc() function.

When you use the object-oriented approach, the number of rows returned is storedin the num_rows member of the result object, and you can access it as follows:

$num_results = $result->num_rows;

When you use a procedural approach, the function mysqli_num_rows() gives you thenumber of rows returned by the query.You should pass it the result identifier, like this:

$num_results = mysqli_num_rows($result);

It’s useful to know this if you plan to process or display the results, because you nowknow how many there are and can loop through them:

for ($i=0; $i <$num_results; $i++) {

// process results

}

In each iteration of this loop, you call $result->fetch_assoc() (ormysqli_fetch_assoc()).The loop does not execute if no rows are returned.This is afunction that takes each row from the resultset and returns the row as an array, with eachkey an attribute name and each value the corresponding value in the array:

$row = $result->fetch_assoc();

Or you can use a procedural approach:

$row = mysqli_fetch_assoc($result);

Given the array $row, you can go through each field and display it appropriately, asshown in this example:

echo "<br />ISBN: ";

echo stripslashes($row['isbn']);

As previously mentioned, you call stripslashes() to tidy up the value before display-ing it.

276 Chapter 11 Accessing Your MySQL Database from the Web with PHP

Several variations can be used to get results from a result identifier. Instead of an arraywith named keys, you can retrieve the results in an enumerated array withmysqli_fetch_row(), as follows:

$row = $result->fetch_row($result);

or

$row = mysqli_fetch_row($result);

The attribute values are listed in each of the array values $row[0], $row[1], and so on.(The mysqli_fetch_array() function allows you to fetch a row as either or both kindsof array.)

You could also fetch a row into an object with the mysqli_fetch_object() func-tion:

$row = $result->fetch_object();

or

$row = mysqli_fetch_object($result);

You can then access each of the attributes via $row->title, $row->author, and so on.

Disconnecting from the DatabaseYou can free up your resultset by calling either

$result->free();

or

mysqli_free_result($result);

You can then use

$db->close();

or

mysqli_close($db);

to close a database connection. Using this command isn’t strictly necessary because theconnection will be closed when a script finishes execution anyway.

Putting New Information in the DatabaseInserting new items into the database is remarkably similar to getting items out of thedatabase.You follow the same basic steps: make a connection, send a query, and check theresults. In this case, the query you send is an INSERT rather than a SELECT.

Although this process is similar, looking at an example can sometimes be useful. InFigure 11.3, you can see a basic HTML form for putting new books into the database.

The HTML for this page is shown in Listing 11.3.

277Putting New Information in the Database

Figure 11.3 This interface for putting new books into the database could beused by Book-O-Rama’s staff.

Listing 11.3 newbook.html— HTML for the Book Entry Page

<html>

<head>

<title>Book-O-Rama - New Book Entry</title>

</head>

<body>

<h1>Book-O-Rama - New Book Entry</h1>

<form action="insert_book.php" method="post">

<table border="0">

<tr>

<td>ISBN</td>

<td><input type="text" name="isbn" maxlength="13" size="13"></td>

</tr>

<tr>

<td>Author</td>

<td> <input type="text" name="author" maxlength="30" size="30"></td>

</tr>

<tr>

<td>Title</td>

<td> <input type="text" name="title" maxlength="60" size="30"></td>

</tr>

<tr>

<td>Price $</td>

<td><input type="text" name="price" maxlength="7" size="7"></td>

278 Chapter 11 Accessing Your MySQL Database from the Web with PHP

</tr>

<tr>

<td colspan="2"><input type="submit" value="Register"></td>

</tr>

</table>

</form>

</body>

</html>

The results of this form are passed along to insert_book.php, a script that takes thedetails, performs some minor validations, and attempts to write the data into the data-base.The code for this script is shown in Listing 11.4.

Listing 11.4 insert_book.php— This Script Writes New Books into the Database

<html>

<head>

<title>Book-O-Rama Book Entry Results</title>

</head>

<body>

<h1>Book-O-Rama Book Entry Results</h1>

<?php

// create short variable names

$isbn=$_POST['isbn'];

$author=$_POST['author'];

$title=$_POST['title'];

$price=$_POST['price'];

if (!$isbn || !$author || !$title || !$price) {

echo "You have not entered all the required details.<br />"

."Please go back and try again.";

exit;

}

if (!get_magic_quotes_gpc()) {

$isbn = addslashes($isbn);

$author = addslashes($author);

$title = addslashes($title);

$price = doubleval($price);

}

@ $db = new mysqli('localhost', 'bookorama', 'bookorama123', 'books');

if (mysqli_connect_errno()) {

echo "Error: Could not connect to database. Please try again later.";

exit;

}

Listing 11.3 Continued

279Putting New Information in the Database

$query = "insert into books values

('".$isbn."', '".$author."', '".$title."', '".$price."')";

$result = $db->query($query);

if ($result) {

echo $db->affected_rows." book inserted into database.";

} else {

echo "An error has occurred. The item was not added.";

}

$db->close();

?>

</body>

</html>

The results of successfully inserting a book are shown in Figure 11.4.

Listing 11.4 Continued

Figure 11.4 The script completes successfully and reports that the book hasbeen added to the database.

If you look at the code for insert_book.php, you can see that much of it is similar tothe script you wrote to retrieve data from the database.You check that all the form fieldswere filled in, and you format them correctly for insertion into the database (if required)with addslashes():

if (!get_magic_quotes_gpc()) {

$isbn = addslashes($isbn);

280 Chapter 11 Accessing Your MySQL Database from the Web with PHP

$author = addslashes($author);

$title = addslashes($title);

$price = doubleval($price);

}

Because the price is stored in the database as a float, you don’t want to put slashes intoit.You can achieve the same effect of filtering out any odd characters on this numericalfield by calling doubleval(), which we discussed in Chapter 1,“PHP Crash Course.”This also takes care of any currency symbols that the user might have typed into theform.

Again, you connect to the database by instantiating the mysqli object and setting upa query to send to the database. In this case, the query is an SQL INSERT:

$query = "insert into books values

('".$isbn."', '".$author."', '".$title."', '".$price."')";

$result = $db->query($query);

This query is executed on the database by calling $db->query() (or mysqli_query() ifyou want to do things procedurally).

One significant difference between using INSERT and SELECT is in the use ofmysqli_affected_rows().This is a function in the procedural version or a class mem-ber variable in the object-oriented version:

echo $db->affected_rows." book inserted into database.";

In the previous script, you used mysqli_num_rows() to determine how many rows werereturned by a SELECT.When you write queries that change the database, such asINSERTs, DELETEs, and UPDATEs, you should use mysqli_affected_rows() instead.

We’ve now covered the basics of using MySQL databases from PHP.

Using Prepared StatementsThe mysqli library supports the use of prepared statements.They are useful for speedingup execution when you are performing large numbers of the same query with differentdata.They also protect against SQL injection-style attacks.

The basic concept of a prepared statement is that you send a template of the queryyou want to execute to MySQL and then send the data separately.You can send multiplelots of the same data to the same prepared statement; this capability is particularly usefulfor bulk inserts.

You could use prepared statements in the insert_book.php script, as follows:

$query = "insert into books values(?, ?, ?, ?)";

$stmt = $db->prepare($query);

$stmt->bind_param("sssd", $isbn, $author, $title, $price);

$stmt->execute();

echo $stmt->affected_rows.' book inserted into database.';

$stmt->close();

281Using Prepared Statements

Let’s consider this code line by line.When you set up the query, instead of substituting in the variables as done previously,

you put in question marks for each piece of data.You should not put any quotationmarks or other delimiters around these question marks.

The second line is a call to $db->prepare(), which is called mysqli_stmt_prepare() in the procedural version.This line constructs a statement object or resourcethat you will then use to do the actual processing.

The statement object has a method called bind_param(). (In the procedural version,it is called mysqli_stmt_bind_param().) The purpose of bind_param() is to tell PHPwhich variables should be substituted for the question marks.The first parameter is a for-mat string, not unlike the format string used in printf().The value you are passinghere (“sssd”) means that the four parameters are a string, a string, a string, and a double,respectively. Other possible characters in the format string are i for integer and b forblob.After this parameter, you should list the same number of variables as you have ques-tion marks in your statement.They will be substituted in this order.

The call to $stmt->execute() (mysqli_stmt_execute() in the procedural version)actually runs the query.You can then access the number of affected rows and close thestatement.

So how is this prepared statement useful? The clever thing is that you can change thevalues of the four bound variables and re-execute the statement without having to repre-pare.This capability is useful for looping through bulk inserts.

As well as binding parameters, you can bind results. For SELECT type queries, you canuse $stmt->bind_result() (or mysqli_stmt_bind_result()) to provide a list of vari-ables that you would like the result columns to be filled into. Each time you call $stmt->fetch() (or mysqli_stmt_fetch()), column values from the next row in the resultsetare filled into these bound variables. For example, in the book search script you lookedat earlier, you could use

$stmt->bind_result($isbn, $author, $title, $price);

to bind these four variables to the four columns that will be returned from the query.After calling

$stmt->execute();

you can call

$stmt->fetch();

in the loop. Each time this is called, it fetches the next result row into the four boundvariables.

You can also use mysqli_stmt_bind_param() and mysqli_stmt_bind_result() inthe same script.

282 Chapter 11 Accessing Your MySQL Database from the Web with PHP

Using Other PHP-Database InterfacesPHP supports libraries for connecting to a large number of databases, including Oracle,Microsoft SQL Server, and PostgreSQL.

In general, the principles of connecting to and querying any of these databases aremuch the same.The individual function names vary, and different databases have slightlydifferent functionality, but if you can connect to MySQL, you should be able to easilyadapt your knowledge to any of the others.

If you want to use a database that doesn’t have a specific library available in PHP, youcan use the generic ODBC functions. ODBC, which stands for Open DatabaseConnectivity, is a standard for connections to databases. It has the most limited function-ality of any of the function sets, for fairly obvious reasons. If you have to be compatiblewith everything, you can’t exploit the special features of anything.

In addition to the libraries that come with PHP, available database abstraction classessuch as MDB2 allow you to use the same function names for each type of database.

Using a Generic Database Interface: PEAR MDB2Let’s look at a brief example using the PEAR MDB2 abstraction layer.This is one of themost widely used of all the PEAR components. Instructions for installing the MDB2abstraction layer can be found in the “PEAR Installation” section in Appendix A,“Installing PHP and MySQL.”

For comparative purposes, let’s look at how you could write the search results scriptdifferently using MDB2.

Listing 11.5 results_generic.php—Retrieves Search Results from the MySQLDatabase and Formats Them for Display

<html>

<head>

<title>Book-O-Rama Search Results</title>

</head>

<body>

<h1>Book-O-Rama Search Results</h1>

<?php

// create short variable names

$searchtype=$_POST['searchtype'];

$searchterm=trim($_POST['searchterm']);

if (!$searchtype || !$searchterm) {

echo "You have not entered search details. Please go back and try again.";

exit;

}

if (!get_magic_quotes_gpc()) {

$searchtype = addslashes($searchtype);

283Using Other PHP-Database Interfaces

$searchterm = addslashes($searchterm);

}

// set up for using PEAR MDB2

require_once('MDB2.php');

$user = 'bookorama';

$pass = 'bookorama123';

$host = 'localhost';

$db_name = 'books';

// set up universal connection string or DSN

$dsn = "mysqli://".$user.":".$pass."@".$host."/".$db_name;

// connect to database

$db = &MDB2::connect($dsn);

// check if connection worked

if (MDB2::isError($db)) {

echo $db->getMessage();

exit;

}

// perform query

$query = "select * from books where ".$searchtype." like '%".$searchterm."%'";

$result = $db->query($query);

// check that result was ok

if (MDB2::isError($result)) {

echo $db->getMessage();

exit;

}

// get number of returned rows

$num_results = $result->numRows();

// display each returned row

for ($i=0; $i <$num_results; $i++) {

$row = $result->fetchRow(MDB2_FETCHMODE_ASSOC);

echo "<p><strong>".($i+1).". Title: ";

echo htmlspecialchars(stripslashes($row['title']));

echo "</strong><br />Author: ";

echo stripslashes($row['author']);

echo "<br />ISBN: ";

echo stripslashes($row['isbn']);

Listing 11.5 Continued

284 Chapter 11 Accessing Your MySQL Database from the Web with PHP

echo "<br />Price: ";

echo stripslashes($row['price']);

echo "</p>";

}

// disconnect from database

$db->disconnect();

?>

</body>

</html>

Let’s examine what you do differently in this script.To connect to the database, you use the line

$db = MDB2::connect($dsn);

This function accepts a universal connection string that contains all the parameters nec-essary to connect to the database.You can see this if you look at the format of the con-nection string:

$dsn = "mysqli://".$user.":".$pass."@".$host."/".$db_name;

After this, you check to see whether the connection was unsuccessful using theisError() method and, if so, print the error message and exit:

if (MDB2::isError($db)) {

echo $db->getMessage();

exit;

}

Assuming everything has gone well, you then set up a query and execute it as follows:

$result = $db->query($query);

You can check the number of rows returned:

$num_results = $result->numRows();

You retrieve each row as follows:

$row = $result->fetchRow(DB_FETCHMODE_ASSOC);

The generic method fetchRow()can fetch a row in many formats; the parameterMDB2_FETCHMODE_ASSOC tells it that you would like the row returned as an associative array.

After outputting the returned rows, you finish by closing the database connection:

$db->disconnect();

As you can see, this generic example is similar to the first script.

Listing 11.5 Continued

285Next

The advantages of using MDB2 are that you need to remember only one set of data-base functions and that the code will require minimal changes if you decide to changethe database software.

Because this is a MySQL book, we use the MySQL native libraries for extra speedand flexibility.You might want to use the MDB2 package in your projects because some-times the use of an abstraction layer can be extremely helpful.

Further ReadingFor more information on connecting MySQL and PHP together, you can read theappropriate sections of the PHP and MySQL manuals.

For more information on ODBC, visit http://www.webopedia.com/TERM/O/ODBC.html.

NextIn the next chapter, we go into more detail about MySQL administration and discusshow to optimize databases.

Index

SYMBOLS! (logical operator), 38!= (comparison operator), 37!= (inequality operator), 40, 87!== (comparison operator), 37!== (non-identity operator), 40, 87$result->fetch_assoc() function, 275$type parameter, 829% (modulus operator), 33% (wildcard character), 293%= (combined assignment operator), 35& (bitwise operator), 38& (reference operator), 36&& (logical operator), 38+ (addition operator), 33+ (plus symbol), 126, 748+ (union operator), 40, 87++ (increment operator), 35-36+= (combined assignment operator), 35, (comma operator), 39- (subtraction operator), 33— (decrement operator), 35-36-= (combined assignment operator), 35. (string concatenation operator), 26-27.= (combined assignment operator), 35/ (division operator), 33/= (combined assignment operator), 35< (comparison operator), 37<< (bitwise operator), 38<= (comparison operator), 37= (assignment operator), 34== (comparison operator), 37== (equality operator), 40, 87== (equals comparison operator), 37=== (comparison operator), 37=== (identity operator), 40, 87?: (ternary operator), 39@ (error suppression operator), 39

Aa file mode, 63a+ file mode, 63about.php files (Tahuayo application), 819absolute paths, 62abstract classes, 186access

associative array contents, 85control (authentication)

implementing, 392-395multiple pages, protecting, 399passwords, 395-399

modifiers, 166-167MySQL, 219-220numerically indexed array contents,

accessing, 83-84to .php files, restricting, 374-375restricting to sensitive data, 364substrings, substr() function, 118-119

accountscreating, 668-669deleting, 670modifying, 670online newsletters, 702-705, 719selecting, 671, 673setting up, 666-668

ACID compliance transactions, 313Acrobat Web site, 776actions

Amazon, 826MLM, 701script architecture, 694

Add to Cart link, 817add_bm() function, 597-598, 881add_bms.php files (PHPBookmark applica-

tion), 572add_bm_form.php files (PHPBookmark

application), 572add_quoting() function, 766addBMResponse() function, 874adding Ajax elements to PHPbookmark proj-

ects, 871-880addition (+) operator, 33addNewBookmark() function, 873addslashes() function, 114, 272, 296, 417addToCart() function, 852

admin.php files (Shopping Cart application),611

admin.php script (Shopping Cart applica-tion), 641-643

admin_fns.php files (Shopping Cart applica-tion), 612

administration, 609, 643-650administration menu (admin.php),

641-643edit_book_form.php script, 646functions, online newsletters, 721insert_book.php script, 644-645insert_book_form.php script, 644show_book.php script, 646users, 226-227views, 609

AdobeFDF Web site, 789PostScript, 774-775Web site, 776

Advanced Maryland Automated NetworkDisk Archiver (AMANDA), 358

advanced OO features, 184-186, 191aggregate functions, MySQL, 256aggregating data, 256-257Ajax, 856

bookmarks, adding, 872developer Web sites, 885elements, 871-880JavaScript libraries, 884servers

communication, 863-864response, 866

XMLHTTPRrequest object, 860-862ajaxServerTime.html, 866-869aliases, tables, 253-254ALL privilege, 227ALTER privilege, 225ALTER TABLE statement, 261-263AMANDA (Advanced Maryland Automated

Network Disk Archiver), 358Amazon

actions, 826Associate ID, 813books, showing in categories, 826-828browse nodes, 816caching, 814-815, 846-849checking out, 852-853

912 a file mode

connecting, 807-808constants.php file, 823developer token, 813index.php file, 820-826PHP SOAP libraries, 814project codes, installing, 853-854REST/XML, 838-839, 844sessions, creating, 823shopping carts, building, 813, 849-852SOAP (Simple Object Access

Protocol), 845-846solution overview, 815-820Web Services interfaces, 813-814XML, parsing, 814

AmazonResultSet class, 819, 828-829Analog Web site, 330anchoring strings, 126-127and operator, 38anomalies, avoiding (Web databases), 213anonymous login (FTP), 462ANSI Web site, 265anti-aliasing text, 489Apache

configurations, PHP installations, 904HTTP server, 380-381installation

binary installations, 890source installations, 891Windows, 902

parameters, MaxClients, 273resources, 909running, 897Software Web site, 909Today Web site, 909Web server

basic authentication (HTTP),400-406

htpasswd program, 405mod_auth module, 402mod_auth_mysql module, 406-408

Web site, 891Week Web site, 909

applicationsarchives, 7Bob’s Auto Parts, 14, 17, 199-202

Book-O-Rama applicationDatabase Search page, 268schema, 219, 230

content, 546development environment, 544documentation, 544-545internationalization, 7layer protocols, 414logic, 546optimizations, 546-547PHPBookmark

creating, 569extensions, 606files, 572

planning, 536-537prototypes, 545-546rewriting code, 537-538running, 536-537Shopping Cart. See Shopping Cart

applicationSmart Form Mail

creating, 107-109regular expressions, 128-129

software engineering, 536Tahuayo (Amazon), 815-820testing code, 548tiers, 218version control, 542-543Web forum. See Web forum applica-

tionwriting maintainable code, 538

breaking up, 541-542code standards, 538commenting, 540directory structures, 542function libraries, 542indenting, 540-541naming conventions, 538-540

architecture, Web databases, 216-218archives

applications, 7BUGTRAQ, 437

arguments, 22Array data type (variables), 29array() language construct, 82array_count_values() function, 104

913array_count_values() function

array_push() function, 713array_reverse() function, 97-98array_walk() function, 103-104arrays, 81-82

associative, 85contents, accessing, 85each() function, 85-87initializing, 85list() function, 85-87looping through, 85-87

bounding box contents, 497categoryList, 827converting to scalar variables, 105-106elements, 82

applying functions, 103-104counting, 104

functions, passing by reference, 104indexes, 82key-value pairs, getdate() function, 473loading from files, 98-101medium style form variable, 24multidimensional, 81, 88-92

sorting, 93-95three-dimensional arrays, 90, 92two-dimensional arrays, 88-90

navigating within an array, 102numerically indexed arrays

accessing with loops, 84contents, accessing, 83-84initializing, 82-83

operators, 33-34, 87-88reordering, 96

array_reverse() function, 97-98shuffle() function, 96

set cardinality, 104sorting, 92

asort() function, 93ksort() function, 93reverse order, 93sort() function, 92

superglobal, 24article list (Web forum application), 747,

749adding new articles, 762-769displaying articles, 752-753plus symbols, 748

threadscollapsing, 748-752expanding, 748-751

treenode class, 753, 757-760viewing individual articles, 760-762

ASCII, 772ASINSearch() method, 829asort() function, 93ASP style (PHP tags), 19assignment operators, 28, 34

combination assignment operators, 35decrement operators, 35-36equal sign (=), 25increment operators, 35-36reference operator, 36returning values, 34-35

Associate ID (Amazon), 813associative arrays, 85. See also arrays

contents, accessing, 85each() function, 85-87initializing, 85list() function, 85-87looping through, 85, 87

associativity, operators, 42-44asterisk symbol (*), regular expressions, 126atomic column values (databases), 214-215attachments, email, 689attributes, 162-166

creating, 162-164overriding, 170-173

auditing, 357authentication, 343, 350-351, 383-384,

401-406. See also securityaccess control

encrypting passwords, 397-399implementing, 392-395multiple pages, protecting, 399storing passwords, 395

basic authentication (HTTP), 399-400with Apache .htaccess files,

402-406in PHP, 400-402

custom, creating, 408digest authentication (HTTP), 400identifying users, 391-392

914 array_push() function

mod_auth_mysql module, 406-408documentation Web sites, 408installing, 406-407testing, 407

passwords, 350-351session control, 517-524

authmain.php script, 517-522logout.php script, 523-524members_only.php script, 522-523

usersinput data, validating, 580logging in, 584-587logging out, 587-588passwords, 588-595registering, 577, 580-583

Web sites, 408authmain.php script (authentication),

517-522auto_append_file (php.ini file), 142-143AUTO_INCREMENT keyword, 231auto_prepend_file (php.ini file), 142-143autocommit mode, 314autoload()function, 187automatic generation of images, 490-491AVG(column) function, 256

Bb file mode, 63backing up, 358

AMANDA (Advanced MarylandAutomated Network Disk Archiver),358

databases, 305-306FTP functions, 459-463

checking update times, 464-465closing connections, 466downloads, 465-466logins, 463remote connections, 463

MySQL databases, 358backticks, 448backtrace (functions), 196base canvases, 495baseline descenders, 497basename() function, 442, 445

basic authentication (HTTP), 399-400with Apache .htaccess files, 402-406in PHP, 400-402

binary installations, 890MySQL, 892-893

binary large objects (BLOB types), 239, 241bind_param() method, 281bindings, late static bindings, 185-186bitwise operators, 38BLOB types (binary large objects), 239-241blocks, 47

catch (exception handling), 194try (exception handling), 193

Bob’s Auto Parts application, 14, 17exception handling, 199-202

book details page (Shopping Cart applica-tion), 616, 622-623, 646

Book-O-Rama applicationDatabase Search page, 268schema, 219, 230setting up, 243tables, SQL code, 245

book_fns.php files (Shopping Cart applica-tion), 612

book_sc database (Shopping Cart applica-tion), 612, 614-615

book_sc.sql files (Shopping Cart applica-tion), 612

book_sc_fns.php files (Shopping Cart appli-cation), 612

bookdisplayfunctions.php files (Tahuayoapplication), 819

bookmark_fns.php files (PHPBookmarkapplication), 572

bookmarks, 571adding, 596-599, 872bookmark.gif files (PHPBookmark

application), 572deleting, 600-602displaying, 599recommending, 571storing, 571

bookmarks.sql files (PHPBookmark applica-tion), 572

books, Amazon categories, 826, 828Boolean data type (variables), 29bottom-up approach to security, 363bottom.php files (Tahuayo application), 819

915bottom.php files (Tahuayo application)

bounding boxesarray contents, 497coordinates, 496

Boutell Web site, 508branching (regular expressions), 127break statement, 56breaking up code, 541-542brochureware sites, 328

common pitfalls, 330limitations, 328

answering feedback, 329lack of information, 328poor presentation, 329tracking success, 330-331updated information, 329

browse nodes (Amazon), 816browsedir.php file, 439browseNode variable, 824browseNodeSearch() function, 845browseNodeSearch() method, 829, 835browsers

authentication, 351directories, 439secure transactions, 410-411Web database architecture, 216

bugs, 376-377PHP 5.3 fixes, 7regression, 377

BUGTRAQ archives, 437building MLM, 687buttons

colors, 495make_button.php scripts, 492scripts, calling, 493text

colors/fonts, 492fitting onto, 495-498positioning, 498-499writing, 499

Ccache() function, 847-848cached() function, 847-848cachefunctions.php files (Tahuayo applica-

tion), 820caching Amazon, 814-815, 846-849calculate_items() function, 630-631

calculate_price() function, 630-631calculating dates

in MySQL, 478-480in PHP, 477-478

calendar functions, 480-481calling

button scripts, 493class operations, 167functions, 22, 143

case sensitivity, 146errors, 66parameters, 143-144prototypes, 144undefined functions, 145-146

canvasbase, 495images, creating, 487

caret symbol (^), regular expressions,126-127

Cartesian product, 250, 254cartfunctions.php files (Tahuayo application),

820CAs (Certifying Authorities), 355cascading style sheets (CSS), 546case sensitivity

calling functions, 146MySQL statements, 221strings, changing, 113-114

casts (variable types), 30catalog scripts (Shopping Cart application),

615-617index.php, 615-620show_book.php, 616, 622-623, 646show_cat.php, 615, 620-622

catch blocks (exception handling), 194categories, Amazon books, 826, 828category page (Shopping Cart application),

615, 620-622categoryfunctions.php files (Tahuayo applica-

tion), 820categoryList array, 827Certificate Signing Request (CSR), 356-357certification projects, personalized docu-

ments, 779files, 779index.html file, 780-781PDF, 788-796PDFlib, 796, 802-804

916 bounding boxes

RTF, 784-787score.php file, 782-784

Certifying Authorities (CAs), 355CGI Interpreter, 890CGI specification Web site, 450change_passwd.php files (PHPBookmark

application), 572change_passwd_form.php files

(PHPBookmark application), 572change_password() function, 590, 720change_password.php files (Shopping Cart

application), 611change_password_form.php files (Shopping

Cart application), 611characters

classes, 125escaping, 114padding, 112reading, 75sets, 124-125

check_admin_user() function, 700check_auth_user() function, 665check_logged_in() function, 700check_normal_user() function, 700check_valid_user() function, 585checkdate() function, 370, 474Checkout links, 818checkout.php files (Shopping Cart applica-

tion), 611checkout.php script (Shopping Cart applica-

tion), 633-638chgrp() function, 446child nodes (Web forum tree structure), 743chmod() function, 446chown() function, 446ciphertext (encryption), 351classes, 160-161

abstract, 186AmazonResultSet, 828-829attributes, 164-166calling, 167character (regular expressions), 125converting to strings, 190creating, 162-164CSS, 859designing, 174-175Exception, 195-196

extending, 196-197methods, 195

exceptions, creating, 196inheritance, 162instantiating, 164polymorphism, 161Product, 839tree_node class, 743treenode class (Web forum applica-

tion), 753-760type hinting, 184writing code for, 175-183

clausesGROUP BY, 256-257HAVING, 257LIMIT, 258ORDER BY, 255SELECT, 255-257throw, 196WHERE, 248

comparison operators, 248-249join condition, 250

client-side programming, 859cloning objects, 186closedir($dir) function, 440closing tags (XML), 810code

blocks, 47content, 546execution directives, 57indenting, 47logic, 546naming conventions, 539organizing, 374optimizations, 546-547prototypes, 545-546reusing. See reusing coderewriting, 537-538Shopping Cart application, 610testing, 548version control, 542-543

CVS (Concurrent VersionsSystem), 543

multiple programmers, 543repository, 542-543

writing, 538-541Codewalkers Web site, 909collapsing threads (Web forum application),

748, 752

917collapsing threads (Web forum application)

colorsbuttons, 495RGB (red, green, and blue), 488text, 492

columns, 232-236date and time types, 238-239DESCRIBE statement, 299keys, 209

creating, 215foreign keys, 210primary keys, 210

numeric types, 236-238floating point data types, 237-238integral data types, 237

string, 239-241values, 209

atomic column values, 214-215EXPLAIN statement, 303

columns_priv table, 288, 292-293combination assignment operators, 35comma (,) operator, 39command line, 531commands

DESCRIBE, 233-234GRANT, 223-228LOCK TABLES, 305mysql, 221mysql_dump, 305phpinfo(), 31REVOKE, 227-228SHOW, 233-234SQL, 229-231traceroute (UNIX), 344Web server functions, 447-450

comments, 20-21, 540commercial Web sites, 327, 336

adding value to goods or services, 335authentication, 343cutting costs, 335-336firewalls, 357-358importance of stored information, 342online brochures, 328

common pitfalls, 330limitations, 328-331

orders for goods or services, 331-334privacy policies, 333

providing services and digital goods,334-335

return policies, 333risks, 336

competition, 338crackers, 337failure to attract business, 337-338hardware failure, 337legislation and taxes, 339service provider failures, 338software errors, 338system capacity limits, 339

security, 342auditing, 357authentication, 350-351backing up data, 358Certificate Signing Request

(CSR), 356-357Certifying Authorities (CAs), 355compromises, 349digital certificates, 355digital signatures, 354-355encryption, 351-354hash function, 354log files, 357passwords, 350-351physical security, 359Secure Web servers, 356-357security policies, creating, 349-350threats, 342-348

SSL (Secure Sockets Layer), 333strategies, selecting, 339types, 327-328

committed transactions, 314comparing strings, 119

length, testing, 120strcasecmp() function, 119strcmp() function, 119strnatcmp() function, 119

comparison operators, 36-37equals operator, 37WHERE clauses, 248-249

compatibility of commercial Web sites, 334components, user personalization, 570compression, SSL (Secure Sockets Layer),

416

918 colors

compromised servers, 365Concurrent Versions System (CVS), 543conditionals, 46

code blocks, 47comparing, 51else statements, 47elseif statements, 48-49if statements, 46-47indenting code, 47switch statements, 49-51

conditions, join, 250configuration

DMZs, 386-387PHP, 894sessions, 516-517web servers

Apache HTTP server, 380-381Microsoft IIS, 381

connectionsAmazon, 807-808Database servers, 384-385FTP servers, closing, 466MySQL database, 293networks, runtime errors, 557-558remote FTP servers, 463Web databases, 273

constants, 31error reporting, 562

constants.php filesAmazon, 823Tahuayo application, 819

constructors, 163-164content (code), 546continuation symbol (MySQL), 220continue handlers, 320continue statements, 56control

characters\n (newline), 68\t (tab), 68

structures, 46, 49alternate syntax, 56breaking out of, 56conditionals, 46-51declare, 57

loops, 51-56stored procedures, 319-323

version (code), 542-543CVS (Concurrent Versions System),

543multiple programmers, 543repository, 542-543

conversionarrays to scalar variables, 105-106calendars, 481classes to strings, 190format strings, 112-113printf() function, 112-113type codes, 112-113

cookies, 510-511session IDs, 511-512setting, 510-511

coordinates, bounding boxes, 496copy() function, 447correlated subqueries, 260cos() function, 804count() function, 104COUNT(items) function, 256counting array elements, 104crackers, 337, 366CREATE privilege, 226CREATE TABLE command (SQL), 229-231CREATE TEMPORARY TABLES privilege, 226create_database.php files (Warm Mail appli-

cation), 655create_database.sql files, 745

MLM application, 691Web forum application, 744

credit card numbers, storing, 419criteria, retrieving from databases, 248-249cross join, 254crypt() function, 397-398

PHP 5.3, functionality in, 7cryptography, 352CSR (Certificate Signing Request), 356-357CSS (cascading style sheets), 546, 858

classes, 859curly braces ({}), regular expressions, 126current() function, 102cursors (stored procedures), 319-323custom authentication, creating, 408cutting costs (commercial Web sites), 335-336CVS (Concurrent Versions System), 543

919CVS (Concurrent Versions System)

Ddata

aggregating, 256-257encrypting, 418graphing, 499-507grouping, 256-257input

checking, 558user authentication validation, 580

inserting into databases, 244-245joins, 254-255loading from files, 311redundant data, avoiding (Web databas-

es), 212-213retrieving

from databases, 246-247from multiple tables, 249-250in a particular order, 255-256with specific criteria, 248-249

rows, returning, 258sensitive data

credit card numbers, storing, 419storing, 417-418

storing, 59tables

aliases, 253-254joining, 251-252rows unmatched, 252-253two-table joins, 250-251

transfer, 306-308types

BLOB types (binary large objects),239

date and time data types, 238-239floating point data types (numeric

column types), 237-238integral data types (numeric col-

umn types), 237TEXT types, 239variables, 29

Data Definition Languages (DDL), 244Data Encryption Standard (DES), 353Data Manipulation Languages (DML), 244data_valid_fns.php files

MLM application, 691PHPBookmark application, 572

Shopping Cart application, 612Warm Mail application, 655Web forum application, 744

databases, 208backing up, 305-306benefits, 80, 207Book-O-Rama

setting up, 243tables, SQL code, 245

book_sc database (Shopping Cartapplication), 612-615

creating with MySQL, 222data

aggregating, 256-257grouping, 256-257inserting, 244-245joins, 254-255loading from files, 311retrieving, 246-256rows unmatched, 252-253tables, 251-254two-table joins, 250-251

DDL (Data Definition Languages), 244DML (Data Manipulation Language),

244dropping, 264front page, 574-577information gathering, 296

EXPLAIN statement, 299-303SHOW statement, 296-297

keys, 209foreign keys, 210primary keys, 210

lists, 688MySQL, 287

aggregate functions, 256backing up, 358columns_priv table, 292connection verification, 293db table, 290-291host table, 291join types, 254-255request verification, 293results.php script, 269tables_priv table, 292

920 data

user table, 289Web database architecture, 268-271

optimizing, 304-305default values, 305designs, 304indexes, 305permissions, 304tables, 304

passwordsencrypting, 295storing, 295

PEAR, 284-285privilege system, 287-288

columns_priv table, 293db table, 290-291grant table, 293host table, 290-291privileges, updating, 293-294tables_priv table, 293user table, 289-290

queries, indexes, 304records

deleting, 264updating, 261

relational databases, 210relationships, 211

many-to-many relationships, 211one-to-many relationships, 211one-to-one relationships, 211, 216

replication, 306-307data transfer, 306-308master servers, 306-307slaves, 306-308

restoring, 306rows, returning, 258runtime errors, 555-557schemas, 210, 573-574security, 294

operating system, 294passwords, 295user privileges, 295-296Web issues, 296

selecting in MySQL, 229

serversconnecting to, 384-385security, 383-385

setting up (online newsletters),692-694

Shopping Cart application, 615SQL (Structured Query Language),

243-244subqueries, 258-259

correlated, 260operators, 259row, 260temporary tables, 260

subscribers, 688tables, 208

altering, 261-263Cartesian product, 250columns, 209, 232-241creating in MySQL, 229-231dropping, 264equi-joins, 251indexes, creating, 234-235joins, 250keywords, 231left joins, 252-253rows, 209types, 216, 229values, 209viewing, 233-234

Warm Mail application (email client),655-656

Web forum application, 744-745, 747date and time

calendars, 481column types, 238-239converting between PHP and MySQL

formats, 476-477data types, 238-239in MySQL

calculations, 478-480DATE_FORMAT() function,

476-477MySQL Web site, 481UNIX_TIMESTAMP() function,

476-477

921date and time

in PHP, 469, 474calculations, 477-478calendar functions, 480-481checkdate() function, 474date() function, 469-472floor() function, 478getdate() function, 473microseconds, 480mktime() function, 471-472PHP Web site, 481

date() function, 21-22, 445, 469-471format codes, 469-471Unix timestamps, 471-472

date_add() function, 478DATE_FORMAT() function, 476-477date_sub() function, 478db table, 288, 290-291db_connect() function, 583db_fns.php files

MLM application, 691PHPBookmark application, 572Shopping Cart application, 612Warm Mail application, 655Web forum application, 744

db_result_to_array() function, 619DDL (Data Definition Languages), 244DDoS (Distributed Denial of Service), 346,

364preparing for, 387

debugging variables, 559-561declare control structure, 57declare handlers, 320declaring

functions, 146-147stored functions, 318-319stored procedures, 316-317

decoct() function, 446decrement operators, 35-36decryption, 352default values, database optimization, 305DELETE privilege, 225DELETE statement, 264delete_account() function, 670delete_bm() function, 601delete_bms.php files

PHPBookmark application, 572Shopping Cart application, 612

delete_category.php files (Shopping Cartapplication), 612

delete_message() function, 681-682deletion anomalies, avoiding (Web databas-

es), 213Denial of Service (DoS), 346-347, 364deploying new software versions, 379deregistering variables, 513DES (Data Encryption Standard), 353DESC keyword, 255descenders (letters), 497DESCRIBE command, 233-234DESCRIBE statement, 299describe user; statement, 289design. See also configuration

classes, 174-175database optimization, 304Web databases, 211

anomalies, avoiding, 213atomic column values, 214-215keys, creating, 215null values, avoiding, 216questions, formulating, 215real-world objects, modeling, 211-212redundant data, avoiding, 212-213table types, 216

design_button.html file, 492-493destroying sessions, 513destructors, 163-164Details link, 817developer token (Amazon), 813development environments, 544Devshed Web site, 508, 908DHTML (Dynamic HTML), 857diagrams

entity relationship, 210online newsletters, 689-691

die() language construct, 526digest authentication (HTTP), 400digital certificates, 355digital goods (commercial Web sites), provid-

ing, 334-335digital signatures, 354-355directives

execution, 57magic_quotes_gpc, 417magic_quotes_runtime, 417php.ini file, editing, 529-530

922 date and time

directoriesbrowsing, 439extensions, copying libpdf_file, 899files, write permissions, 418functions, 439

creating directories, 443deleting directories, 443file paths, 442-443reading from directories, 439-441

structures, 542dirname() function, 442, 445disabling unnecessary OS applications, 388disaster recovery, 364

planning, 388-389disconnecting Web databases, 276discussion board application, 741-742,

763-764article list, 747-749

collapsing threads, 748-752displaying articles, 752-753expanding threads, 748-751individual articles, viewing,

760-762new articles, adding, 762-769plus symbols, 748treenode class, 753, 757-760

database design, 744-747extensions, 769files, 744posters, 744solutions, 742-744tree structure, 742-743tree_node class, 743

discussion boards, 741discussion_fns.php files (Web forum applica-

tion), 744disgruntled employees, 366disk_free_space($path) function, 443display() function, 758display_account_form() function, 667, 703,

719display_account_select() function, 672-673display_account_setup() function, 667, 669display_book_form() function, 647display_button() function, 733display_cart() function, 627-630display_categories() function, 618-619

display_information() function, 713-714display_items() function, 709display_list() function, 674display_list_form() function, 722display_mail_form() function, 726display_message() function, 678display_password_form() function, 719display_post() function, 762display_preview_button() function, 733display_registration_form() function, 577display_tree() function, 752-753display_user_menu() function, 585display_user_urls() function, 599displaying articles (Web forum application),

752-753Distributed Denial of Service (DDoS), 346division operator, 33DML (Data Manipulation Languages), 244DMZs (demilitarized zones), 366

configuring, 386-387dns_get_mx() function, 459do..while loops, 55-56do_html_header() function, 632, 672, 700Document Type Definition. See DTDdocumentation

gd,Web site, 508Web application projects, 544-545

documentsheaders, 779, 804personalized, 771RTF, 784-787

certification project, 779-781,788-796, 802-804

creating, 771-772extensions, 805formats, 772requirements, 776-777

DOM (Document Object Model), 857web resources, 884

DoS (Denial of Service), 346-347, 364preparing for, 387

double data type (variables), 29doubleval() function, 296downloading

files from FTP servers, 465-466FreeType library, 484jpeg-6b, 484

923downloading

PostScript Type 1 fonts, 484t1lib, 484

draw_star() function, 804drawing

figures, 499-507functions, 488images, scripts, 486text, 487-489

DROP DATABASE statement, 264DROP privilege, 226DROP TABLE statement, 264dropping

databases, 264tables, 264

DTD (Document Type Definition), 810dump variables.php file, 559dynamic content, 21

date() function, 21-22functions, 22

Ee-commerce Web sites, 327, 336

adding value to goods or services, 335authentication, 343cutting costs, 335-336online brochures, 328

common pitfalls, 330limitations, 328-331

orders for goods or services, 331-334privacy policies, 333providing services and digital goods,

334-335return policies, 333risks, 336

competition, 338crackers, 337failure to attract business, 337-338hardware failure, 337legislation and taxes, 339service provider failures, 338software errors, 338system capacity limits, 339

security, 342auditing, 357authentication, 350-351backing up data, 358

Certificate Signing Request (CSR),356-357

Certifying Authorities (CAs), 355compromises, 349digital certificates, 355digital signatures, 354-355encryption, 351-354firewalls, 357-358hash function, 354importance of stored information, 342log files, 357passwords, 350-351physical security, 359Secure Web servers, 356-357security policies, creating, 349-350threats, 342-348

SSL (Secure Sockets Layer), 333strategies, selecting, 339types, 327-328

each() function, 85, 87, 102echo statements, 26-27edit_book.php files (Shopping Cart applica-

tion), 612edit_book_form.php files (Shopping Cart

application), 612, 646edit_category.php files (Shopping Cart applica-

tion), 611edit_category_form.php files (Shopping Cart

application), 611elements, 82

applying functions, 103-104counting, 104root elements (XML), 811

else statements, 47elseif statements, 48-49email

accountscreating, 668-669deleting, 670modifying, 670selecting, 671, 673setting up, 666-668

attachments, 689encryption, 419-420

GPG (Gnu Privacy Guard),419-427

PGP (Pretty Good Privacy), 419

924 downloading

reading, 452sending, 452Warm Mail application

database, 655-656deleting email, 681-682email, 681-682extensions, 686files, 654-655forwarding/replying, 684-685IMAP function library, 652-653interface, 654logging in, 663-666logging out, 666reading mail, 671-681script architecture, 657, 662-663sending, 682-685solutions, 652-654

embedding PHP in HTML, 17-18comments, 20-21PHP

statements, 19-20tags, 18-19

whitespace, 20empty() function, 45encryption, 351-352, 419-420

algorithm, 351ciphertext, 351cryptography, 352data, 418Data Encryption Standard (DES), 353decryption, 352digital certificates, 355digital signatures, 354-355GPG (Gnu Privacy Guard), 419

installing, 420-422key pairs, 420-421testing, 422-427

hash functions, 354passwords, 295, 397-399PGP (Pretty Good Privacy), 419plain text, 351private keys, 353public keys, 353-354RSA, 353

end() function, 102engineering software, 536

entities (HTML), 372entity relationship diagrams, 210ENUM type, 241envelopes, SOAP, 812environments

development, 544PHP functions, 450

EPA Web site, 359equal sign (=) assignment operator, 25equality operator, 87equals operator, 37equi-joins, 251, 255Equifax Secure, 355ereg() function, 129-130eregi() function, 129ereg_replace() function, 130eregi_replace() function, 130errors

401 errors (HTTP), 404exception handling, 565-567exit statement, 56function calling, 66handling, 202logic, 558-559messages, 145-146PHP 5.3, 7programming, 551-554

logic errors, 558-559runtime errors, 553-555syntax errors, 552-553

reporting levels, 562-563runtime, 553-554

database interaction, 555-557functions that don’t exist, 554-555input data, checking, 558network connections, 557-558reading/writing files, 555

settings, 563-564software, 338, 347

developer assumptions, 347poor specifications, 347poor testing, 348

suppression operator, 39syntax, 552-553triggering, 564

escapeshellcmd() function, 378, 417, 449escaping characters, 114

925escaping characters

escaping output, 371eval() function, 525-526evaluating strings, 525-526Evil Walrus Web site, 909examining php.ini file, 380Exception class, 195-196

extending, 196-197methods, 195

exceptions, 193-195, 565-567Bob’s Auto Parts application, 199-202catch blocks, 194classes, 196Exception class, 195-197I/O (input/output) files, 199throwing, 193try blocks, 193tutorials, 203user-defined exceptions, 196-199

exec() function, 447executable content (stored data), 417execution

command line, 531directives, 57operator, 39-40quotes, 377-378

exithandlers, 321language constructs, 526statements, 56

expand_all() function, 751expanding threads (Web forum application),

748-751EXPLAIN statement, 299-303

column values, 303join types, 301-302

explode() function, 100-101, 116-117, 459expressions

regular, 123-124* symbol, 126+ symbol, 126branching, 127caret symbol (^), 126-127character sets, 124-125curly braces ({}), 126Perl, 123slash (\), 127

Smart Form Mail application,128-129

special characters, 127-128splitting strings, 130string anchoring, 126-127subexpressions, 126substrings

finding, 129-131extending

Exception class, 196-197syntax, 257

Extensible Markup Language. See XMLextensions

copying libpdf_file, 899loading, 528online newsletters, 740personalized documents, 805PHPBookmark application, 606require() statement, 136Shopping Cart application, 650Warm Mail application, 686Web forum application, 769

extract() function, 105-106extract_type parameter, 105

extract_type parameter, 105Extreme Programming Web site, 549

Ff file mode, 63FastTemplate Web site, 546fclose() function, 69, 440FDF Web site, 789fdf_create() function, 789fdf_set_file() function, 789fdf_set_value() function, 789Fedex Web site, 335feof() function, 73fetchRow() method, 284fgetc() function, 75fgetcsv() function, 73-74fgets() function, 73fgetss() function, 73fields

scope, 290tables, 209

figures, drawing, 499-507File Details view, 445

926 escaping output

FILE privilege, 226-227, 295File Transfer Protocol. See FTPfile() function, 74file_exists() function, 76fileatime() function, 445filedetails.php file, 444-445filegroup() function, 444, 446fileinfo extension, 7filemtime() function, 445filename extensions, require() statement,

136fileowner() function, 444, 446fileperms() function, 446files, 59-61, 443

backing up, 459-466browsedir.php, 439checking, 76closing, 69constants.php (Amazon), 823create_database.sql, 745creating, 447data, loading from, 311deleting, 76, 447design_button.html, 492-493dump variables.php, 559filedetails.php, 444-445formats, 68-69handle.php, 566htaccess files (Apache Web server),

402-406httpd.conf, 896-897I/O (input/output), 199index.html (certification application),

780-781index.php

MLM online newsletters, 694Tahuayo application, 820-826Warm Mail application, 657

libpdf_php, copying, 899limitations, 79loading arrays from, 98-101locking, 78-79log files, 357lookup.php, 453make_button.php, 493mirroring FTP functions, 459-466MLM, 690

modes, 61-62moving, 447multiple, uploading (online newslet-

ters), 727, 731navigating, 76-77new_post.php, 763newbooks.txt, 311opening, 61

file modes, 61-62fopen() function, 62-64FTP (File Transfer Protocol), 64-65HTTP (Hypertext Transfer

Protocol), 64-65potential problems, 65-66

paths, directories, 442-443pdflib.php, 796personalized documents, 779php.ini file

auto_append_file, 142-143auto_prepend_file, 142-143directives, editing, 529-530

PHPBookmark application, 572pollsetup.sql, 500progex.php, 448-449properties, changing, 446reading, 61, 71-72, 444-446

feof() function, 73fgetc() function, 75fgetcsv() function, 73-74fgets() function, 73fgetss() function, 73file() function, 74fopen() function, 72fpassthru() function, 74fread() function, 75readfile() function, 74

reading/writing, 555rtf.php, 786score.php (certification project),

782-784Shopping Cart application, 611-612showpoll.php, 502-506simplegraph.php, 486status function results, 448-449Tahuayo application, 819-820

927files

topbar.php, 825uploading, 431-432

displaying, 437FTP (File Transfer Protocol), 466HTML, 431-433online newsletters, 688-689PHP, writing, 434-438security, 434, 438troubleshooting, 438-439

utilityfunctions.php, 825vote.html, 500Warm Mail application (email client),

654-655Web forum application, 744write permissions, 418writing, 61

file formats, 68-69fputs() function, 67fwrite() function, 67fwrite() function, parameters, 68

filesize() function, 76, 446filetype() function, 446filled_out() function, 580-581filtering

input data (Web databases), 272user input, 367-371

final keyword, 172find and replace substrings, 122-123finding substrings, 120-121

numerical position, 121regular expressions, 129-130strchr() function, 121stristr() function, 121strpos() function, 121strrchr() function, 121strrpos() function, 122strstr() function, 121

findstr.exe, 377firewalls, 357-358, 386FishCartSQL, 650fitting text onto buttons, 495-498flat files, 59-61

checking, 76closing, 69deleting, 76formats, 68-69

limitations, 79locking, 78-79navigating, 76-77opening, 61

file modes, 61-62fopen() function, 62-64FTP (File Transfer Protocol), 64-65HTTP (Hypertext Transfer

Protocol), 64-65potential problems, 65-66

reading, 61, 71-72feof() function, 73fgetc() function, 75fgetcsv() function, 73-74fgets() function, 73fgetss() function, 73file() function, 74fopen() function, 72fpassthru() function, 74fread() function, 75readfile() function, 74

writing, 61file formats, 68-69fputs() function, 67fwrite() function, 67fwrite() function, parameters, 68

Float data type (variables), 29floating point data types (numeric column

types), 237-238flock() function, 78floor() function, 478focus groups, 330-331fonts

button text, 492descenders, 497FreeType library, downloading, 484images, creating, 491-499PDF readers, 794-795PostScript Type 1 fonts, downloading,

484TrueType, 492

footers, script architecture, 694fopen() function, 61-64, 72, 440, 454for loops, 54-55foreach loops, 54-55

iteration, 191

928 files

foreign keysdatabases, 210InnoDB tables, 315-316

forgot_form.php files (PHPBookmark appli-cation), 572

forgot_passwd.php files (PHPBookmarkapplication), 572

formatscodes, date() function, 469-471images, 484

GIF (Graphics InterchangeFormat), 485

JPEG (Joint Photographic ExpertsGroup), 485

PNG (Portable NetworkGraphics), 485

WBMP (Wireless Bitmap), 485personalized documents, 772

ASCII, 772HTML, 773paper, 772PDF, 775PostScript, 774-775RTF, 774word processors, 773

strings, 110case, changing, 113-114conversion specifications, 112-113HTML formatting, 110-111ltrim() function, 110nl2br() function, 110-111printing, 110, 112-113rtrim() function, 110storage, 114-116trim() function, 110trimming whitespace, 110

formsHTML, 268-269, 431

Bob’s Auto Parts application, 14, 17creating, 14-16processing, 16

totaling with operators, 41-42variables, accessing, 23-27

forum application. See Web forum applica-tion

forwarding to email, Warm Mail application,684-685

fpassthru() function, 74FPDF function library, 778fputs() function, 67fread() function, 75FreeType library, downloading, 484fseek() function, 77ftell() function, 76FTP (File Transfer Protocol), 459

anonymous login, 462backing up files, 459-463

checking update times, 464-465closing connections, 466downloads, 465-466logins, 463remote connections, 463

FTP transfer modes, 466ftp_get() function, 466ftp_mdtm() function, 464ftp_nlist() function, 467ftp_size() function, 467mirroring files, 459-463

checking update times, 464-465closing connections, 466downloads, 465-466logins, 463remote connections, 463

opening files, 64-65set_time_limit() function, 467timeouts, avoiding, 467uploading files, 466

ftp_connect() function, 463ftp_get() function, 466ftp_mdtm() function, 464ftp_nlist() function, 467ftp_size() function, 467full joins, 250, 254functions, 143-144, 151, 158. See also com-

mands$result->fetch_assoc(), 275add_bm(), 597-598add_quoting(), 766addslashes(), 114, 272, 296, 417addToCart(), 852aggregate, MySQL, 256applying to array elements, 103-104arguments, 22

929functions

array_count_values(), 104array_push(), 713array_reverse(), 97-98array_walk(), 103-104arsort(), 93asort(), 93autoload(), 187AVG(column), 256backtrace, 196basename(), 442, 445browseNodeSearch(), 845cache(), 847-848cached(), 847-848calculate_items(), 630-631calculate_price(), 630-631calendars, 480-481calling, 22, 143

case sensitivity, 146errors, 66parameters, 143-144prototypes, 144undefined functions, 145-146

change_password(), 590, 720check_admin_user(), 700check_auth_user(), 665check_logged_in(), 700check_normal_user(), 700check_valid_user(), 585checkdate(), 370, 474chgrp(), 446chmod(), 446chown(), 446closedir($dir), 440copy(), 447cos(), 804count(), 104COUNT(items), 256creating, 146crypt(), 397-398current(), 102date(), 21-22, 445, 469-471

format codes, 469-471Unix timestamps, 471-472

DATE_FORMAT(), 476-477db_connect(), 583

db_result_to_array(), 619declaring, 146-147decoct(), 446delete bm(), 601delete_account(), 670delete_message(), 681-682directories, 439

creating, 443deleting, 443file paths, 442-443reading from, 439-441

dirname(), 442, 445disk_free_space($path), 443display() function, 758display_account_form(), 667, 703, 719display_account_select(), 672-673display_account_setup(), 667, 669display_book_form(), 647display_button(), 733display_cart(), 627-630display_categories(), 618-619display_information(), 713-714display_items(), 709display_list(), 674display_list_form(), 722display_mail_form(), 726display_message(), 678display_password_form(), 719display_post(), 762display_preview_button(), 733display_registration_form(), 577display_tree(), 752-753display_user_menu(), 585display_user_urls(), 599do_html_header(), 632, 672, 700doubleval(), 296drawing parameters, 488draw_star(), 804each(), 85-87, 102empty(), 45end(), 102ereg(), 129-130eregi(), 129ereg_replace(), 130eregi_replace(), 130

930 functions

escapeshellcmd(), 378, 417, 449eval(), 525-526exec(), 447expand_all(), 751explode(), 100-101, 116-117extract(), 105-106fclose(), 69, 440fdf_create(), 789fdf_set_file(), 789fdf_set_value(), 789feof(), 73fgetc(), 75fgetcsv(), 73-74fgets(), 73fgetss(), 73file(), 74file_exists(), 76fileatime(), 445filegroup(), 444, 446filemtime(), 445fileowner(), 444, 446fileperms(), 446files

creating, 447deleting, 447moving, 447properties, changing, 446reading, 444-446status results, 448-449

filesize(), 76, 446filetype(), 446filled_out(), 580-581flock(), 78floor(), 478fopen(), 61-64, 72, 440, 454fpassthru(), 74fputs(), 67fread(), 75fseek(), 77ftell(), 76FTP functions, 459-466

backing up files, 459-466ftp_get(), 466ftp_mdtm(), 464ftp_nlist(), 467

ftp_size(), 467mirroring files, 459-466set_time_limit(), 467timeouts, avoiding, 467uploading files, 466

ftp_connect(), 463fwrite(), 67-68get_accounts(), 668get_account_list(), 671get_archive(), 716get_categories(), 618get_category_name(), 621get_current_user(), 529get_email(), 707get_extension_funcs(), 528get_loaded_extensions(), 528get_magic_quotes_gpc() function, 272get_post(), 761-762get_post_title(), 765get_random_word(), 593get_unsubscribed_lists(), 712get_user_urls(), 585, 599getARS(), 828, 844-846getCategoryName(), 826-827getdate(), 473getenv(), 450getlastmod(), 529gettype(), 44Header(), 489-490, 787highlight_file(), 530-531htmlentities, 372-374htmlspecialchars(), 272, 372-374, 417ImageColorAllocate(), 488ImageCreate(), 487ImageCreateFromGIF(), 487, 495ImageCreateFromJPEG(), 487, 495ImageCreateFromPNG(), 487, 495ImageDestroy(), 490ImageFill(), 488ImageFilledRectangle(), 505-507ImageGetTTFBBox(), 496ImageJPEG(), 490ImageLine(), 505ImagePNG(), 490, 495ImageRectangle(), 507

931functions

images, 507ImageString(), 488ImageTTFBBox(), 497ImageTTFText(), 496, 507IMAP function library, 652-653imap_body(), 679-680imap_delete(), 682imap_expunge(), 682imap_fetchheader(), 679imap_header(), 679imap_headers(), 676, 679imap_open(), 675-676implode(), 117ini_get(), 529-530ini_set(), 529-530insert_order(), 636intval(), 101is_uploaded_file(), 438isset(), 45, 155join(), 117krsort(), 93ksort(), 93libraries, 542

FPDF, 778mail_fns.php, 668output_fns.php, 664PHPBookmark application, 572

list(), 85-87load_list_info(), 714login(), 585, 706lstat(), 446ltrim(), 110mail(), 109, 452, 595, 689max() function, 155-156MAX(column), 256microtime(), 480MIN(column), 256mkdir(), 443mktime(), 471-472my_error_handler (), 565mysql_affected_rows(), 280mysql_connect(), 274, 555mysql_query(), 274-275mysql_select_db(), 274mysqli_errno(), 556

mysqli_error(), 556mysqli_fetch_assoc(), 275mysqli_query(), 556naming, 147-148, 539network lookup, 455-459

dns_get_mx(), 459explode(), 459gethostbyaddr(), 458gethostbyname(), 456-458getmxrr(), 456parse_url(), 458

next(), 102nl2br(), 110-111notify_password(), 592-594number_of_accounts(), 671ODBC (Open Database connectivity),

282open_mailbox(), 675opendir(), 440overloading, 147parameters, 22, 148-150

pass by reference, 153-154pass by value, 153-154

passing functions by reference, 104passthru(), 448pdf_add_outline(), 794pdf_begin_page(), 793pdf_close(), 796pdf_fill(), 804pdf_rect(), 802pdf_replace(), 789pdf_setlinewidth(), 802pdf_set_info(), 793pdf_show(), 795pdf_show_xy(), 803pdf_stringwidth(), 803pdf_stroke(), 802PHP environment variables, 450phpinfo(), 450, 778posix_getgrgid(), 446posix_getpwuid(), 444-446pretty(), 714prev(), 102print(), 110printf(), 111-112

932 functions

prototypes, 144putenv(), 450range(), 83readdir($dir), 440readfile(), 74recommend_urls(), 603-605recursive functions, 156-158register(), 582rename(), 447reset_password(), 592reset(), 102retrieve_message(), 678returning from, 154-155rewind(), 76rewinddir($dir), 441rmdir(), 443rsort(), 93rtrim(), 110runtime errors, 554-555safeString(), 825scope, 151send(), 734send_message(), 683-684serialize(), 526-527, 848session_get_cookie_params(), 511session_register(), 513session_start(), 512-515session_unregister(), 513set_error_handler(), 565setcookie(), 510-511settype(), 44shal1(), 398shopping carts (Amazon), 849show_source(), 530-531showBrowseNode(), 826-827showCart(), 852showCategories(), 826ShowSmallCart(), 825showSummary(), 828, 844shuffle(), 96sin(), 804sizeof(), 104sort(), 92split(), 130sprintf(), 111

stat(), 446STD(column), 256STDDEV(column), 256store_account(), 704store_account_settings(), 668-669store_list(), 723store_new_post(), 767stored, declaring, 318-319str_replace(), 122, 787strcasecmp(), 119strchr(), 121strcmp(), 119strings

case, 113-114versus regular expressions, 131

strip_tags(), 417stripslashes(), 116, 272, 296stristr(), 121strlen(), 120strnatcmp(), 119strpos(), 121strrchr(), 121strrpos(), 122strstr(), 121, 597strtok() function, 117strtolower(), 113strtoupper(), 113subscribe(), 717substr(), 118-119substr_replace(), 123SUM(column), 256system(), 448touch(), 447trim(), 110, 271uasort(), 95ucfirst(), 113ucwords(), 114uksort(), 95umask(), 443undefined, calling, 145-146UNIX_TIMESTAMP(), 476-477unlink(), 76, 447unserialize(), 527, 848unset(), 45unsubscribe(), 717

933functions

urlencode(), 399, 455usort(), 94valid_email(), 581values, returning, 155-156variables, 44, 148

reinterpreting, 46scope, 151-153status, testing, 45type, setting/testing, 44-45

fwrite() function, 67-68

Ggd documentation Web site, 508generating images automatically, 490-491get_account_list() function, 671get_accounts() function, 668get_archive() function, 716get_categories() function, 618get_category_name() function, 621get_current_user() function, 529get_email() function, 707get_extension_funcs() function, 528get_loaded_extensions() function, 528get_magic_quotes_gpc() function, 272get_post() function, 761-762get_post_title() function, 765get_random_word() function, 593get_unsubscribed_lists() function, 712get_user_urls() function, 585, 599getARS() function, 828, 844, 846getCategoryName() function, 826-827getdate() function, 473getenv() function, 450gethostbyaddr() function, 458gethostbyname() function, 456-458getlastmod() function, 529getmxrr() function, 456getServerTime() function, 862-868gettype() function, 44Ghostscript Web site, 775GIF (Graphics Interchange Format), 485global privileges, 224global scope, 151global variables, 151GMT (Unix Epoch), 471Gnu Privacy Guard (GPG), 419

installing, 420-422key pairs, 420-421

testing, 422-427Web site, 419

goods (commercial Web sites)adding value to, 335digital goods, providing, 334-335taking orders for, 331-334

Google Web site, 811GPG (Gnu Privacy Guard), 419

installing, 420-422key pairs, 420-421testing, 422-427Web site, 419

GRANT command, 223-228GRANT privilege, 295GRANT statements, 287, 297grant tables, 288, 293Graphics Interchange Format (GIF), 485graphs

data, 499-507tutorials, 508

Gregorian calendar, 480-481GROUP BY clause, 256-257grouping data, 256-257

H-h switch (mysql command), 221hackers, 366handle.php file, 566handlers

continue, 320declare, 320exit, 321

handlingerrors, 202exceptions, 193-195, 565-567

Bob’s Auto Parts application,199-202

catch blocks, 194classes, creating, 196Exception class, 195-197I/O (input/output) files, 199throwing exceptions, 193try blocks, 193tutorials, 203user-defined exceptions, 196-199

handshaking, 414-415

934 functions

hardwarefailure (commercial Web sites), 337thieves, 366

hash() function, 354PHP 5.3, functionality in, 7

HAVING clause, 257header bar summaries, printing (Shopping

Cart application), 632Header() function, 489-490, 787headers

generating certificates, 804message headers (Warm Mail applica-

tion), 680-681script architecture, 694

HEAP tables, 312Hello World scripts, PDFlib, 792-796heredoc syntax, 27highlight_file() function, 530-531highlighting syntax, 530-531host table, 288, 290-291hosting services, 382-383HotScripts.com Web site, 908htaccess files (Apache Web server), 402-406HTML (Hypertext Markup Language), 773

embedding PHP, 17-18comments, 20-21statements, 19-20tags, 18-19whitespace, 20

entities, 372file upload, 433formatting (strings), 110-111forms

file upload, 431order, creating, 14-16processing, 14, 17

htmlentities() function, 372-374htmlspecialchars() function, 272, 372-374,

417htpasswd program (Apache Web server), 405HTTP (Hypertext Transfer Protocol), 414, 856

authentication Web sites, 408basic authentication, 399-400

401 errors, 404with Apache .htaccess files,

402-406in PHP, 400-402

digest authentication, 400handshaking, 414-415opening files, 64-65requests, 856-857Secure Sockets Layer (SSL), 414XML Amazon connections, 808

httpd.conf, 896-897HTTPResponse() function, 866Hypertext Markup Language. See HTMLHypertext Transfer Protocol. See HTTP

II/O (input/output) files, exception handling,

199IDE (Integrated Development Environment),

544identifiers, 28

images, destroying, 490MySQL identifiers, 235-236results identifiers, 275-276

identity operator, 87if statements, 46-47ImageColorAllocate() function, 488ImageCreate() function, 487ImageCreateFromGIF() function, 487, 495ImageCreateFromJPEG() function, 487, 495ImageCreateFromPNG() function, 487, 495ImageDestroy() function, 490ImageFill() function, 488ImageFilledRectangle() function, 505, 507ImageGetTTFBBox() function, 496ImageJPEG() function, 490ImageLine() function, 505ImageMagick library, 483ImagePNG() function, 490, 495ImageRectangle() function, 507images

canvas, creating, 487colors, RGB (red, green, and blue),

488creating, 486-487

fonts, 491-495text, 491-495, 499

data, graphing, 499-507drawing scripts, 486figures, drawing, 499-507

935images

formats, 484GIF (Graphics Interchange

Format), 485JPEG (Joint Photographic Experts

Group), 485PNG (Portable Network

Graphics), 485WBMP (Wireless Bitmap), 485

functions, 507generating automatically, 490-491identifiers, destroying, 490inline, dynamically produced, 491outputting, 489-490supporting PHP, 484text

drawing/printing, 487-489fitting onto buttons, 495-498positioning, 498-499writing onto buttons, 499

ImageString() function, 488ImageTTFBBox() function, 497ImageTTFText() function, 496, 507IMAP (Internet Message Access Protocol),

452, 651-652client Web site, 891function library, 652-653

imap_body() function, 679-680imap_delete() function, 682imap_expunge() function, 682imap_fetchheader() function, 679imap_header() function, 679imap_headers() function, 676, 679imap_open() function, 675-676implementing

inheritance, 167-168login (online newsletters), 702PHPBookmark database, 573-577recommendations, 602-605

implode() function, 117importing public keys (Gnu Privacy Guard),

422include() statement, 134

auto_append_file (php.ini file),142-143

auto_prepend_file (php.ini file),142-143

include_fns.php filesMLM application, 691Warm Mail application, 655Web forum application, 744

increment operators, 35-36indenting code, 47, 540-541INDEX privilege, 225index.html files (certification application),

779-781index.php file

MLM application, 691MLM online newsletters, 694Shopping Cart application, 611Tahuayo application, 819-826Warm Mail application, 655-657Web forum application, 744

index.php script (Shopping Cart application),615-620

indexesarrays, 304creating (MySQL), 234-235database optimization, 305queries, 304

inequality operator, 87inheritance, 162

implementing, 167-168multiple inheritance, 172-174preventing, 172

ini_get() function, 529-530ini_set() function, 529-530initializing

associative arrays, 85numerically indexed arrays, 82-83

inline images, dynamically produced, 491inner join, 254InnoDB tables

foreign keys, 315-316transactions, 314-315

input datachecking, 271, 558filtering, 272validating, 580

input/output (I/O) files, exception handling,199

insert book.php script, prepared statements,280

INSERT privilege, 225INSERT queries, 276-280

936 images

INSERT statement, 244insert_book.php files (Shopping Cart applica-

tion), 611insert_book.php script, 278-279insert_book.php script (Shopping Cart applica-

tion), 644-645insert_book_form.php files (Shopping Cart

application), 611insert_book_form.php script (Shopping Cart

application), 644insert_category.php files (Shopping Cart appli-

cation), 611insert_category_form.php files (Shopping Cart

application), 611insert_order() function, 636insertion anomalies, avoiding (Web databas-

es), 213install program (Apache), 902installation

Apache,Windows, 902binary installations, 890-893GPG (Gnu Privacy Guard), 420-422MIME mail package, 905mod_auth_mysql module, 406-407MySQL, 900-901PEAR (PHP Extension and Application

Repository), 905-906PHP, 14, 894, 903-905project codes,Amazon, 853-854source installations, 891-896

instanceof type operator, 40instances, SOAP (Simple Object Access

Protocol), 845instantiating classes, 164integer data types

numeric column types, 237variables, 29

Integrated Development Environment (IDE), 544interfaces

administration interface (Shopping Cartapplication), 643-650

administrator, Shopping Cart applica-tion, 609

PHP database interfaces, 282Warm Mail application (email client), 654Web Services (Amazon), 813-814

internationalization (applications), 7Internet Message Access Protocol (IMAP),

452, 651-652

Internet Protocol (IP), 414Internet, secure transactions, 411-412intl extension, 7intval() function, 101IP (Internet Protocol), 414is_uploaded_file() function, 438isset() function, 45, 155iteration. See loops

JJavaScript

add_BM() function, 881addBMResponse() function, 874addNewBookmark() function, 873libraries for Ajax applications, 884XMLHTTPRequest, 860, 862

JD (Julian Day) Count calendar, 480-481join() function, 117joins, 254-255

Cartesian product, 254conditions,WHERE clause, 250cross, 254equi-joins, 251, 255EXPLAIN statement, 301-302full, 250, 254inner, 254left, 252-255strings

implode() function, 117join() function, 117

tables, 251-252two-table, 250-251types, MySQL, 254-255

JPEG (Joint Photographic Experts Group),485, 778, 891

jpeg-6b, downloading, 484Julian calendar, 480-481

Kkeys

arrays, 82, 473databases

creating, 215foreign keys, 210primary keys, 210

937keys

pairs, installing, 420-421private keys, 420public keys, 420-422

keywordsAUTO_INCREMENT, 231DESC, 255LIKE, 249NOT NULL, 231PRIMARY KEY, 231REGEXP, 249return, 154-155UNSIGNED, 231

krsort() function, 93ksort() function, 93

Llanguages

constructsarray(), 82die(), 526exit, 526

DDL (Data Definition Languages),244

DML (Data Manipulation Language),244

late static bindings, 185-186leaf nodes (Web forum tree structure), 743left joins, 252-255length of strings, testing, 120letters, descenders, 497libpdf_php file, copying, 899libraries. See also functions, libraries

FreeType, downloading, 484function, 542, 572ImageMagick, 483mysqli prepared statements, 280-281PDFlib

certificates, 796, 802-804PDF documents, 792-796

PECL (PHP Extension Class Library),483

PHP, 891database interfaces, 282SOAP libraries (Amazon), 814

SOAP, 812

LIKE keyword, 249LIMIT clause, SELECT statement, 258links

Add to Cart, 817Checkout, 818Details, 817Web forum tree structure, 742

list() function, 85, 87lists

creating (online newsletters), 722-724databases, 688viewing (online newsletters), 708-716

literals, 27special characters (regular expressions),

127LOAD_DATA_INFILE statement, 311load_list_info() function, 714loading

arrays from files, 98-101data from files, 311extensions, 528

local variables, 151stored procedures, 319

LOCK TABLES command, 226, 305locking files, 78-79logging in

log files, 357MySQL, 221-222online newsletters, 705-707user authentication, 584-587Warm Mail application (email client),

663-666logging out

MySQL, 229online newsletters, 721user authentication, 587-588Warm Mail application (email client),

666logic, 546

errors, 558-559separating from content, 546

logical operators, 38login

anonymous login (FTP), 462FTP servers, 463implementing (online newsletters), 702

login() function, 585, 706

938 keys

login.php filesPHPBookmark application, 572-577Shopping Cart application, 611

logout.php filesPHPBookmark application, 572Shopping Cart application, 611

logout.php script (authentication), 523-524long style form variable, 24-26lookup functions

dns_get_mx(), 459explode(), 459networks, 455-459

gethostbyaddr(), 458gethostbyname(), 456-458getmxrr(), 456parse_url(), 458

lookup.php file, 453loops, 51-53

accessing numerically indexed arrays,84

associative arrays, 85-87break statement, 56do..while loops, 55-56for loops, 54-55foreach loops, 54-55iteration, 188-191while loops, 53-54

lstat() function, 446ltrim() function, 110

Mmagic quotes, 115magic_quotes_gpc directive, 417magic_quotes_runtime directive, 417Mail Exchange (MX) records, 459mail() function, 109, 452, 595, 689mail_fns.php files (Warm Mail application),

655mail_fns.php function library, get_accounts()

function, 668mailbox (Warm Mail application), viewing

contents of, 674-676mailing list manager. See MLMmain page (Shopping Cart application),

615-620

maintainability of code, 538breaking up, 541-542code standards, 538commenting, 540directory structures, 542function libraries, 542indenting, 540-541naming conventions, 538-540

make_button.php file, 492-493malicious code injection, 365many-to-many relationships (databases),

211master servers, database replication,

306-307matching

regular expressions, 123-124* symbol, 126+ symbol, 126branching, 127caret symbol (^), 126-127character classes, 125character sets, 124-125curly braces ({}), 126finding substrings, 129-130literal special characters, 127replacing substrings, 130slash (\), 127special characters, 127-128splitting strings, 130string anchoring, 126-127subexpressions, 126Web references, 131

substrings, 120-121find and replace, 122-123numerical position, 121regular expressions, 129-130strchr() function, 121stristr() function, 121strpos() function, 121strrchr() function, 121strrpos() function, 122strstr() function, 121

max() function, 155-156MAX(column) function, 256max_connections parameter, 273MaxClients parameter (Apache), 273

939MaxClients parameter (Apache)

md5(), PHP 5.3, functionality in, 7medium style form variable, 24member.php files (PHPBookmark applica-

tion), 572members_only.php script (authentication),

522-523MEMORY tables, 312MERGE tables, 312messages. See also errors, messages

sending, 733, 737-739viewing, 680-681

methods. See also functionsASINSearch(), 829bind_param(), 281browseNodeSearch(), 829, 835_call(), 186-187Exception class, 195fetchRow(), 284overloading, 186-187parseXML(), 838static, 184

microseconds, measuring, 480Microsoft

IIS, configuring, 381Web site, 773Word, RTF, 774

microtime() function, 480MIME mail package, installing, 905MIN(column) function, 256mirroring

FTP functions, 459-463checking update times, 464-465closing connections, 466downloads, 465-466logins, 463remote connections, 463

RAID (Redundant Array ofInexpensive Disks), 358

mktime() function, 471-472MLM (mailing list manager), 687

actions, 701building, 687files, 690online newsletters, 687

account settings, 702-705, 719administrative functions, 721databases, 688, 692-694

diagrams, 689-691email attachments, 689extensions, 740file upload, 688-689lists, 708-717, 722-724logging in, 705-707logging out, 721login, implementing, 702passwords, 719-721previewing, 732-733requirements, 688script architecture, 694, 700-701sending messages, 733, 737-739solution overview, 689-691subscribing, 717-718unsubscribing, 717-718uploading, 724-731

mlm_fns.php files (MLM application), 691mod_auth module (Apache Web server),

402mod_auth_mysql module, 406-408

documentation Web sites, 408installing, 406-407testing, 407

mode variable, 824modeling real-world objects (Web databas-

es), 211-212modes

autocommit, 314file modes, 61-62

modificationanomalies, avoiding (Web databases),

213dates (scripts), 529

modulescode, 539, 610mod_auth (Apache Web server), 402mod_auth_mysql, 406-408

installing, 406-407testing, 407

operator, 33PHP, running, 890

monitorsMySQL, 220-221security, 363

moving files, 447

940 md5(), PHP 5.3, functionality in

multidimensional arrays, 81-92sorting, 93

reverse sorts, 95user-defined sorts, 93-95

three-dimensional arrays, 90-92two-dimensional arrays, 88-90

multiline comments, 21multiple files, 727, 731multiple inheritance, 172-174multiple programmers, 543multiplication operator, 33MX (Mail Exchange) records, 459my_error_handler() function, 565MyISAM table, 312myisamchk utility, 303, 306MySQL

access, 219-220aggregate functions, 256continuation symbol, 220database, 287, 292

backing up, 358connection verification, 293creating, 222db table, 290-291host table, 291request verification, 293results.php script, 269selecting, 229tables, creating, 229-231tables_priv table, 292user table, 289viewing, 233-234Web database architecture, 268-271

date and timeconverting between PHP and

MySQL formats, 476-477date calculations, 478, 480DATE_FORMAT() function,

476-477MySQL Web site, 481UNIX_TIMESTAMP() function,

476-477GRANT command, 223-228identifiers, 235-236

installationbinary installations, 890-893source installations, 891Windows, 900Windows, setting PATH, 900-901

join types, 254-255logging in, 221-222logging out, 229max_connections parameter, 273mod_auth_mysql module, 406-408

documentation Web sites, 408installing, 406-407testing, 407

mysql command, 221online manual, 241passwords, 418privileges, 223

global privileges, 224GRANT command, 223-228principle of least privilege, 223REVOKE command, 227-228types, 225-227

resources, 909REVOKE command, 227-228runtime errors, 555-557semicolon (;), 220statements, 221syntax, 257users

GRANT command, 224-228REVOKE command, 227-228setting up, 223, 227-229

Web site, 220mysql command, 221mysql_affected_rows() function, 280mysql_dump command, 305mysql_query() function, 274-275mysql_select_db() function, 274mysqladmin facility, 235mysqlhotcopy script, 306mysqli_connect() function, 274, 555mysqli_errno() function, 556mysqli_error() function, 556mysqli_fetch_assoc() function, 275mysqli_query() function, 556

941mysqli_query() function

Nnamespaces, 158

PHP 5.3, 7XML, 811

namingconventions, 538-540functions, 147-148

Natural Order String Comparison Web site,119

navigatingwithin arrays, 102files, 76-77

Netcraft, 382Netscape Web site

cookie specification, 511SSL 3.0 Specification, 427

Network News Transfer Protocol (NNTP), 452networks

connecting, 557-558lookup functions, 455-459

dns_get_mx(), 459explode(), 459gethostbyaddr(), 458gethostbyname(), 456-458getmxrr(), 456parse_url(), 458

TCP/IP security, 343new operator, 39New York Times Web site, 392new_post.php files, 763

Web forum application, 744newbooks.txt file, 311newline control sequence (\n), 68newsletters, 687

accountsconfiguring, 719creating, 702-705

administrative functions, 721databases

configuring, 692-694lists/subscribers, 688

diagrams, 689-691email attachments, 689

extensions, 740file upload, 688-689lists

archives, viewing, 716-717creating, 722-724viewing, 708-716

logging in, 705-707logging out, 721login, implementing, 702passwords, 719-721previewing, 732-733requirements, 688script architecture, 694, 700-701sending messages, 733, 737-739solution overview, 689-691subscribing, 717-718unsubscribing, 717-718uploading, 724-731

next() function, 102nl2br() function, 110-111NNTP (Network News Transfer Protocol), 452nodes

browse nodes (Amazon), 816Web forum tree structure, 742

child nodes, 743leaf nodes, 743parent nodes, 743root nodes, 743

non-identity operator, 87NOT NULL keyword, 231notify_password() function, 592-594NULL data type (variables), 29null values, avoiding (Web databases), 216number_of_accounts() function, 671numeric column types, 236-238

date and time, 238-239floating point data types, 237-238integral data types, 237string, 239-241

numerical position of substrings, finding,121

numerically indexed arraysaccessing with loops, 84contents, accessing, 83-84initializing, 82-83

942 namespaces

OObject data type (variables), 29objects, 160-161

cloning, 186real-world modeling (Web databases),

211-212throwing, 196

ODBC (Open Database Connectivity) func-tions, 282

one-to-many relationships (databases), 211one-to-one relationships (databases), 211,

216online brochures (commercial Web sites),

328common pitfalls, 330limitations, 328

answering feedback, 329lack of information, 328poor presentation, 329tracking success, 330-331updated information, 329

online catalogs (Shopping Cart application),608

online newsletters, 687accounts

configuring, 719creating, 702-705

administrative functions, 721databases

configuring, 692-694lists/subscribers, 688

diagrams, 689-691email attachments, 689extensions, 740file upload, 688-689lists

archives, viewing, 716-717creating, 722-724viewing, 708-716

logging in, 702, 705-707logging out, 721passwords, 719-721previewing, 732-733requirements, 688script architecture, 694, 700-701sending messages, 733, 737-739

solution overview, 689-691subscribing, 717-718unsubscribing, 717-718uploading, 724-727, 731

OOP (object-oriented programming)classes, 160-161objects, 160-161polymorphism, 161

Open Database Connectivity (ODBC) func-tions, 282

open_mailbox() function, 675opendir() function, 440opening files, 61

file modes, 61-62fopen() function, 62-64FTP (File Transfer Protocol), 64-65HTTP (Hypertext Transfer Protocol),

64-65potential problems, 65-66tags (XML), 810

OpenSSLconfiguring, 894Web site, 891

operating systemsdatabase security, 294unnecessary applications, disabling, 388updating, 387-388

operationscreating, 162-164overriding, 173

operators, 32arithmetic operators, 33-34arrays, 40, 87-88assignment (=), 25, 28, 34

combination assignment operators,35

decrement operators, 35-36increment operators, 35-36reference operator, 36returning values, 34-35

associativity, 42-44bitwise operators, 38comma operator, 39comparison operators, 36-37

equals operator, 37WHERE clauses, 248-249

943operators

error suppression operator, 39execution operator, 39-40logical operators, 38new operator, 39precedence, 42-44strings

concatenation operator, 26-27operators, 34

subqueries, 259ternary operator, 39totaling forms, 41-42type operator, 40unary operators, 33

optimizingcode, 546-547databases, 304-305

default values, 305designs, 304indexes, 305permissions, 304tables, 304

Zend Optimizer, 547or operator, 38ORDER BY clause, 255order forms

creating, 14-16processing, 16

order.fns.php files (Shopping Cart applica-tion), 612

ordered data, retrieving, 255-256ordering strings

strcasecmp() function, 119strcmp() function, 119strnatcmp() function, 119

orders for goods or services (commercialWeb sites), 331-332

compatibility, 334trust, 333unanswered questions, 332user interfaces, 333-334

organizing code, 374output_fns.php files

MLM application, 691PHPBookmark application, 572Shopping Cart application, 612

Warm Mail application, 655Web forum application, 744

output_fns.php function library, 664outputting images, 489-490overloading

functions, 147methods, 186-187

overriding, 170-173owners (scripts), identifying, 529

P-p switch (mysql command), 221padding characters, 112pages. See Web pagesparameters, 22

$type, 829Apache, MaxClients, 273drawing functions, 488extract() function, 105function parameters, 148-150

calling functions, 143-144pass by reference, 153-154pass by value, 153-154

max_connections parameter, 273startup, 900

parent nodes (Web forum tree structure),743

parse_url() function, 458parseXML() method, 838parsing XML (Amazon), 814pass by value (function parameters),

153-154passing by reference, 104, 153-154passthru() function, 448passwords, 350-351, 362, 570

databasesaccess, 383-384security, 295

encrypting, 295, 397-399logging in to MySQL, 221-222MySQL, 418online newsletters, 719-721storing, 295, 395user authentication, 588-595

PATH settings, MySQL installations, 900-901

944 operators

pathsabsolute, 62file, 442-443relative, 62

paymentsmodules, 639-641systems, 608-609

PCRE extension, 7PDF (Portable Document Format), 771-775

generating certificates, 788-791headers, 804PDFlib, 792-804

personalized documents, 772readers, 794-795templates, creating, 776-777Web site, 775

pdf.php files (certification application), 779pdf_add_outline() function, 794pdf_begin_page() function, 793pdf_close() function, 796pdf_fill() function, 804pdf_rect() function, 802pdf_replace() function, 789pdf_set_info() function, 793pdf_setlinewidth() function, 802pdf_show() function, 795pdf_show_xy() function, 803pdf_stringwidth() function, 803pdf_stroke() function, 802PDFlib

certificates, 796, 802-804PDF documents, 792-796

pdflib.php files, 796certification application, 779

PEAR (PHP Extension and ApplicationRepository)

Databases, 284-285installing, 905-906Web site, 907

PECL (PHP Extension Class Library), 483Web site, 907

per-class constants, 184Perl regular expressions, 123permissions

database optimization, 304write files, 418

personalization, 771certification project, 779

files, 779index.html file, 780-781PDF, 788-791PDF, PDFlib, 792-796PDFlib, 796, 802-804RTF, 784-787score.php file, 782-784

creating, 771-772extensions, 805formats, 772

ASCII, 772HTML, 773paper, 772PDF, 775PostScript, 774-775RTF, 774word processors, 773

headers, 804requirements

questions/answers, 776software, 776-777

usersbookmarks, 571, 596-602defined, 569passwords, 570recommendations, implementing,

602-603, 605solutions, 570-572system requirements, 570usernames, 570

PGP (Pretty Good Privacy), 419phar extension, 7Philip and Alex’s Guide to Web Publishing

Web site, 910Phorum web forums project, 770PHP

advanced OO features, 184-186, 191Application Tools Web site, 909Base Library Web site, 908basic authentication (HTTP), 400-402calling functions, 22Center Web site, 908Classes Repository Web site, 908Club Web site, 908

945PHP

command line, 531configuring, 894constants, 31control structures, 46, 49

alternate syntax, 56breaking out of, 56conditionals, 46-51declare, 57loops, 51-56

database interfaces, 282date and time, 469, 474

calendar functions, 480-481checkdate() function, 474converting between PHP and

MySQL formats, 476-477date calculations, 477-478date() function, 469-472floor() function, 478getdate() function, 473microseconds, 480mktime() function, 471-472PHP Web site, 481

date() function, 21-22Developer Web site, 909Developer’s Network Unified Forums

Web site, 909development environments, 544embedding in HTML, 17-18

comments, 20-21statements, 19-20tags, 18-19whitespace, 20

environment variable functions, 450evaluating strings, 525-526extensions directory, copying

libpdf_files, 899functions

eval() function, 525-526get_current_user() function, 529get_extension_funcs(), 528get_loaded_extensions() function,

528getlastmod() function, 529highlight_file(), 530-531ini_get() function, 529-530

ini_set() function, 529-530my_error_handler() function, 565mysql connect() function, 555mysqli_errno() function, 556mysqli_error() function, 556mysqli_query() function, 556names in code, 539serialize() function, 526-527set_error_handler() function, 565show_source() functions, 530-531unserialize() function, 527variables, 44-46

gd documentation Web site, 508highlighting syntax, 530-531Homepage Web site, 908images

canvas, creating, 487creating, 486-499formats, 484generating automatically, 490-491GIF (Graphics Interchange

Format), 485identifiers, destroying, 490JPEG (Joint Photographic Experts

Group), 485outputting, 489-490PNG (Portable Network Graphics),

485supporting, 484text, 487-499WBMP (Wireless Bitmap), 485

installation, 14, 894binary installations, 890source installations, 891, 893-896Windows, 903-905

jpeg-6b, downloading, 484Kitchen Web site, 909language constructs

die(), 526exit, 526

libraries, 891Magazine Web site, 907modular names in code, 539network lookup functions, 455-459

dns_get_mx(), 459explode(), 459

946 PHP

gethostbyaddr(), 458gethostbyname(), 456-458getmxrr(), 456parse_url(), 458

online manual, 80operators, 32

arithmetic operators, 33-34array operator, 40assignment operators, 28-36associativity, 42-44bitwise operators, 38comma operator, 39comparison operators, 36-37error suppression operator, 39execution operator, 39-40logical operators, 38new operator, 39precedence, 42-44string operators, 34ternary operator, 39totaling forms, 41-42type operator, 40unary operators, 33

optimizations, 546-547PHP 5.3

bug fixes in, 7crypt() functionality in, 7date/time functions in, 7date_add() function, 478date_sub() function, 478error reporting in, 7fileinfo extension, 7hash() functionality in, 7intl extension, 7md5() functionality in, 7MySQLnd drivers, 7namespaces, 7new features of, 7PCRE extension, 7phar extension, 7php.ini administration in, 7Reflection extension, 7SPL extension, 7sqlite3 extension, 7time/date functions in, 7

Windows support for, 7, 900Zend engine improvements, 7

resources, 907-909Resource Web site, 908-909running

as CGI Interpreter, 890as modules, 890

scripts, 551debugging variables, 559, 561errors, 562-567modification dates, 529programming errors, 551-558MySQL passwords, 418owners, identifying, 529terminating execution, 526

serialization, 526-527sessions. See sessionsSOAP libraries (Amazon), 814statements, 19-20tags, 18-19

ASP style, 19require() statement, 136SCRIPT style, 19Short style, 19

variablesform variables, accessing, 23-27identifiers, 28names in code, 539scope, 31-32superglobal, 32types, 29-30user declared variables, 28values, assigning, 28

Web site, 481, 537, 891writing, 434-438XML style, 19

PHP Extension and Application Repository(PEAR)

installing, 905-906Web site, 907

PHP, Hypertext Preprocessor Web site, 106php.ini file

administration in PHP 5.3, 7auto_append_file, 142-143auto_prepend_file, 142-143

947php.ini file

directives, editing, 529-530examining, 380

phpautodoc Web site, 545PHPBookmark application

Ajax elements, adding, 871creating, 569

database schema, 573-574front page, 574-577function libraries, 572

extensions, 606files, 572project, 870-883

PHPBuilder.com Web site, 908PHPCertifcation.pdf files (certification appli-

cation), 779PHPCertification.rtf files (certification appli-

cation), 779PHPCommunity Web site, 907phpdoc Web site, 544PHPDocumentor Web site, 544PHPIndex.com Web site, 908phpinfo() command, 31phpinfo() function, 450, 778PHPMyAdmin.Net Web site, 908PHPWizard.net Web site, 908php|architect Web site, 907physical security, 359, 388plain text (encryption), 351plus symbols (+)

regular expressions, 126Web forum articles, 748

PNG (Portable Network Graphics), 485library Web site, 891

pollsetup.sql file, 500polymorphism, 161POP (Post Office Protocol), 452POP3 (Post Office Protocol version 3),

651-652populate.sql files (Shopping Cart applica-

tion), 612Portable Document Format. See PDFPortable Network Graphics. See PNGpositioning text buttons, 498-499POSIX regular expressions. See regular

expressionsposix_getgrgid() function, 446posix_getpwuid() function, 446posix_getpwuid() functions, 444

Post Office Protocol (POP), 452Post Office Protocol version 3 (POP3),

651-652post-decrement operator, 35-36post-increment operator, 35-36posters (Web forum application), 744Postnuke Web site, 909PostScript, 774-775

Downloading fonts, 484power failures, 359pre-decrement operator, 35-36pre-increment operator, 35-36precedence, operators, 42-44prepared statements, 280-281preparing for DoS/DDoS attacks, 387preprocessing script architecture, 694Pretty Good Privacy (PGP), 419pretty() function, 714prev() function, 102preventing

inheritance, 172overriding, 172

previewing online newsletters, 732-733PRIMARY KEY keyword, 231primary keys (databases), 209-210principle of least privilege, 223print() function, 110printf() function, 111-112printing

header bar summaries (Shopping Cartapplication), 632

strings, 110-113print() function, 110printf() function, 111-112sprintf() function, 111

text images, 487-489privacy policies

commercial Web sites, 333SSL (Secure Sockets Layer), 333

private access modifier, 166-167visibility, controlling, 169-170

private keysencryption, 353Gnu Privacy Guard (GPG), 420

privilegesFILE, 295GRANT, 295

948 php.ini file

MySQL, 223global privileges, 224GRANT command, 223-228principle of least privilege, 223REVOKE command, 227-228

PROCESS, 295types, 225-227system, 287-288

columns_priv table, 293db table, 290-291grant table, 293host table, 290-291privileges, updating, 293-294slaves, 307tables_priv table, 293

user table, 289-290updating, 293-294user database security, 295-296

PROCESS privilege, 226, 295process.php files (Shopping Cart applica-

tion), 611process.php script (Shopping Cart applica-

tion), 639processing HTML forms, 14, 17Product class, 839Product.php files (Tahuayo application), 819progex.php file, 448-449programming errors, 551, 553-554

logic errors, 558-559runtime errors, 553-554

database interaction, 555-557functions that don’t exist, 554-555input data, checking, 558network connections, 557-558reading/writing files, 555

syntax errors, 552-553programs. See also applications

install (Apache), 902running command line, 531

project codes, installing (Amazon), 853-854property files, changing, 446protocols, 451-452

application layer protocols, 414File Transfer Protocol (FTP), 459

anonymous login, 462backing up files, 459-465

ftp_get() function, 466ftp_mdtm() function, 464ftp_nlist() function, 467ftp_size() function, 467mirroring files, 459-465set_time_limit() function, 467timeouts, avoiding, 467uploading files, 466

FTP (File Transfer Protocol), 64-65HTTP (Hypertext Transfer Protocol),

414handshaking, 414-415opening files, 64-65Secure Sockets Layer (SSL), 414

IMAP (Internet Message AccessProtocol), 452, 651-652

IP (Internet Protocol), 414NNTP (Network News Transfer

Protocol), 452POP (Post Office Protocol), 452POP3 (Post Office Protocol version

3), 651-652RFCs (Requests for Comments),

451-452SMTP (Simple Mail Transfer

Protocol), 452, 652SOAP (Simple Object Access

Protocol), 845-846stacks, 413-414TCP (Transmission Control Protocol),

414Web Services

SOAP (Simple Object AccessProtocol), 811-812

WSDL (Web Services DescriptionLanguage), 812

prototypescode, 545-546functions, 144

public access modifier, 166-170public keys

encryption, 353-354Gnu Privacy Guard (GPG), 420-422

purchase.php files (Shopping Cart applica-tion), 611

purchase.php script (Shopping Cart applica-tion), 634, 639

949purchase.php script (Shopping Cart application)

putenv() function, 450PX-PHP Code Exchange Web site, 908

Qqueries

EXPLAIN statement, 299-303indexes, 304INSERT, 276-280subqueries, 258-259

correlated, 260operators, 259row, 260temporary tables, 260

Web databases, 271adding data, 276-280connections, setting up, 273disconnecting from databases, 276input data, 271-272mysql_query() function, 274-275prepared statements, 280-281retrieving results, 275-276selecting databases, 274

quotes, magic quotes, 115

Rr+ file mode, 63RAID (Redundant Array of Inexpensive

Disks), 358range() function, 83RDBMS (relational database management

systems), 80, 243readdir($dir) function, 440readers, PDF, 794-795readfile() function, 74reading

from directories, 439-441files, 61, 71-72, 444-446

feof() function, 73fgetc() function, 75fgetcsv() function, 73-74fgets() function, 73fgetss() function, 73file() function, 74fopen() function, 72fpassthru() function, 74

fread() function, 75readfile() function, 74

runtime errors, 555Warm Mail application, 671, 681

mailbox contents, viewing, 674-676messages, 677-678, 680-681selecting accounts, 671, 673

real-world objects, modeling (Web databas-es), 211-212

recommend.php files (PHPBookmark appli-cation), 572

recommend_urls() function, 603, 605recommendations

bookmarks, 571implementing, 602-603, 605

recordsdeleting, 264updating, 261tables, 209

recursive functions, 156-158red, green, and blue (RGB), 488Redundant Array of Inexpensive Disks

(RAID), 358redundant data, avoiding (Web databases),

212-213reference operator, 36reflection API, 190-191Reflection extension, 7REGEXP keyword, 249register() function, 582register_form.php files (PHPBookmark appli-

cation), 572register_new.php files (PHPBookmark appli-

cation), 572registering

session variables, 513user authentication, 577, 580-583

regression, 377regular expressions, 123-124

* symbol, 126+ symbol, 126branching, 127caret symbol (^), 126-127characters

classes, 125sets, 124-125

curly braces ({}), 126functions versus string functions, 131

950 putenv() function

Perl, 123slash (\), 127Smart Form Mail application, 128-129special characters, 127-128splitting strings, 130string anchoring, 126-127subexpressions, 126substrings

finding, 129-130replacing, 130

Web references, 131reinterpreting variables, 46relational database management systems.

See RDBMSrelational databases, 208, 210

benefits, 207keys, 209

foreign keys, 210primary keys, 210

relationships, 211many-to-many relationships, 211one-to-many relationships, 211one-to-one relationships, 211, 216

schemas, 210tables, 208

columns, 209rows, 209values, 209

relationships (databases), 211many-to-many relationships, 211one-to-many relationships, 211one-to-one relationships, 211, 216

relative paths, 62RELOAD privilege, 226remote FTP connections, 463rename() function, 447reordering arrays, 96

array_reverse() function, 97-98shuffle() function, 96

repetitive tasks. See loopsreplacing substrings, 122-123

with regular expressions, 130replication, databases, 306-307

data transfer, 306-308master servers, 306-307slaves, 306-308

REPLICATION CLIENT privilege, 226REPLICATION SLAVE privilege, 226replying to email, Warm Mail application,

684-685repository (version control, code), 542repudiation, 348-349requests

HTTP, 856-857MySQL database, 293server response, 866

Requests for Comments (RFCs), 451-452require() statement, 135-136

auto_append_file (php.ini file),142-143

auto_prepend_file (php.ini file),142-143

filename extensions, 136PHP tags, 136Web site templates, 137-142

reset password() function, 592reset() function, 102resetting passwords, user authentication,

593resources, 907

Apache, 909data types, 29MySQL and SQL, 909PHP, 907-909Web development, 910

responses (HTTP), 866REST/XML (Amazon), 838-839, 844restoring databases, 306restricting access

to .php files, 374-375to sensitive data, 364

result identifiers, retrieving query results(Web databases), 275-276

results.php script, 269retrieve_message() function, 678returning

assignment operator, 34-35from functions, 154-155keywords, 154-155policies, 333rows, 258statements, 154values, 94, 155-156

951returning

reusing codebenefits, 133-134

consistency, 134cost, 134reliability, 134

include() statement, 134, 142-143require() statement, 135-136, 142-143

auto_prepend_file (php.ini file),142-143

filename extensions, 136PHP tags, 136Web site templates, 137-142

reverse sort orderarrays, 93multidimensional arrays, 95

reverse spam, 346REVOKE command, 227-228rewind() function, 76rewinddir($dir) function, 441rewriting code, 537-538RFCs (Requests for Comments), 451-452

RFC Editor Web site, 451, 468RGB (red, green, and blue), 488Rich Text Format (RTF), 771, 774risks for commercial Web sites, 336

competition, 338crackers, 337failure to attract business, 337-338hardware failure, 337legislation and taxes, 339service provider failures, 338software errors, 338system capacity limits, 339

rmdir() function, 443rolled back transactions, 314root elements (XML), 811root nodes (Web forum tree structure), 743rows

returning, 258subqueries, 260unmatched, 252-253values, 209

RSA, 353rsort() function, 93RTF (Rich Text Format), 771, 774

generating certificates, 784-787templates, creating, 776

rtf.php files, 779, 786rtrim() function, 110running

Apache, 897command line programs, 531PHP

as CGI Interpreter, 890as modules, 890

runtime errors, 553-554database interaction, 555-557functions that don’t exist, 554-555input data, checking, 558network connections, 557-558reading/writing files, 555

SS-HTTP (Secure Hypertext Transfer Protocol),

412safeString() function, 825scalar variables, 81,

converting arrays to, 105-106schemas

Book-O-Rama application, 219, 230database (PHPBookmark application),

573-577scope

fields, 290function scope, 151global scope, 151variable scope, 31-32, 150-153

score.php files (certification project),779-784

screening user input, 417SCRIPT style (PHP tags), 19scripts

admin.php script (Shopping Cartapplication), 641, 643

architecturefooters, 694headers, 694online newsletters, 694-701performing actions, 694preprocessing, 694

authmain.php (authentication),517-522

breaking out of, 56

952 reusing code

buttons, calling, 493catalog scripts (Shopping Cart applica-

tion), 615-617index.php, 615-620show_book.php, 616, 622-623, 646show_cat.php, 615, 620-622

checkout.php script (Shopping Cartapplication), 633-638

edit_book_form.php (Shopping Cartapplication), 646

executing, 531Hello World, 792-796images, drawing, 486insert_book.php, 278-279, 644-645

prepared statements, 280insert_book_form.php script

(Shopping Cart application), 644logout.php (authentication), 523-524make_button.php, 492members_only.php (authentication),

522-523modification dates, 529mysqlhotcopy, database backup, 306owners, identifying, 529PHP, MySQL passwords, 418process.php script (Shopping Cart

application), 639purchase.php script (Shopping Cart

application), 634, 639querying Web databases, 271

adding data, 276-280connections, setting up, 273disconnecting from databases, 276input data, 271-272mysql_query() function, 274-275prepared statements, 280-281retrieving results, 275-276selecting databases, 274

results.php, 269servertime.php, 863-864show_book.php (Shopping Cart

application), 646show_cart.php script (Shopping Cart

application), 623-627adding items to cart, 630-631header bar summary, printing, 632

updated carts, saving, 631-632viewing contents of cart, 627-630

terminating execution, 526Warm Mail application (email client),

657, 662-663Web database architecture, 217

SearchDatabase.com Web site, 909searching substrings, 120-121

find and replace, 122-123numerical position, 121regular expressions, 129-130strchr() function, 121stristr() function, 121strpos() function, 121strrchr() function, 121strrpos() function, 122strstr() function, 121

Secure Hypertext Transfer Protocol (S-HTTP),412

Secure Socket Layer. See SSLsecure storage, 417-419secure transactions, 409-410

Internet, 411-412screening user input, 417Secure Sockets Layer (SSL), 413-415

compression, 416handshaking, 414-415protocol stacks, 413-414sending data, 415-416

secure storage, 417-419systems, 412-413user machines, 410-411Web browsers, 410-411

Secure Web servers, 355-357security, 362

authentication, 343, 401-406access control, implementing,

392-395basic authentication. See basic

authenticationcustom, creating, 408digest authentication, 400encrypting passwords, 397-399identifying users, 391-392mod_auth_mysql module, 406-408multiple pages, protecting, 399

953security

passwords, 350-351storing passwords, 395Web sites, 408

bottom-up approach, 363bugs, testing for, 376-377Certifying Authorities (CAs), 355code organization, 374commercial Web sites, 342

auditing, 357authentication, 350-351backing up data, 358Certificate Signing Request

(CSR), 356-357compromises, 349crackers, 337digital certificates, 355digital signatures, 354-355encryption, 351-354firewalls, 357-358hash function, 354importance of stored information,

342log files, 357passwords, 350-351physical security, 359Secure Web servers, 356-357security policies, creating, 349-350threats, 342-349

databases, 294, 384authentication, 383-384connecting to servers, 384-385operating system, 294passwords, 295servers, 385user privileges, 295-296Web issues, 296

denial of service, 364disaster recovery, 364, 388-389DMZ, 386-387DoS attacks, preparing for, 387effect on usability, 362encryption, 352-353, 419-420

Data Encryption Standard (DES),353

GPG (Gnu Privacy Guard),419-427

PGP (Pretty Good Privacy), 419files

system considerations, 375-376uploads, 434, 438

firewalls, 386hosting services, 382-383malicious code injection, 365monitoring, 363output, escaping, 371passwords, 362.php files, restricting access to,

374-375physical security, 388restricting access to sensitive data, 364Secure Socket Layer (SSL), 344SQL injection attacks, 371TCP/IP networks, 343top-down approach, 363transactions, 409-410

Internet, 411-412screening user input, 417Secure Sockets Layer (SSL),

413-416secure storage, 417-419systems, 412-413user machines, 410-411Web browsers, 410-411

user input, filtering, 367-371SELECT clauses, 257SELECT privileges, 225SELECT statements, 246

LIMIT clause, 258ORDER BY clause, 255

selectingdatabases in MySQL, 229Web databases, 274

selectors (CSS), 858semicolon (;), MySQL, 220, 274send() function, 734send_message() function, 683-684sending

email, 452messages, online newsletters, 733,

737-739

954 security

Warm Mail applicationforwarding/replying, 684-685new messages, 682-684

sensitive data, storing, 417-419serialization, 526-527

session variables, 514serialize() function, 526-527, 848server-side programming, 860servers

Apache. See Apache,Web serverauthentication, 351communication with Ajax, 863-864database servers,Web database archi-

tecture, 217master, database replication, 306-307response to HTTP requests, 866secure storage, 417-419Secure Web servers, 355-357Web servers,Web database architec-

ture, 216servertime.php script, 863-864services

adding, 335, 452-454providing, 334-335taking orders for, 331-334

session_get_cookie_params() function, 511session_register() function, 513session_start() function, 512, 514-515session_unregister() function, 513sessions, 509, 512

authentication, 517-524configuring, 516-517cookies, 510-511creating (Amazon), 823destroying, 513example session, 514-516IDs, 509-512Shopping Cart application, 608, 623starting, 512variables, 510

deregistering, 513implementing, 513registering, 513serializing, 514

set cardinality (arrays), 104

SET type, 241set_error_handler() function, 565set_time_limit() function, 467setcookie() function, 510-511setting up

Book-O-Rama, 243databases of lists, 688

settype() function, 44SGML (Standard Generalized Markup

Language), 808shal1() function, 398shell command executor, 377-378shell script-style comments, 20Shopping Cart application, 607, 617, 624,

643, 650administration

interfaces, 609views, 609-610

administration interface, 643-647, 650administration menu (admin.php),

641, 643edit_book_form.php script, 646insert_book.php script, 644-645insert_book_form.php script, 644show_book.php script, 646

book_sc database, 612-615catalog scripts, 615-617

index.php, 615-620show_book.php, 616, 622-623, 646show_cat.php, 615, 620-622

code modules, 610database, 615extensions, 650files, 611-612online catalogs, building, 608payments

modules, 639-641systems, 608-609

session variables, 608, 623shopping cart module

adding items, 630-631checkout.php script, 633-638header bar summary, printing, 632purchase.php script, 634, 639show_cart.php script, 623-627

955Shopping Cart application

updates, saving, 631-632viewing contents of, 627-630

solution overview, 609-612tracking user’s purchases, 608user view, 609-610

shopping carts, 607building (Amazon), 813, 849-852

Short style (PHP tags), 19short style form variable, 23-24SHOW COLUMNS statement, 297SHOW command, 233-234SHOW DATABASES privilege, 226SHOW statement, 296-297SHOW TABLES statement, 297show_book.php files (Shopping Cart applica-

tion), 611show_book.php script (Shopping Cart appli-

cation), 616, 622-623, 646show_cart.php files (Shopping Cart applica-

tion), 611show_cart.php script (Shopping Cart applica-

tion), 623, 625, 627adding items to cart, 630-631header bar summary, printing, 632updated carts, saving, 631-632viewing contents of cart, 627-630

show_cat.php files (Shopping Cart applica-tion), 611

show_cat.php script (Shopping Cart applica-tion), 615, 620-622

show_source() function, 530-531showBrowseNode() function, 826-827showCart() function, 852showCategories() function, 826showpoll.php file, 502-504, 506ShowSmallCart() function, 825showSummary() function, 828, 844shuffle() function, 96SHUTDOWN privilege, 226signature.png files (certification application),

779Simple Mail Transfer Protocol (SMTP), 452,

652Simple Object Access Protocol. See SOAPsimplegraph.php file, 486sin() function, 804

single-line comments, 21sites. See commercial Web sites; Web sitessizeof() function, 104slash (\), 311

regular expressions, 127Slashdot Web site, 392, 741slaves

database replication, 306-308replication, 307

Smart Form Mail applicationcreating, 107-109regular expressions, 128-129

SMTP (Simple Mail Transfer Protocol), 452,652

SOAP (Simple Object Access Protocol),808-812

Amazon, 807-808, 845-846envelopes, 812example, 811instances, 845libraries, 812PHP SOAP libraries (Amazon), 814

softwareengineering, 536errors, 338, 347

developer assumptions, 347poor specifications, 347poor testing, 348

personalized documents, 776PDF, 776-777RTF, 776

updating, 378-379solutions, user personalization, 570-572sort() function, 92sorting arrays, 92

asort() function, 93ksort() function, 93multidimensional, 93

reverse sorts, 95user-defined sorts, 93-95

reverse order, 93sort() function, 92

source installations, 891-896SourceForge Web site, 545, 909spam, 346

956 Shopping Cart application

special charactersliteral special characters (regular

expressions), 127regular expressions, 127-128

special privileges, 227specifications, CGI Web site, 450speed of queries, 304SPL extension, 7split() function, 130splitting strings

explode() function, 116-117regular expressions, 130strtok() function, 117substr() function, 118-119

sprintf() function, 111SQL (Structured Query Language), 243

ANSI standard Web site, 265Book-O-Rama database

setting up, 243tables, code to populate, 245

Course Web site, 909CREATE TABLE command, 229-231databases, 246-256

defined, 243-244dropping, 264joins, 254-255records, 261, 264rows, 252-253, 258subqueries, 258-260tables, 251-254, 261-263two-table joins, 250-251

DDL (Data Definition Languages),244

DML (Data Manipulation Language),244

MySQLaggregate functions, 256join types, 254-255

RDBMS (relational database manage-ment systems), 243

resources, 909strings, security, 371

sqlite3 extension, 7

SSL (Secure Sockets Layer), 344, 412-415,889

commercial Web sites, 333compression, 416handshaking, 414-415protocol stacks, 413-414sending data, 415-416testing, 899

stability, planning for, 376-377Standard Generalized Markup Language.

See SGMLstarting sessions, 512startup parameters, 900stat() function, 446statements

ALTER TABLE, 261-263break statement, 56continue statement, 56DELETE, 264DESCRIBE, 299describe user;, 289DROP DATABASE, 264DROP TABLE, 264echo statements, 26-27else statements, 47elseif statements, 48-49exit statement, 56EXPLAIN, 299-303

column values, 303join types, 301-302

GRANT, 287, 297if statements, 46-47include() statement, 134

auto_append_file (php.ini file),142-143

auto_prepend_file (php.ini file),142-143

INSERT, 244LOAD_DATA_INFILE, 311MySQL case-sensitivity, 221PHP statements, 19-20prepared, 280-281require() statement, 135-136

auto_append_file (php.ini file),142-143

957statements

auto_prepend_file (php.ini file),142-143

filename extensions, 136PHP tags, 136Web site templates, 137-140, 142

return statement, 154SELECT, 246

LIMIT clause, 258ORDER BY clause, 255

SHOW, 296-297SHOW COLUMNS, 297SHOW TABLES, 297switch statements, 49-51UPDATE, 261

static bindings, 185static methods, implementing, 184STD (column) function, 256STDDEV (column) function, 256storage engines, 312-313

InnoDB tablesforeign keys, 315-316transactions, 314-315

MEMORY tables, 312MERGE tables, 312MyISAM, 312

store_account() function, 704store_account_settings() function, 668-669store_list() function, 723store_new_post() function, 767store_new_post.php files (Web forum appli-

cation), 744stored functions, declaring, 318-319stored procedures, 316

control structures, 319-323cursors, 319-323declaring, 316-317local variables, 319stored functions, declaring, 318-319

storingbookmarks, 571data, 59. See also filespasswords, 295, 395redundant data (Web databases),

212-213secure storage, 417-419

session IDs, cookies, 511-512strings, 114-116

addslashes() function, 114stripslashes() function, 116

str_replace() function, 122, 787strategies, commercial Web sites, 339strcasecmp() function, 119strchr() function, 121strcmp() function, 119strings

anchoring, 126-127case functions, 113-114column types, 239-241comparing, 119

length of strings, testing, 120strcasecmp() function, 119strcmp() function, 119strnatcmp() function, 119

concatenation operator, 26-27data type (variables), 29evaluating, 525-526formatting, 110

case, changing, 113-114conversion specifications, 112-113HTML formatting, 110-111ltrim() function, 110nl2br() function, 110-111printing, 110-113rtrim() function, 110storage, 114-116trim() function, 110trimming whitespace, 110

functions versus regular expressionfunctions, 131

joiningimplode() function, 117join() function, 117

length, testing, 120operators, 34ordering

strcasecmp() function, 119strcmp() function, 119strnatcmp() function, 119

958 statements

printing, 110-113print() function, 110printf() function, 111-112sprintf() function, 111

securing, 371specifying, 27splitting

explode() function, 116-117regular expressions, 130strtok() function, 117substr() function, 118-119

substringsaccessing, substr() function,

118-119finding, 120-121, 129-130numerical position of, finding, 121replacing, 122-123, 130

tokens, 117strip_tags() function, 417stripslashes() function, 116, 272, 296stristr() function, 121strlen() function, 120strnatcmp() function, 119Stronghold Web site, 356strpos() function, 121strrchr() function, 121strrpos() function, 122strstr() function, 121, 597strtok() function, 117strtolower() function, 113strtoupper() function, 113Structured Query Language. See SQLstructures, directory, 542style sheets, CSS, 859subexpressions, 126subqueries, 258-259

correlated, 260operators, 259row, 260temporary tables, 260

subscribe() function, 717subscribers

databases, 688online newsletters, 717-718

substr() function, 118-119substr_replace() function, 123

substringsaccessing, 118-119finding, 120-121

numerical position, 121regular expressions, 129-130strchr() function, 121stristr() function, 121strpos() function, 121strrchr() function, 121strrpos() function, 122strstr() function, 121

replacing, 122-123, 130subtraction operator, 33SUM(column) function, 256Summary Web site, 330SUPER privilege, 226superglobal arrays, 24superglobal variables, 32switch statements, 49-51switches

-h switch (mysql command), 221-p switch (mysql command), 221-u switch (mysql command), 221

syntactic sugar, 537syntax, 552

ALTER TABLE statement, 262-263control structures, 56DESCRIBE statement, 299errors, 552-553extended, 257heredoc, 27highlighting, 530-531

system() function, 448systems

capacity limits (commercial Web sites),339

operating, 294secure transactions, 412-413user personalization, 570

Tt file mode, 63t1lib, downloading, 484tab control sequence (\t), 68

959tab control sequence (\t)

tablesaliases, 253-254altering, 261-263Book-O-Rama database, 245Cartesian product, 250columns, 209

atomic column values, 214-215DESCRIBE statement, 299types, 232-233

columns_priv, 288-293creating in MySQL, 229-231

indexes, creating, 234-235keywords, 231table types, 229viewing tables, 233-234

databasesbackup, 305optimization, 304

db, 288-291dropping, 264equi-joins, 251grant, 288, 293host, 288-291InnoDB

foreign keys, 315-316transactions, 314-315

joins, 250-255keys, 209

creating,Web databases, 215primary keys, 210

left joins, 252-253MEMORY, 312MERGE, 312MyISAM, 312rows, 209

returning, 258unmatched, 252-253values, 209

schemas, 210scope fields, 290tables_priv, 288-293temporary, 260two-table joins, 250-251user, 288-290

tables_priv table, 288-293

tagsclosing/opening (XML), 810PHP tags, 18-19

ASP style, 19require() statement, 136SCRIPT style, 19Short style, 19XML style, 19

Tahuayo application (Amazon), 815-820TCP (Transmission Control Protocol), 414TCP/IP (Transmission Control

Protocol/Internet Protocol), 386security, 343

templatesPDF, creating, 776-777RTF, creating, 776Web sites, 137-142

temporary tables, subqueries, 260terminating execution (scripts), 526ternary operator, 39testing

code, 548GPG (Gnu Privacy Guard), 422-427mod_auth_mysql module, 407PHP

installations, 904-905support, 897

regression, 377SSL, 899string length, 120variable status, 45

text, 59-61anti-aliasing, 489baseline, 497buttons, colors/fonts, 492checking, 76ciphertext (encryption), 351closing, 69deleting, 76fitting onto buttons, 495-498formats, 68-69images

creating, 491-499drawing or printing on, 487-489

960 tables

limitations, 79locking, 78-79navigating, 76-77opening, 61

file modes, 61-62fopen() function, 62-64FTP (File Transfer Protocol), 64-65HTTP (Hypertext Transfer

Protocol), 64-65potential problems, 65-66

plain text (encryption), 351positioning, 498-499reading, 61, 71-72

feof() function, 73fgetc() function, 75fgetcsv() function, 73-74fgets() function, 73fgetss() function, 73file() function, 74fopen() function, 72fpassthru() function, 74fread() function, 75readfile() function, 74

writing, 61, 499file formats, 68-69fputs() function, 67fwrite() function, 67-68

TEXT type, 239-241Thawte Web site, 348, 355threaded discussion group application,

741-742, 763-764article list, 747, 749

collapsing threads, 748, 752displaying articles, 752-753expanding threads, 748-751individual articles, viewing,

760-762new articles, adding, 762-769plus symbols, 748treenode class, 753-760

database design, 744-745, 747extensions, 769files, 744posters, 744

solutions, 742-744tree structure, 742-743tree_node class, 743

threads, 741collapsing, 748, 752expanding, 748-753

threats to securitycommercial Web sites, 342

DDoS (Distributed Denial ofService), 346

DoS (Denial of Service), 346-347exposure of confidential data,

343-344loss of data, 344-345modification of data, 345-346repudiation, 348-349software errors, 347-348

crackers, 366disgruntled employees, 366hardware thieves, 366infected machines, 366

three-dimensional arrays, 90-92throw clause, 196throwing exceptions, 193tiers (applications), 218TIFF library Web site, 778, 891time and date

converting between PHP and MySQLformats, 476-477

in MySQLdate calculations, 478-480DATE_FORMAT() function,

476-477MySQL Web site, 481UNIX_TIMESTAMP() function,

476-477in PHP, 7, 469, 474

calendar functions, 480-481checkdate() function, 474date calculations, 477-478date() function, 469-472floor() function, 478getdate() function, 473microseconds, 480mktime() function, 471-472PHP Web site, 481

961time and date

timeouts, avoiding, 467timestamps, Unix, 471-472tokens (strings), 117top-down approach to security, 363topbar.php file, 819, 825totaling forms with operators, 41-42touch() function, 447traceroute command (UNIX), 344tracking user’s purchases (Shopping Cart

application), 608Transmission Control Protocol. See TCPTransmission Control Protocol/Internet

Protocol. See TCP/IPtransactions, 313

ACID compliance, 313autocommit mode, 314committed, 314defined, 313InnoDB tables, 314-315rolled back, 314secure transactions, 409-410

Internet, 411-412screening user input, 417Secure Sockets Layer (SSL),

413-416secure storage, 417-419systems, 412-413user machines, 410-411Web browsers, 410-411

transfer modes, FTP, 466transferring data, database replication,

306-308tree structure (Web forum application),

742-743tree_node class, 743treenode class (Web forum application),

753, 757-760treenode_class.php files (Web forum appli-

cation), 744triggering errors, 564trim() function, 110, 271Tripwire Web site, 346troubleshooting

errors, 66. See also errorsfile uploads, 438-439opening files, 65-66

TrueType fonts, 492try blocks (exception handling), 193tuples (tables), 209tutorials

exception handling, 203graphs, 508

two-dimensional arrays, 88-90two-table joins, 250-251type

conversion specification type codes,112-113

hinting, 184operator, 40

U-u switch (mysql command), 221uasort() function, 95ucfirst() function, 113ucwords() function, 114uksort() function, 95umask() function, 443unary operators, 33undefined functions, calling, 145-146uninterruptible power supply (UPS), 359union operator, 87Unix

binary installations, 890-893date() function, 471-472Epoch (GMT), 471httpd.conf file, 896-897libpdf_php file, copying, 899PHP, testing, 897source installations, 891, 893-896SSL, testing, 899traceroute command, 344

UNIX_TIMESTAMP() function, 476-477unlink() function, 76, 447unmatched rows, 252-253unnecessary OS applications, disabling, 388unserialize() function, 527, 848unset() function, 45UNSIGNED keyword, 231unsubscribe() function, 717unsubscribing online newsletters, 717-718update anomalies (Web databases)

962 timeouts, avoiding

UPDATE privilege, 225UPDATE statement, 261updating

avoiding, 213FTP servers, 464-465operating systems, 387-388privileges, 293-294records, 261Shopping Cart application, 631-632software, 378-379

upload.php files (MLM application), 691uploading

files, 431-432displaying, 437HTML, 433HTML forms, 431PHP, writing, 434-438security, 434, 438troubleshooting, 438-439

FTP (File Transfer Protocol), 466online newsletters, 724-731

UPS (uninterruptible power supply), 359url_fns.php files (PHPBookmark application),

572urlencode() function, 399, 455USAGE privilege, 227user authentication

input data, validating, 580logging in, 584-587logging out, 587-588passwords

resetting, 591-595setting, 588-591

registering, 577, 580-583user declared variables, 28user input, screening, 417user interfaces, commercial Web sites,

333-334user personalization

bookmarksadding, 596-599deleting, 600-602displaying, 599recommending, 571storing, 571

defined, 569passwords, 570recommendations, 602-605solutions, 570-572system requirements, 570usernames, 570

user privileges, database security, 295-296user tables, 288-290user views (Shopping Cart application),

609-610user-defined exceptions, 196-197, 199user-defined sorts, multidimensional arrays,

93-95user_auth_fns.php files

MLM application, 691PHPBookmark application, 572Shopping Cart application, 612Warm Mail application, 655

user_auth_fns.php librarycheck_auth_user() function, 665

usernames, 570users

administrative user privileges, 226-227authentication, 391, 401-406

access control, implementing,392-395

basic authentication, 399digest authentication, 400encrypting passwords, 397-399identifying users, 391-392mod_auth_mysql module, 406-408multiple pages, protecting, 399storing passwords, 395Web sites, 408

MySQL, setting up, 223privileges, 223

global privileges, 224GRANT command, 223-228principle of least privilege, 223REVOKE command, 227-228types, 225-227

secure transactions, 410-411setting up in MySQL, 223-229

Using mkdir() function, 443usort() function, 94

963usort() function

utilities, myisamchk, 303utilityfunctions.php file, 820, 825

Vvalid email() function, 581validating user authentication input data,

580values

array elements, 82assigning to variables, 28atomic column values (databases),

214-215columns, EXPLAIN statement, 303default, database optimization, 305null values, avoiding (Web databases),

216returning, 94

assignment operator, 34-35functions, max() function, 155-156

tables, 209variables, 27, 30, 150-153, 539

arrays, 81-82applying functions to elements,

103-104associative arrays, 85converting to scalar variables,

105-106counting elements, 104elements, 82functions, passing by reference, 104indexes, 82loading from files, 98-101multidimensional arrays, 88-95navigating within an array, 102numerically indexed arrays, access-

ing contents, 83-84operators, 87-88reordering, 96-98set cardinality, 104sorting, 92-93

browseNode, 824debugging, 559-561environment functions, 450form variables, 23-27

functions, 44, 148reinterpreting, 46status, testing, 45types, setting/testing, 44-45

global variables, 151identifiers, 28local stored procedures, 319local variables, 151mode, 824page, 824scalar variables, 81, 105-106scope, 31-32sessions, 510

deregistering, 513implementing, 513registering, 513serializing, 514Shopping Cart application, 623

superglobal, 32types, 29

casts, 30data types, 29strength, 29-30variable variables, 30

user declared variables, 28values, assigning, 28

verificationsconnections, 293requests, 293

VeriSign, 355Web site, 348

version control (code), 542-543CVS (Concurrent Versions System),

543multiple programmers, 543repository, 542-543

view_post.php files (Web forum application),744

viewingdatabases in MySQL, 233-234individual articles (Web forum appli-

cation), 760-762lists (online newsletters), 708-717message headers (Warm Mail applica-

tion), 680-681tables in MySQL, 233-234

964 utilities, myisamchk

views, File Details, 445visibility, controlling, 169-170vote.html file, 500

Ww file mode, 63w+ file mode, 63W3C Web site, 808Warm Mail application (email client)

accountscreating, 668-669deleting, 670modifying, 670selecting, 671-673setting up, 666-668

databases, setting up, 655-656email, deleting, 681-682extensions, 686files, 654-655IMAP function library, 652-653interface, 654logging in, 663-666logging out, 666reading mail, 671, 681

mailbox contents, viewing, 674-676messages, 677-681selecting accounts, 671, 673

script architecture, 657, 662-663sending mail

forwarding/replying, 684-685new messages, 682-684

solutionscomponents, 652-653overview, 654-655

WBMP (Wireless Bitmap), 485Web application projects

content, 546database security, 296development environment, 544documentation, 544-545logic, 546planning, 536-537prototypes, 545-546rewriting code, 537-538

running, 536-537software engineering, 536testing code, 548version control, 542-543writing maintainable code, 538

breaking up, 541-542code standards, 538commenting, 540directory structures, 542function libraries, 542indenting, 540-541naming conventions, 538-540

Web browsersauthentication, 351secure transactions, 410-411Web database architecture, 216

Web databasesarchitecture, 216-218, 268-271designing, 211

anomalies, avoiding, 213atomic column values, 214-215keys, creating, 215null values, avoiding, 216questions, formulating, 215real-world objects, modeling,

211-212redundant data, avoiding, 212-213table types, 216update anomalies, avoiding, 213

querying, 271adding data, 276-280connections, setting up, 273disconnecting from databases, 276input data, 271-272mysql_query() function, 274-275prepared statements, 280-281retrieving results, 275-276selecting databases, 274

selecting in MySQL, 229tables

column types, 232-241creating, 229-231indexes, creating, 234-235

965Web databases

keywords, 231types, 229viewing, 233-234

transaction process, 217users, setting up, 228-229viewing in MySQL, 233-234

Web development, 910Web forum application, 741-742, 763-764

article list, 747-749collapsing threads, 748-752displaying articles, 752-753expanding threads, 748-751individual articles, viewing,

760-762new articles, adding, 762-769plus symbols, 748treenode class, 753-760

database design, 744-747extensions, 769files, 744posters, 744solution components, 742-743solution overview, 743-744tree structure, 742-743tree_node class, 743

Web forumsPhorum, 770threads, 741

Web pagesauthentication, 399services, adding, 452, 454

Web resources for DOM, 884Web servers

Apache. See Apache,Web serverauthentication, 351commands, 447-450file upload, 434-438Microsoft IIS, configuring, 381secure storage, 417-419Secure Web servers, 355-357Web database architecture, 216

Web Services. See also SOAPadding to Web pages, 452-454defined, 811

interfaces (Amazon), 813-814protocols

SOAP (Simple Object AccessProtocol), 811-812

WSDL (Web Services DescriptionLanguage), 812

Web Services Description Language (WSDL),812

Web sitesAdobe, FDF, 789Adobe Acrobat, 776Ajax development, 885AMANDA (Advanced Maryland

Automated Network Disk Archiver),358

Analog, 330ANSI, 265Apache, 891Apache Software, 909Apache Today, 909Apache Week, 909authentication documentation, 408Boutell, 508BUGTRAQ archives, 437CGI specification, 450Codewalkers, 909CVS (Concurrent Versions System),

543, 549Devshed, 508, 908EPA, 359Equifax Secure, 355Evil Walrus, 909Extreme Programming, 549FastTemplate, 546FDF, 789Fedex, 335FishCartSQL, 650FPDF function library, 778gd documentation, 508Ghostscript, 775GNU Privacy Guard, 419Google, 811HotScripts.com, 908IMAP c client, 891

966 Web databases

JPEG (Joint Photographic ExpertsGroup), 485

JPEG library, 778, 891Microsoft Word, 773MySQL, 220, 309, 891, 909

date and time functions, 481online manual, 241

Natural Order String Comparison,119

Netscapecookie specification, 511SSL 3.0 Specification, 427

New York Times, 392OpenSSL, 891PDF, 775PEAR (PHP Extension and

Application Repository), 907PECL, 907Philip and Alex’s Guide to Web

Publishing, 910PHP, 537, 891

Application Tools, 909Base Library, 908calendar functions, 481Center, 908Classes Repository, 908Club, 908Developer, 909Developer’s Network Unified

Forums, 909Homepage, 908Hypertext Preprocessor, 106Kitchen, 909Magazine, 907online manual, 80Resource, 908-909

phpautodoc, 545PHPBuilder.com, 908PHPCommunity, 907phpdoc, 544PHPDocumentor, 544PHPIndex.com, 908PHPMyAdmin.Net, 908PHPWizard.net, 908

php|architect, 907PNG (Portable Network Graphics),

485PNG library, 891Postnuke, 909PX-PHP Code Exchange, 908RFC Editor, 451, 468SearchDatabase.com, 909Slashdot, 392, 741SourceForge, 545, 909SQL Course, 909Stronghold, 356Summary, 330templates, 137-142Thawte, 348, 355TIFF library, 778, 891Tripwire, 346UPS, 335VeriSign, 348, 355W3C, 808Webalizer, 330WeberDev.com, 908WebMonkey.com, 908Zend, 131, 508Zend.Com, 907zlib library, 891

Webalizer Web site, 330WeberDev.com Web site, 908WebMonkey.com Web site, 908WHERE clause, 248

comparison operators, 248-249join condition, 250

while loops, 53-54whitespace, 20, 110wildcard character (%), 293Windows

Apache, 902MySQL, 900-901PHP, 903-904

Apache configurations, 904testing, 904-905

support, 7, 900Wireless Bitmap (WBMP), 485word processor formats, 773

967word processor formats

writingcode for classes, 175-183files, 61, 418

file formats, 68-69fputs() function, 67fwrite() function, 67-68

maintainable code, 538breaking up, 541-542code standards, 538commenting, 540directory structures, 542function libraries, 542indenting, 540-541naming conventions, 538-540

PHP file uploads, 434-438runtime errors, 555Text buttons, 499

WSDL (Web Services Description Language),812

X-Yx file mode, 63x+ file mode, 63XHTML (Extensible Hypertext Markup

Language), 858XML (Extensible Markup Language), 807,

860Amazon connections, 807-808defined, 808-810DTD (Document Type Definition),

810example, 808namespaces, 811parsing (Amazon), 814REST/XML (Amazon), 838-839, 844root elements, 811SGML (Standard Generalized Markup

Language), 808styles, 19tags (closing and opening), 810

XMLHTTPRequest object, 860, 862XSLT (XSL Transformations), 860XSS (Cross Site Scripting) attacks, 365

ZZend engines

Optimizers, 547PHP 5.3, improvements for, 7Web site, 131, 508, 907

zlib library Web site, 891

968 writing