-
00 7842 FM 3/6/01 3:38 PM Page i PHP and MySQL Web Development Luke Welling and Laura Thomson 201 West 103rd St.
-
00 7842 FM 3/6/01 3:38 PM Page ii PHP and MySQL Web Development ACQUISITIONS EDITOR Copyright DEVELOPMENT EDITOR © 2001 by Sams Publishing All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein.
-
00 7842 FM 3/6/01 3:38 PM Page iii Overview Introduction 1 PART I Using PHP 1 PHP Crash Course 2 Storing and Retrieving Data 3 Using Arrays 69 4 String Manipulation and Regular Expressions 5 Reusing Code and Writing Functions 6 Object-Oriented PHP 147 PART II 9 49 93 117 Using MySQL 7 Designing Your Web Database 171 8 Creating Your Web Database 9 Working with Your MySQL Database 183 207 10 Accessing Your MySQL Database from the Web with PHP 11 Advanced MySQL 245 PART III
-
00 7842 FM 3/6/01 3:38 PM Page iv PART V Building Practical PHP and MySQL Projects 22 Using PHP and MySQL for Large Projects 23 Debugging 24 Building User Authentication and Personalization 25 Building a Shopping Cart 26 Building a Content Management System 27 Building a Web-Based Email Service 28 Building a Mailing List Manager 29 Building Web Forums 30 Generating Personalized Documents in Portable Document Format (PDF) 477 587 617 655 711 A Installing PHP 4 and MySQL B Web
-
00 7842 FM 3/6/01 3:38 PM Page v Contents Introduction 1 Who Should Read This Book? ..............................................................1 What Is PHP? ..........................................................................................1 What Is MySQL? ....................................................................................2 Why Use PHP and MySQL? ..................................................................2 Some of PHP’s Strengths .......................................
-
00 7842 FM 3/6/01 vi 3:38 PM PHP AND Page vi MYSQL WEB DEVELOPMENT Accessing Form Variables ....................................................................19 Form Variables ................................................................................19 String Concatenation ......................................................................20 Variables and Literals ......................................................................21 Identifiers ..........................................
-
00 7842 FM 3/6/01 3:38 PM Page vii CONTENTS Breaking Out of a Control Structure or Script ....................................47 Next: Saving the Customer’s Order ......................................................47 2 Storing and Retrieving Data 49 Saving Data for Later ..........................................................................50 Storing and Retrieving Bob’s Orders ..................................................50 Overview of File Processing ......................................
-
00 7842 FM 3/6/01 viii 3:38 PM PHP AND Page viii MYSQL WEB DEVELOPMENT Associative Arrays ................................................................................73 Initializing an Associative Array ....................................................73 Accessing the Array Elements ........................................................73 Using Loops with each() and list() ..................................................74 Multidimensional Arrays ...........................................
-
00 7842 FM 3/6/01 3:38 PM Page ix CONTENTS Introduction to Regular Expressions ..................................................109 The Basics ....................................................................................109 Character Sets and Classes ............................................................110 Repetition ......................................................................................111 Subexpressions .....................................................................
-
00 7842 FM 3/6/01 x 3:38 PM PHP AND Page x MYSQL WEB DEVELOPMENT Returning Values from Functions ......................................................141 Code Blocks ..................................................................................142 Recursion ............................................................................................143 Further Reading ..................................................................................145 Next .......................................
-
00 7842 FM 3/6/01 3:38 PM Page xi CONTENTS Web Database Architecture ................................................................180 Architecture ..................................................................................180 Further Reading ..................................................................................182 Next ....................................................................................................
-
00 7842 FM 3/6/01 xii 3:38 PM PHP AND Page xii MYSQL WEB DEVELOPMENT Dropping a Whole Database ..............................................................226 Further Reading ..................................................................................226 Next ....................................................................................................226 10 Accessing Your MySQL Database from the Web with PHP 227 How Web Database Architectures Work .....................................
-
00 7842 FM 3/6/01 3:38 PM Page xiii CONTENTS Table Optimization ........................................................................262 Using Indexes ................................................................................262 Use Default Values ........................................................................262 Use Persistent Connections ..........................................................262 Other Tips ...........................................................................
-
00 7842 FM 3/6/01 xiv 3:38 PM PHP AND Page xiv MYSQL WEB DEVELOPMENT Authentication Principles ....................................................................291 Using Authentication ..........................................................................292 Encryption Basics ..............................................................................293 Private Key Encryption ......................................................................294 Public Key Encryption ....................
-
00 7842 FM 3/6/01 3:38 PM Page xv CONTENTS Using Encryption in PHP ..................................................................338 Further Reading ..................................................................................347 Next ....................................................................................................347 PART IV Advanced PHP Techniques 349 16 Interacting with the File System and the Server 351 Introduction to File Upload ....................................
-
00 7842 FM 3/6/01 xvi 3:38 PM PHP AND Page xvi MYSQL WEB DEVELOPMENT Converting Between PHP and MySQL Date Formats ......................396 Date Calculations ................................................................................398 Using the Calendar Functions ............................................................399 Further Reading ..................................................................................400 Next ..............................................................
-
00 7842 FM 3/6/01 3:38 PM Page xvii CONTENTS Simple Session Example ....................................................................435 Configuring Session Control ..............................................................437 Implementing Authentication with Session Control ..........................438 Further Reading ..................................................................................445 Next ........................................................................................
-
00 7842 FM 3/6/01 xviii 3:38 PM PHP AND Page xviii MYSQL WEB DEVELOPMENT 23 Debugging 477 Programming Errors ..........................................................................478 Syntax Errors ................................................................................478 Runtime Errors ..............................................................................480 Logic Errors ..................................................................................
-
00 7842 FM 3/6/01 3:38 PM Page xix CONTENTS Solution Overview ..............................................................................542 Implementing the Database ................................................................546 Implementing the Online Catalog ......................................................548 Listing Categories ..........................................................................551 Listing Books in a Category .......................................................
-
00 7842 FM 3/6/01 xx 3:38 PM PHP AND Page xx MYSQL WEB DEVELOPMENT Script Architecture ..............................................................................623 Logging In and Out ............................................................................629 Setting Up Accounts ..........................................................................632 Creating a New Account ..............................................................634 Modifying an Existing Account ....................
-
00 7842 FM 3/6/01 3:38 PM Page xxi CONTENTS Previewing the Newsletter ............................................................703 Sending the Message ....................................................................704 Extending the Project ..........................................................................709 Next ....................................................................................................709 29 Building Web Forums 711 The Problem .................................
-
00 7842 FM 3/6/01 xxii 3:38 PM PHP AND Page xxii MYSQL WEB DEVELOPMENT Problems with Headers ......................................................................777 Extending the Project ..........................................................................778 Further Reading ..................................................................................778 PART VI Appendixes 779 A Installing PHP 4 and MySQL 781 Running PHP as a CGI Interpreter or Module ................................
-
00 7842 FM 3/6/01 3:38 PM Page xxiii About the Authors Laura Thomson is a lecturer in Web programming in the Department of Computer Science at RMIT University in Melbourne, Australia. She is also a partner in the award-winning Web development firm Tangled Web Design. Laura has previously worked for Telstra and the Boston Consulting Group.
-
00 7842 FM 3/6/01 3:38 PM Page xxiv Dedication To our Mums and Dads. Acknowledgments We would like to thank the team at Sams for all their hard work. In particular, we would like to thank Shelley Johnston Markanday without whose dedication and patience this book would not have been possible. We would also like to thank Israel Denis Jr. and Chris Newman for their valuable contributions. We appreciate immensely the work done by the PHP and MySQL development teams.
-
00 7842 FM 3/6/01 3:38 PM Page xxv Tell Us What You Think! As the reader of this book, you are our most important critic and commentator. We value your opinion and want to know what we’re doing right, what we could do better, what areas you’d like to see us publish in, and any other words of wisdom you’re willing to pass our way. You can email or write me directly to let me know what you did or didn’t like about this book—as well as what we can do to make our books stronger.
-
00 7842 FM 3/6/01 3:38 PM Page xxvi
-
01 7842 intro 3/6/01 3:33 PM Page 1 Introduction Welcome to PHP and MySQL Web Development. Within its pages, you will find distilled knowledge from our experiences using PHP and MySQL, two of the hottest Web development tools around. In this introduction, we’ll cover • Why you should read this book • What you will be able to achieve using this book • What PHP and MySQL are and why they’re great • An overview of the new features of PHP 4 • How this book is organized Let’s get started.
-
01 7842 intro 2 3/6/01 PHP 3:33 PM AND Page 2 MYSQL WEB DEVELOPMENT Using a language such as PHP and a database such as MySQL allows you to make your sites dynamic: to have them be customizable and contain real-time information. We have deliberately focused this book on real-world applications, even in the introductory chapters. We’ll begin by looking at a simple online ordering system, and work our way through the various parts of PHP and MySQL.
-
01 7842 intro 3/6/01 3:33 PM Page 3 INTRODUCTION The home page for PHP is available at http://www.php.net The home page for Zend is at http://www.zend.com What’s New In PHP Version 4? If you have used PHP before, you will notice a few important improvements in version 4. In this new version • PHP 4 is much faster than previous versions because it uses the new Zend Engine. If you need even higher performance, you can obtain the Zend Optimizer, Zend Cache, or Zend Compiler from http://www.zend.com.
-
01 7842 intro 4 3/6/01 PHP 3:33 PM AND Page 4 MYSQL WEB DEVELOPMENT To demonstrate this, the examples in this book have been written and tested on two popular setups: • Linux using the Apache Web server • Microsoft Windows 2000 using Microsoft Internet Information Server (IIS) Whatever hardware, operating system, and Web server you choose, we believe you should seriously consider using PHP and MySQL.
-
01 7842 intro 3/6/01 3:33 PM Page 5 INTRODUCTION Cost PHP is free. You can download the latest version at any time from http://www.php.net for no charge. Learning PHP The syntax of PHP is based on other programming languages, primarily C and Perl. If you already know C or Perl, or a C-like language such as C++ or Java, you will be productive using PHP almost immediately. Portability PHP is available for many different operating systems.
-
01 7842 intro 6 3/6/01 PHP 3:33 PM AND Page 6 MYSQL WEB DEVELOPMENT Ease of Use Most modern databases use SQL. If you have used another RDBMS, you should have no trouble adapting to this one. MySQL is also easier to set up than many similar products. Portability MySQL can be used on many different UNIX systems as well as under Microsoft Windows. Source Code As with PHP, you can obtain and modify the source code for MySQL. How Is This Book Organized? This book is divided into five main sections.
-
02 7842 part 1 3/6/01 3:42 PM Page 7 PART Using PHP I IN THIS PART 1 PHP Crash Course 9 2 Storing and Retrieving Data 3 Using Arrays 49 69 4 String Manipulation and Regular Expressions 5 Reusing Code and Writing Functions 6 Object-Oriented PHP 147 117 93
-
02 7842 part 1 3/6/01 3:42 PM Page 8
-
03 7842 CH01 3/6/01 3:39 PM Page 9 PHP Crash Course CHAPTER 1
-
03 7842 CH01 3/6/01 10 3:39 PM Page 10 Using PHP PART I This chapter gives you a quick overview of PHP syntax and language constructs. If you are already a PHP programmer, it might fill some gaps in your knowledge. If you have a background using C, ASP, or another programming language, it will help you get up to speed quickly. In this book, you’ll learn how to use PHP by working through lots of real world examples, taken from our experience in building e-commerce sites.
-
03 7842 CH01 3/6/01 3:39 PM Page 11 PHP Crash Course CHAPTER 1 11 Using PHP 1 In order to work through the examples in this chapter and the rest of the book, you will need access to a Web server with PHP installed. To get the most from the examples and case studies, you should run them and try changing them. To do this, you’ll need a testbed where you can experiment.
-
03 7842 CH01 3/6/01 12 3:39 PM Page 12 Using PHP PART I Part of the HTML for this is shown in Listing 1.1. There are two important things to notice in this code. LISTING 1.1 orderform.html—HTML for Bob’s Basic Order Form
-
03 7842 CH01 3/6/01 3:39 PM Page 13 PHP Crash Course CHAPTER 1 Processing the Form To process the form, we’ll need to create the script mentioned in the ACTION attribute of the FORM tag called processorder.php. Open your text editor and create this file. Type in the following code:
Bob’s Auto Parts - Order Results Bob’s Auto Parts
Order Results
Notice, how everything we’ve typed so far is just plain HTML.
-
03 7842 CH01 3/6/01 14 3:39 PM Page 14 Using PHP PART I FIGURE 1.2 Text passed to PHP’s echo construct is echoed to the browser. None of the raw PHP is visible. This is because the PHP interpreter has run through the script and replaced it with the output from the script. This means that from PHP we can produce clean HTML viewable with any browser—in other words, the user’s browser does not need to understand PHP. This illustrates the concept of server-side scripting in a nutshell.
-
03 7842 CH01 3/6/01 3:39 PM Page 15 PHP Crash Course CHAPTER 1 PHP Tag Styles There are actually four different styles of PHP tags we can use. Each of the following fragments of code is equivalent. • Short style echo “
Order processed.”; ?> This is the tag style that will be used in this book. It is the default tag that PHP developers use to code PHP. This style of tag is the simplest and follows the style of an SGML (Standard Generalized Markup Language) processing instruction.
-
03 7842 CH01 3/6/01 16 3:39 PM Page 16 Using PHP PART I As you have probably guessed, using the echo construct has a very simple result; it prints (or echoes) the string passed to it to the browser. In Figure 1.2, you can see the result is that the text “Order processed.” appears in the browser window. You will notice that a semicolon appears at the end of the echo statement. This is used to separate statements in PHP much like a period is used to separate sentences in English.
-
03 7842 CH01 3/6/01 3:39 PM Page 17 PHP Crash Course CHAPTER 1 17 way they did, when it was last modified, and so on. You will generally find comments in all but the simplest PHP scripts. 1 The PHP interpreter will ignore any text in a comment. Essentially the PHP parser skips over the comments that are equivalent to whitespace. PHP CRASH COURSE PHP supports C, C++, and shell script style comments.
-
03 7842 CH01 3/6/01 18 3:39 PM Page 18 Using PHP PART I FIGURE 1.3 PHP’s date() function returns a formatted date string. Calling Functions Look at the call to date(). This is the general form that function calls take. PHP has an extensive library of functions you can use when developing Web applications. Most of these functions need to have some data passed to them and return some data.
-
03 7842 CH01 3/6/01 3:39 PM Page 19 PHP Crash Course CHAPTER 1 Accessing Form Variables Within your PHP script, you can access each of the form fields as a variable with the same name as the form field. Let’s look at an example. Start by adding the following lines to the bottom of your PHP script: echo echo echo echo echo “
Your order is as follows:”; “
”; $tireqty.” tires
”; $oilqty.” bottles of oil
”; $sparkqty.
-
03 7842 CH01 3/6/01 20 3:39 PM Page 20 Using PHP PART I There are two ways of accessing the form data via variables. In this example, and throughout this book, we have used the short style for referencing form variables. In this case, you will notice that the variable names we use in this script are the same as the ones in the HTML form. This is always the case with the short style.
-
03 7842 CH01 3/6/01 3:39 PM Page 21 PHP Crash Course CHAPTER 1 You could alternatively write echo “$tireqty tires
”; This is equivalent to the first statement. Either format is valid, and which one you use is a matter of personal taste. Variables and Literals The variable and string we concatenate together in each of the echo statements are different types of things. Variables are a symbol for data. The strings are data themselves.
-
03 7842 CH01 3/6/01 22 3:39 PM Page 22 Using PHP PART I User-Declared Variables You can declare and use your own variables in addition to the variables you are passed from the HTML form. One of the features of PHP is that it does not require you to declare variables before using them. A variable will be created when you first assign a value to it—see the next section for details. Assigning Values to Variables You assign values to variables using the assignment operator, =.
-
03 7842 CH01 3/6/01 3:39 PM Page 23 PHP Crash Course CHAPTER 1 Type Strength For example, when we created $totalqty and $totalamount, their initial types were determined, as follows: $totalqty = 0; $totalamount = 0.00; Because we assigned 0, an integer, to $totalqty, this is now an integer type variable. Similarly, $totalamount is now of type double. Strangely enough, we could now add a line to our script as follows: $totalamount = “Hello”; The variable $totalamount would then be of type string.
-
03 7842 CH01 3/6/01 24 3:39 PM Page 24 Using PHP PART I (As you can see, PHP allows a lot of freedom in this area—all languages will let you change the value of a variable, but not many will allow you to change the variable’s type, and even fewer will let you change the variable’s name.) The way these work is to use the value of one variable as the name of another. For example, we could set $varname = “tireqty”; We can then use $$varname in place of $tireqty.
-
03 7842 CH01 3/6/01 3:39 PM Page 25 PHP Crash Course CHAPTER 1 echo TIREPRICE; As well as the constants you define, PHP sets a large number of its own. An easy way to get an overview of these is to run the phpinfo() command: phpinfo(); This will provide a list of PHP’s predefined variables and constants, among other useful information. We will discuss some of these as we go along. Variable Scope The term scope refers to the places within a script where a particular variable is visible.
-
03 7842 CH01 3/6/01 26 3:39 PM Page 26 Using PHP PART I Arithmetic Operators Arithmetic operators are very straightforward—they are just the normal mathematical operators. The arithmetic operators are shown in Table 1.1. TABLE 1.1 PHP’s Arithmetic Operators Operator Name Example + Addition Subtraction Multiplication Division Modulus $a + $b * / % $a - $b $a * $b $a / $b $a % $b With each of these operators, we can store the result of the operation.
-
03 7842 CH01 3/6/01 3:39 PM Page 27 PHP Crash Course CHAPTER 1 String Operators 1 $a = “Bob’s “; $b = “Auto Parts”; $result = $a.$b; Auto Parts”. Assignment Operators We’ve already seen =, the basic assignment operator. Always refer to this as the assignment operator, and read it as “is set to.” For example $totalqty = 0; This should be read as “$totalqty is set to zero”. We’ll talk about why when we discuss the comparison operators later in this chapter.
-
03 7842 CH01 3/6/01 28 3:39 PM Page 28 Using PHP PART I Combination Assignment Operators In addition to the simple assignment, there is a set of combined assignment operators. Each of these is a shorthand way of doing another operation on a variable and assigning the result back to that variable. For example $a += 5; This is equivalent to writing $a = $a + 5; Combined assignment operators exist for each of the arithmetic operators and for the string concatenation operator.
-
03 7842 CH01 3/6/01 3:39 PM Page 29 PHP Crash Course CHAPTER 1 29 However, if the ++ is after the $a, we are using the post-increment operator. This has a different effect. Consider the following: 1 $a=4; echo $a++; PHP CRASH COURSE In this case, the effects are reversed. That is, first, the value of $a is returned and printed, and second, it is incremented. The value of this whole expression is 4. This is the value that will be printed.
-
03 7842 CH01 3/6/01 30 3:39 PM Page 30 Using PHP PART I It is easy to confuse this with =, the assignment operator. This will work without giving an error, but generally will not give you the result you wanted. In general, non-zero values evaluate to true and zero values to false. Say that you have initialized two variables as follows: $a = 5; $b = 7; If you then test $a = $b, the result will be true. Why? The value of $a = $b is the value assigned to the left-hand side, which in this case is 7.
-
03 7842 CH01 3/6/01 3:39 PM Page 31 PHP Crash Course CHAPTER 1 PHP supports logical AND, OR, XOR (exclusive or), and NOT. 31 1 The set of logical operators and their use is summarized in Table 1.4. PHP CRASH COURSE TABLE 1.
-
03 7842 CH01 3/6/01 32 3:39 PM Page 32 Using PHP PART I Other Operators In addition to the operators we have covered so far, there are a number of others. The comma operator, , ,is used to separate function arguments and other lists of items. It is normally used incidentally. Two special operators, new and ->, are used to instantiate a class and to access class members, respectively. These will be covered in detail in Chapter 6. The array operators, [], enable us to access array elements.
-
03 7842 CH01 3/6/01 3:39 PM Page 33 PHP Crash Course CHAPTER 1 For example, under UNIX-like operating systems, you can use or, equivalently on a Windows server $out = `dir c:`; echo “
”.$out.”
”; Either of these versions will obtain a directory listing and store it in $out. It can then be echoed to the browser or dealt with in any other way. There are other ways of executing commands on the server. We will cover these in Chapter 16, “Interacting with the File System and the Server.
-
03 7842 CH01 3/6/01 34 3:39 PM Page 34 Using PHP PART I FIGURE 1.5 The totals of the customer’s order have been calculated, formatted, and displayed. The total amount seems to be correct, but why were the multiplications performed before the additions? The answer lies in the precedence of the operators, that is, the order in which they are evaluated. Precedence and Associativity: Evaluating Expressions In general, operators have a set precedence, or order, in which they are evaluated.
-
03 7842 CH01 3/6/01 3:39 PM Page 35 PHP Crash Course CHAPTER 1 TABLE 1.6 Continued Operators left left right left left xor left left left left left n/a n/a left left left right right n/a n/a || and print = += -= *= /= .= %= &= |= ^= ~= <<= >>= ? : && | ^ & == != === < <= > >= << >> + - . * / % ! ~ ++ -- (int) (double) (string) (array) (object) @ [] new () Notice that the highest precedence operator is one we haven’t covered yet: plain old parentheses.
-
03 7842 CH01 3/6/01 36 3:39 PM Page 36 Using PHP PART I You can use as many sets of parentheses as you like in an expression. The innermost set of parentheses will be evaluated first. Variable Functions Before we leave the world of variables and operators, we’ll take a look at PHP’s variable functions. These are a library of functions that enable us to manipulate and test variables in different ways.
-
03 7842 CH01 3/6/01 3:39 PM Page 37 PHP Crash Course CHAPTER 1 Testing Variable Status 37 1 PHP has several functions for testing the status of a variable. int isset(mixed var); This function takes a variable name as argument and returns true if it exists and false otherwise. You can wipe a variable out of existence by using its companion function, unset(). This has the following prototype: int unset(mixed var); This gets rid of the variable it is passed and returns true.
-
03 7842 CH01 3/6/01 38 3:39 PM Page 38 Using PHP PART I Each of these accepts a variable as input and returns the variable’s value converted to the appropriate type. Control Structures Control structures are the structures within a language that allow us to control the flow of execution through a program or script. You can group them into conditionals (or branching) structures, and repetition structures, or loops. We will consider the specific implementations of each of these in PHP next.
-
03 7842 CH01 3/6/01 3:39 PM Page 39 PHP Crash Course CHAPTER 1 echo “”; echo “You did not order anything on the previous page!
”; echo “”; The three lines of code enclosed in curly braces are now a block of code. When the condition is true, all three lines will be executed. When the condition is false, all three lines will be ignored. A Side Note: Indenting Your Code As already mentioned, PHP does not care how you lay out your code.
-
03 7842 CH01 3/6/01 40 3:39 PM Page 40 Using PHP PART I if( $totalqty == 0) { echo “You did not order anything on the previous page!
”; } else { if ( $tireqty>0 ) echo $tireqty.” tires
”; if ( $oilqty>0 ) echo $oilqty.” bottles of oil
”; if ( $sparkqty>0 ) echo $sparkqty.” spark plugs
”; } elseif Statements For many of the decisions we make, there are more than two options. We can create a sequence of many options using the elseif statement.
-
03 7842 CH01 3/6/01 3:39 PM Page 41 PHP Crash Course CHAPTER 1 41 switch Statements 1 The switch statement works in a similar way to the if statement, but allows the condition to take more than two values. In an if statement, the condition can be either true or false. In a switch statement, the condition can take any number of different values, as long as it evaluates to a simple type (integer, string, or double).
-
03 7842 CH01 3/6/01 42 3:39 PM Page 42 Using PHP PART I This HTML code has added a new form variable whose value will be “a”, “b”, “c”, or “d”. We could handle this new variable with a series of if and elseif statements like this: if($find == “a”) echo “
Regular customer.”; elseif($find == “b”) echo “
Customer referred by TV advert.”; elseif($find == “c”) echo “
Customer referred by phone directory.”; elseif($find == “d”) echo “
Customer referred by word of mouth.
-
03 7842 CH01 3/6/01 3:39 PM Page 43 PHP Crash Course CHAPTER 1 try to use whichever conditional will be most readable in your situation. You will acquire a feel for this with experience. One thing that computers have always been very good at is automating repetitive tasks. If there is something that you need done the same way a number of times, you can use a loop to repeat some parts of your program. Bob wants a table displaying the freight cost that will be added to a customer’s order.
-
03 7842 CH01 3/6/01 44 3:39 PM Page 44 Using PHP PART I LISTING 1.
-
03 7842 CH01 3/6/01 3:39 PM Page 45 PHP Crash Course CHAPTER 1 echo $num.”
”; $num++; 45 1 } We can use a while loop to do something more useful, such as display the repetitive freight table in Figure 1.7. Listing 1.4 uses a while loop to generate the freight table. LISTING 1.4 freight.
-
03 7842 CH01 3/6/01 46 3:39 PM Page 46 Using PHP PART I The basic structure of a for loop is for( expression1; condition; expression2) expression3; • expression1 is executed once at the start. Here you will usually set the initial value of a counter. • The condition expression is tested before each iteration. If the expression returns false, iteration stops. Here you will usually test the counter against a limit. • expression2 is executed at the end of each iteration.
-
03 7842 CH01 3/6/01 3:39 PM Page 47 PHP Crash Course CHAPTER 1 do..while Loops do expression; while( condition ); A do..while loop differs from a while loop because the condition is tested at the end. This means that in a do..while loop, the statement or block within the loop is always executed at least once. Even if we take this example in which the condition will be false at the start and can never become true, the loop will be executed once before checking the condition and ending.
-
03 7842 CH01 3/6/01 48 3:39 PM Page 48 Using PHP PART I Next: Saving the Customer’s Order Now you know how to receive and manipulate the customer’s order. In the next chapter, we’ll look at how to store the order so that it can be retrieved and fulfilled later.
-
04 7842 CH02 3/6/01 3:37 PM Page 49 Storing and Retrieving Data CHAPTER 2
-
04 7842 CH02 3/6/01 50 3:37 PM Page 50 Using PHP PART I Now that we know how to access and manipulate data entered in an HTML form, we can look at ways of storing that information for later use. In most cases, including the example we looked at in the previous chapter, you’ll want to store this data and load it later. In our case, we need to write customer orders to storage so that they can be filled later.
-
04 7842 CH02 3/6/01 3:37 PM Page 51 Storing and Retrieving Data CHAPTER 2 51 NOTE The HTML and PHP scripts used in this chapter can be found in the chapter2/ folder of this book’s CD-ROM. We’ve modified the form to include a quick way to obtain the customer’s shipping address. You can see this form in Figure 2.1. 2 STORING AND RETRIEVING DATA FIGURE 2.1 This version of the order form gets the customer’s shipping address. The form field for the shipping address is called address.
-
04 7842 CH02 3/6/01 52 3:37 PM Page 52 Using PHP PART I Overview of File Processing There are three steps to writing data to a file: 1. Open the file. If the file doesn’t already exist, it will need to be created. 2. Write the data to the file. 3. Close the file. Similarly, there are three steps to reading data from a file: 1. Open the file. If the file can’t be opened (for example, if it doesn’t exist), we need to recognize this and exit gracefully. 2. Read data from the file. 3. Close the file.
-
04 7842 CH02 3/6/01 3:37 PM Page 53 Storing and Retrieving Data CHAPTER 2 53 Using fopen() to Open a File Let’s assume that we want to write a customer order to Bob’s order file. You can open this file for writing with the following: $fp = fopen(“$DOCUMENT_ROOT/../orders/orders.txt”, “w”); When fopen is called, it expects two or three parameters. Usually you’ll use two, as shown in this code line. You could also specify an absolute path to the file.
-
04 7842 CH02 3/6/01 54 3:37 PM Page 54 Using PHP PART I TABLE 2.1 Summary of File Modes for fopen Mode Meaning r Read mode—Open the file for reading, beginning from the start of the file. Read mode—Open the file for reading and writing, beginning from the start of the file. Write mode—Open the file for writing, beginning from the start of the file. If the file already exists, delete the existing contents. If it does not exist, try and create it.
-
04 7842 CH02 3/6/01 3:37 PM Page 55 Storing and Retrieving Data CHAPTER 2 55 If the filename you use begins with ftp://, a passive mode FTP connection will be opened to the server you specify and a pointer to the start of the file will be returned. If the filename you use begins with http://, an HTTP connection will be opened to the server you specify and a pointer to the response will be returned.
-
04 7842 CH02 3/6/01 56 3:37 PM Page 56 Using PHP PART I If you get this error, you need to make sure that the user that the script runs as has permission to access the file you are trying to use. Depending on how your server is set up, the script might be running as the Web server user or as the owner of the directory that the script is in. On most systems, the script will run as the Web server user.
-
04 7842 CH02 3/6/01 3:37 PM Page 57 Storing and Retrieving Data CHAPTER 2 57 2 STORING AND RETRIEVING DATA FIGURE 2.3 Using your own error messages instead of PHP’s can be more user friendly. Writing to a File Writing to a file in PHP is relatively simple. You can use either of the functions fwrite() (file write) or fputs() (file put string); fputs() is an alias to fwrite().
-
04 7842 CH02 3/6/01 58 3:37 PM Page 58 Using PHP PART I File Formats When you are creating a data file like the one in our example, the format in which you store the data is completely up to you. (However, if you are planning to use the data file in another application, you may have to follow that application’s rules.) Let’s construct a string that represents one record in our data file. We can do this as follows: $outputstring = $date.”\t”.$tireqty.” tires \t”.$oilqty.” oil\t” .$sparkqty.
-
04 7842 CH02 3/6/01 3:37 PM Page 59 Storing and Retrieving Data CHAPTER 2 59 This function will return true if the file was successfully closed or false if it wasn’t. This is generally much less likely to go wrong than opening a file in the first place, so in this case we’ve chosen not to test it. Reading from a File Right now, Bob’s customers can leave their orders via the Web, but if Bob’s staff wants to look at the orders, they’ll have to open the files themselves.
-
04 7842 CH02 3/6/01 60 3:37 PM Page 60 Using PHP PART I FIGURE 2.4 The vieworders.php script displays all the orders currently in the orders.txt file in the browser window. Let’s look at the functions in this script in detail. Opening a File for Reading: fopen() Again, we open the file using fopen(). In this case we are opening the file for reading only, so we use the file mode “r”: $fp = fopen(“$DOCUMENT_ROOT/../orders/orders.
-
04 7842 CH02 3/6/01 3:37 PM Page 61 Storing and Retrieving Data CHAPTER 2 61 There are many different functions that can be used to read from files. The fgets() function is useful when dealing with files that contain plain text that we want to deal with in chunks. An interesting variation on fgets() is fgetss(), which has the following prototype: string fgetss(int fp, int length, string [allowable_tags]); The function fgetcsv() is another variation on fgets().
-
04 7842 CH02 3/6/01 62 3:37 PM Page 62 Using PHP PART I The optional second parameter specifies whether PHP should look for the file in the include_path and operates the same way as in fopen(). The function returns the total number of bytes read from the file. Secondly, you can use fpassthru(). You need to open the file using fopen() first. You can then pass the file pointer as argument to fpassthru(), which will dump the contents of the file from the pointer’s position onward to standard output.
-
04 7842 CH02 3/6/01 3:37 PM Page 63 Storing and Retrieving Data CHAPTER 2 63 It is not generally sensible to read a file character-by-character unless for some reason we want to process it character-by-character. Reading an Arbitrary Length: fread() The final way we can read from a file is using the fread() function to read an arbitrary number of bytes from the file.
-
04 7842 CH02 3/6/01 64 3:37 PM Page 64 Using PHP PART I Navigating Inside a File: rewind(), fseek(), and ftell() You can manipulate and discover the position of the file pointer inside a file using rewind(), fseek(), and ftell(). The rewind() function resets the file pointer to the beginning of the file. The ftell() function reports how far into the file the pointer is in bytes.
-
04 7842 CH02 3/6/01 3:37 PM Page 65 Storing and Retrieving Data CHAPTER 2 65 File Locking Imagine a situation where two customers are trying to order a product at the same time. (Not uncommon, especially when you start to get any kind of volume of traffic on a Web site.
-
04 7842 CH02 3/6/01 66 3:37 PM Page 66 Using PHP PART I You should also add locks to vieworders.php: $fp = fopen(“$DOCUMENT_ROOT /../orders/orders.txt”, “r”); flock($fp, 1); // lock file for reading // read from the file flock($fp, 3); // release read lock fclose($fp); Our code is now more robust, but still not perfect.
-
04 7842 CH02 3/6/01 3:37 PM Page 67 Storing and Retrieving Data CHAPTER 2 67 How RDBMSs Solve These Problems Relational database management systems address all of these issues: • RDBMSs can provide faster access to data than flat files. And MySQL, the database system we use in this book, has some of the fastest benchmarks of any RDBMS. • RDBMSs can be easily queried to extract sets of data that fit certain criteria.
-
04 7842 CH02 3/6/01 3:37 PM Page 68
-
05 7842 CH03 3/6/01 3:41 PM Page 69 Using Arrays CHAPTER 3
-
05 7842 CH03 3/6/01 70 3:41 PM Page 70 Using PHP PART I This chapter shows you how to use an important programming construct—arrays. The variables that we looked at in the previous chapters are scalar variables, which store a single value. An array is a variable that stores a set or sequence of values. One array can have many elements. Each element can hold a single value, such as text or numbers, or another array. An array containing other arrays is known as a multidimensional array.
-
05 7842 CH03 3/6/01 3:42 PM Page 71 Using Arrays CHAPTER 3 71 After we have the information as an array, we can do a number of useful things with it. Using the looping constructs from Chapter 1, we can save work by performing the same actions on each value in the array. The whole set of information can be moved around as a single unit. This way, with a single line of code, all the values can be passed to a function. For example, we might want to sort the products alphabetically.
-
05 7842 CH03 3/6/01 72 3:42 PM Page 72 Using PHP PART I If you have the information stored in file on disk, you can load the array contents directly from the file. We’ll look at this later in this chapter under the heading “Loading Arrays from Files.” If you have the data for your array stored in a database, you can load the array contents directly from the database. This is covered in Chapter 10, “Accessing Your MySQL Database from the Web with PHP.
-
05 7842 CH03 3/6/01 3:42 PM Page 73 Using Arrays CHAPTER 3 73 Using Loops to Access the Array Because the array is indexed by a sequence of numbers, we can use a for loop to more easily display the contents: for ( $i = 0; $i<3; $i++ ) echo “$products[$i] “; This loop will give similar output to the preceding code, but will require less typing than manually writing code to work with each element in a large array.
-
05 7842 CH03 3/6/01 74 3:42 PM Page 74 Using PHP PART I Using Loops with each() and list() Because the indices in this associative array are not numbers, we cannot use a simple counter in a for loop to work with the array. The following code lists the contents of our $prices array: while( { echo echo echo echo } $element = each( $prices ) ) $element[ “key” ]; “ - “; $element[ “value” ]; “
”; The output of this script fragment is shown in Figure 3.2. FIGURE 3.
-
05 7842 CH03 3/6/01 3:42 PM Page 75 Using Arrays CHAPTER 3 75 This line uses each() to take the current element from $prices, return it as an array, and make the next element current. It also uses list() to turn the 0 and 1 elements from the array returned by each() into two new variables called $product and $price. We can loop through the entire $prices array, echoing the contents using this short script.
-
05 7842 CH03 3/6/01 76 3:42 PM Page 76 Using PHP PART I Using PHP, we would write the following code to set up the data in the array shown in Figure 3.3. $products = array( array( “TIR”, “Tires”, 100 ), array( “OIL”, “Oil”, 10 ), array( “SPK”, “Spark Plugs”, 4 ) ); You can see from this definition that our products array now contains three arrays. To access the data in a one-dimensional array, recall that we need the name of the array and the index of the element.
-
05 7842 CH03 3/6/01 3:42 PM Page 77 Using Arrays CHAPTER 3 77 price => 10 ), array( Code => “SPK”, Description => “Spark Plugs”, price =>4 ) ); This array is easier to work with if you want to retrieve a single value. It is easier to remember that the description is stored in the Description column than to remember that it is stored in column 1. Using associative arrays, you do not need to remember that an item is stored at [x][y].
-
3/6/01 Page 78 Using PHP PART I ory Truck Parts Description Price teg Code t ca duc pro 78 3:42 PM TYR CodeOIL Van Parts Tyres 100 Description Oil Price 10 TYRSPKCar Parts Tyres Spark Plugs CodeOIL product 05 7842 CH03 Description Oil CAR_TIR SPK Tires Spark Plugs 100 4 Price 10 100 4 CAR_OIL Oil 10 CAR_SPK Spark Plugs 4 product attribute FIGURE 3.4 This three-dimensional array allows us to divide products into categories.
-
05 7842 CH03 3/6/01 3:42 PM Page 79 Using Arrays CHAPTER 3 79 echo “|”.$categories[$layer][$row][$column]; } echo “|
”; } } Because of the way multidimensional arrays are created, we could create four-, five-, or sixdimensional arrays. There is no language limit to the number of dimensions, but it is difficult for people to visualize constructs with more than three dimensions. Most real-world problems match logically with constructs of three or fewer dimensions.
-
05 7842 CH03 3/6/01 80 3:42 PM Page 80 Using PHP PART I The function asort() orders the array according to the value of each element. In the array, the values are the prices and the keys are the textual descriptions. If instead of sorting by price we want to sort by description, we use ksort(), which sorts by key rather than value. This code will result in the keys of the array being ordered alphabetically—Oil, Spark Plugs, Tires.
-
05 7842 CH03 3/6/01 3:42 PM Page 81 Using Arrays CHAPTER 3 81 The following code sorts this array into alphabetical order using the second column in the array—the description. function compare($x, $y) { if ( $x[1] == $y[1] ) return 0; else if ( $x[1] < $y[1] ) return -1; else return 1; } usort($products, compare); So far in this book, we have called a number of the built-in PHP functions. To sort this array, we have defined a function of our own.
-
05 7842 CH03 3/6/01 82 3:42 PM Page 82 Using PHP PART I if ( $x[2] == $y[2] ) return 0; else if ( $x[2] < $y[2] ) return -1; else return 1; } When usort($products, price. compare) is called, the array will be placed in ascending order by The “u” in usort() stands for “user” because this function requires a user-defined comparison function. The uasort() and uksort() versions of asort and ksort also require a user-defined comparison function.
-
05 7842 CH03 3/6/01 3:42 PM Page 83 Using Arrays CHAPTER 3 83 Reordering Arrays For some applications, you might want to manipulate the order of the array in other ways. The function shuffle() randomly reorders the elements of your array. The function array_reverse() gives you a copy of your array with all the elements in reverse order. Using shuffle() Bob wants to feature a small number of his products on the front page of his site.
-
05 7842 CH03 3/6/01 84 3:42 PM Page 84 Using PHP PART I Because the code selects random pictures, it produces a different page nearly every time you load it, as shown in Figure 3.5. FIGURE 3.5 The shuffle() function enables us to feature three randomly chosen products. Using array_reverse() The function array_reverse() takes an array and creates a new one with the same contents in reverse order. For example, there are a number of ways to create an array containing a countdown from ten to one.
-
05 7842 CH03 3/6/01 3:42 PM Page 85 Using Arrays CHAPTER 3 85 Alternatively, we can use the array_reverse() function to reverse the array created by range(). $numbers = range(1,10); $numbers = array_reverse($numbers); Note that array_reverse() returns a modified copy of the array. Because we did not want the original array, we simply stored the new copy over the original. Loading Arrays from Files In Chapter 2, “Storing and Retrieving Data,” we stored customer orders in a file.
-
05 7842 CH03 3/6/01 86 3:42 PM Page 86 Using PHP PART I LISTING 3.3 vieworders2.php—Using PHP to Separate, Format, and Display Orders for Bob
Bob’s Auto Parts – Customer Orders Bob’s Auto Parts
Customer Orders
//Read in the entire file. //Each order becomes an element in the array $orders= file(“../../orders/orders.
-
05 7842 CH03 3/6/01 3:42 PM Page 87 Using Arrays CHAPTER 3 87 The code in Listing 3.3 loads the entire file into an array but unlike the example in Listing 3.2, here we are using the function explode() to split up each line, so that we can apply some processing and formatting before printing. The output from this script is shown in Figure 3.6. 3 After splitting order records with explode, we can put each part of an order in a different table cell for better looking output.
-
05 7842 CH03 3/6/01 88 3:42 PM Page 88 Using PHP PART I There are a number of ways that we could have extracted numbers from these strings. Here we used the function, intval(). As mentioned in Chapter 1, intval() converts a string to an integer. The conversion is reasonably clever and will ignore parts, such as the label in this example, that cannot be converted to an integer. We will cover various ways of processing strings in the next chapter.
-
05 7842 CH03 3/6/01 3:42 PM Page 89 Using Arrays CHAPTER 3 89 the output would appear in a browser as 3 2 1 Using each(), current(), reset(), end(), next(), pos(), and prev(), you can write your own code to navigate through an array in any order. Applying Any Function to Each Element in an Array: array_walk() Sometimes you might want to work with or modify every element in an array in the same way. The function array_walk() allows you to do this.
-
05 7842 CH03 3/6/01 90 3:42 PM Page 90 Using PHP PART I Occasionally, you might be interested in the key of each element as well as the value. Your function can, as with MyPrint(), choose to ignore the key and userdata parameter. For a slightly more complicated example, we will write a function that modifies the values in the array and requires a parameter. Note that although we are not interested in the key, we need to accept it in order to accept the third parameter.
-
05 7842 CH03 3/6/01 3:42 PM Page 91 Using Arrays CHAPTER 3 91 For example, the following code $array = array(4, 5, 1, 2, 3, 1, 2, 1); $ac = array_count_values($array); creates an array called $ac that contains Key Value 4 1 5 1 1 3 2 2 3 1 This indicates that 4, 5, and 3 occurred once in $array, 1 occurred three times, and 2 occurred twice.
-
05 7842 CH03 3/6/01 92 3:42 PM Page 92 Using PHP PART I TABLE 3.1 Allowed extract_types for extract() Type Meaning EXTR_OVERWRITE Overwrites the existing variable when a collision occurs. Skips an element when a collision occurs. Creates a variable named $prefix_key when a collision occurs. You must supply prefix. Prefixes all variable names with prefix. You must supply prefix.
-
06 7842 CH04 3/6/01 3:41 PM Page 93 String Manipulation and Regular Expressions CHAPTER 4
-
06 7842 CH04 3/6/01 94 3:41 PM Page 94 Using PHP PART I In this chapter, we’ll discuss how you can use PHP’s string functions to format and manipulate text. We’ll also discuss using string functions or regular expression functions to search (and replace) words, phrases, or other patterns within a string. These functions are useful in many contexts. You’ll often want to clean up or reformat user input that is going to be stored in a database.
-
06 7842 CH04 3/6/01 3:41 PM Page 95 String Manipulation and Regular Expressions CHAPTER 4 LISTING 4.1 95 Continued mail($toaddress, $subject, $mailcontent, $fromaddress); ?>
Bob’s Auto Parts - Feedback Submitted Feedback submitted
Your feedback has been sent.
4 Bob’s feedback form asks customers for their name, email address, and comments.
-
06 7842 CH04 3/6/01 96 3:41 PM Page 96 Using PHP PART I Unsurprisingly, this function sends email. The prototype for mail() looks like this: bool mail(string to, string subject, string message, string [additional_headers]); The first three parameters are compulsory and represent the address to send email to, the subject line, and the message contents, respectively. The fourth parameter can be used to send any additional valid email headers.
-
06 7842 CH04 3/6/01 3:41 PM Page 97 String Manipulation and Regular Expressions CHAPTER 4 97 Depending on your particular purpose, you might like to use the ltrim() or chop() functions instead. They are both similar to trim(), taking the string in question as a parameter and returning the formatted string.
-
06 7842 CH04 3/6/01 98 3:41 PM Page 98 Using PHP PART I Both of these techniques print a string “as is.” You can apply some more sophisticated formatting using the functions printf() and sprintf(). These work basically the same way, except that printf() prints a formatted string to the browser and sprintf() returns a formatted string. If you have previously programmed in C, you will find that these functions are the same as the C versions.
-
06 7842 CH04 3/6/01 3:41 PM Page 99 String Manipulation and Regular Expressions CHAPTER 4 99 All conversion specifications start with a % symbol. If you actually want to print a % symbol, you will need to use %%. The padding_character is optional. It will be used to pad your variable to the width you have specified. An example of this would be to add leading zeroes to a number like a counter. The - symbol is optional.
-
06 7842 CH04 3/6/01 100 3:41 PM Page 100 Using PHP PART I The first column shows the function name, the second describes its effect, the third shows how it would be applied to the string $subject, and the last column shows what value would be returned from the function. TABLE 4.
-
06 7842 CH04 3/6/01 3:41 PM Page 101 String Manipulation and Regular Expressions CHAPTER 4 101 (This rule applies universally to special characters, so if you have \\ in your string, you need to replace it with \\\\.) PHP provides two functions specifically designed for escaping characters.
-
06 7842 CH04 3/6/01 102 3:41 PM Page 102 Using PHP PART I component parts. PHP provides several string functions (and one regular expression function) that allow us to do this. In our example, Bob wants any customer feedback from bigcustomer.com to go directly to him, so we will split the email address the customer typed in into parts to find out if they work for Bob’s big customer.
-
06 7842 CH04 3/6/01 3:41 PM Page 103 String Manipulation and Regular Expressions CHAPTER 4 103 The prototype for strtok() is string strtok(string input, string separator); The separator can be either a character or a string of characters, but note that the input string will be split on each of the characters in the separator string rather than on the whole separator string (as explode does). Calling strtok() is not quite as simple as it seems in the prototype.
-
06 7842 CH04 3/6/01 104 3:41 PM Page 104 Using PHP PART I We will look at examples using this test string: $test = “Your customer service is excellent”; If you call it with a positive number for start (only), you will get the string from the start position to the end of the string. For example, substr($test, 1); returns “our customer as with arrays. service is excellent”.
-
06 7842 CH04 3/6/01 3:41 PM Page 105 String Manipulation and Regular Expressions CHAPTER 4 105 return a number greater than zero. If str1 is less than str2, strcmp() will return a number less than zero. This function is case sensitive. The function strcasecmp() is identical except that it is not case sensitive. The function strnatcmp() and its non-case sensitive twin, strnatcasecmp(), were added in PHP 4.
-
06 7842 CH04 3/6/01 106 3:41 PM Page 106 Using PHP PART I Given the functions we have already looked at, we could use explode() or strtok() to retrieve the individual words in the message, and then compare them using the == operator or strcmp(). However, we could also do the same thing with a single function call to one of the string matching or regular expression matching functions. These are used to search for a pattern inside a string. We’ll look at each set of functions one by one.
-
06 7842 CH04 3/6/01 3:41 PM Page 107 String Manipulation and Regular Expressions CHAPTER 4 107 There are two variants on strstr(). The first variant is stristr(), which is nearly identical but is not case sensitive. This will be useful for this application as the customer might type “delivery”, “Delivery”, or “DELIVERY”. The second variant is strrchr(), which is again nearly identical, but will return the haystack from the last occurrence of the needle onwards.
-
06 7842 CH04 3/6/01 108 3:41 PM Page 108 Using PHP PART I You can avoid this problem by using the === operator to test return values: $result = strpos($test, “H”); if ($result === false) echo “Not found” else echo “Found at position 0”; Note that this will only work in PHP 4—in earlier versions you can test for false by testing the return value to see if it is a string (that is, false).
-
06 7842 CH04 3/6/01 3:41 PM Page 109 String Manipulation and Regular Expressions CHAPTER 4 109 The length value is optional and represents the point at which PHP will stop replacing. If you don’t supply this value, the string will be replaced from start to the end of the string. If length is zero, the replacement string will actually be inserted into the string without overwriting the existing string. A positive length represents the number of characters that you want replaced with the new string.
-
06 7842 CH04 3/6/01 110 3:41 PM Page 110 Using PHP PART I Character Sets and Classes Using character sets immediately gives regular expressions more power than exact matching expressions. Character sets can be used to match any character of a particular type—they’re really a kind of wildcard. First of all, you can use the . character as a wildcard for any other single character except a new line (\n). For example, the regular expression .at matches the strings “cat”, “sat”, and “mat”, among others.
-
06 7842 CH04 3/6/01 3:41 PM Page 111 String Manipulation and Regular Expressions CHAPTER 4 TABLE 4.
-
06 7842 CH04 3/6/01 112 3:41 PM Page 112 Using PHP PART I Counted Subexpressions We can specify how many times something can be repeated by using a numerical expression in curly braces ( {} ).You can show an exact number of repetitions ({3} means exactly 3 repetitions), a range of repetitions ({2, 4} means from 2 to 4 repetitions), or an open ended range of repetitions ({2,} means at least two repetitions). For example, (very ){1, 3} matches “very”, “very very” and “very very very”.
-
06 7842 CH04 3/6/01 3:41 PM Page 113 String Manipulation and Regular Expressions CHAPTER 4 113 Summary of Special Characters A summary of all the special characters is shown in Tables 4.4 and 4.5. Table 4.4 shows the meaning of special characters outside square brackets, and Table 4.5 shows their meaning when used inside square brackets. TABLE 4.
-
06 7842 CH04 3/6/01 114 3:41 PM Page 114 Using PHP PART I The second use is to validate customer email addresses in our application by encoding the standardized format of an email address in a regular expression.
-
06 7842 CH04 3/6/01 3:41 PM Page 115 String Manipulation and Regular Expressions CHAPTER 4 115 We can adapt the Smart Form example to use regular expressions as follows: if (!eregi(“^[a-zA-Z0-9_]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$”, $email)) { echo “That is not a valid email address. Please return to the” .” previous page and try again.”; exit; } $toaddress = “feedback@bobsdomain.com”; // the default value if (eregi(“shop|customer service|retail”, $feedback)) $toaddress = “retail@bobsdomain.
-
06 7842 CH04 3/6/01 116 3:41 PM Page 116 Using PHP PART I while (list($key, $value) = each ($arr)) echo “
”.$value; This splits the host name into its five components and prints each on a separate line. Comparison of String Functions and Regular Expression Functions In general, the regular expression functions run less efficiently than the string functions with similar functionality. If your application is simple enough to use string expressions, do so.
-
07 7842 CH05 3/6/01 3:35 PM Page 117 Reusing Code and Writing Functions CHAPTER 5
-
07 7842 CH05 3/6/01 118 3:35 PM Page 118 Using PHP PART I This chapter explains how reusing code leads to more consistent, reliable, maintainable code, with less effort. We will demonstrate techniques for modularizing and reusing code, beginning with the simple use of require() and include() to use the same code on more than one page. We will explain why these are superior to server side includes. The example given will cover using include files to get a consistent look and feel across your site.
-
07 7842 CH05 3/6/01 3:35 PM Page 119 Reusing Code and Writing Functions CHAPTER 5 119 Reliability If a module of code is in use somewhere in your organization, it has presumably already been thoroughly tested. Even if it is only a few lines, there is a possibility that if you rewrite it, you will either overlook something that the original author incorporated or something that was added to the original code after a defect was found during testing.
-
07 7842 CH05 3/6/01 120 3:35 PM Page 120 Using PHP PART I If you load reusable.php, it probably won’t surprise you when “Here is a very simple PHP statement.” appears in your browser. If you load main.php, something a little more interesting happens. The output of this script is shown in Figure 5.1. FIGURE 5.1 The output of main.php shows the result of the require() statement. A file is needed to use a require() statement. In the preceding example, we are using the file named reusable.php.
-
07 7842 CH05 3/6/01 3:35 PM Page 121 Reusing Code and Writing Functions CHAPTER 5 121 Normally, PHP statements would not be processed if they were in a file called for example, page.html. PHP is usually only called upon to parse files with defined extensions such as .php. However, if you load this page.html via a require() statement, any PHP inside it will be processed.
-
07 7842 CH05 3/6/01 122 3:35 PM Page 122 Using PHP PART I FIGURE 5.2 TLA Consulting has a standard look and feel for all its Web pages. Directly reusing the sections of HTML that are common to all pages is a much better approach than cutting and pasting on tens, hundreds, or even thousands of pages. The source code for the homepage (home.html) shown in Figure 5.2 is given in Listing 5.1. LISTING 5.1 home.
-
07 7842 CH05 3/6/01 3:35 PM Page 123 Reusing Code and Writing Functions CHAPTER 5 LISTING 5.1 123 Continued
 | TLA Consulting |  |
-
07 7842 CH05 3/6/01 124 3:35 PM Page 124 Using PHP PART I You can see in Listing 5.1 that a number of distinct sections of code exist in this file. The HTML head contains Cascading Style Sheet (CSS) definitions used by the page. The section labeled “page header” displays the company name and logo, “menu bar” creates the page’s navigation bar, and “page content” is text unique to this page. Below that is the page footer. We can usefully split this file and name the parts header.inc, home.
-
07 7842 CH05 3/6/01 3:35 PM Page 125 Reusing Code and Writing Functions CHAPTER 5 LISTING 5.3 125 header.inc—The Reusable Header for All TLA Web Pages TLA Consulting Pty Ltd |