1 2 SAMS Teach Yourself PHP4 in 24 Hours Matt Zandstra A Division of Macmillan USA 201 West 103rd St., , Indianapolis, Indiana, 46290 . USA Copyright © 2000 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. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein. International Standard Book Number: 0-672-31804-0 Library of Congress Catalog Card Number: 99-65599 Printed in the United States of America First Printing: June 2000 03 02 01 00 4 3 2 1 All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Sams Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark. This publication was produced using the Advent 3B2 Publishing System. Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The information provided is on an "as is" basis. The author and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book or from the use of the programs accompanying it. Dedication For my father: Who would have approved. About the Author Matt Zandstra (<matt@corrosive.co.uk>) runs Corrosive Web Design (http://www.corrosive.co.uk) with his business partner Max Guglielmino. A compulsive scripter, he has developed software in PHP, Java, JavaScript, Perl, Lingo, and AppleScript. Matt 3 originally graduated in philosophy and has learned his trade by reinventing wheels and then working out why they don't run straight. Matt has taught courses in HTML, JavaScript, Perl, and PHP and was a contributing author to Dynamic HTML Unleashed. When not coding, Matt is a committed urban cyclist, a Guinness drinker, an obsessive reader, and a writer of unpublishable short stories. One day he claims he will write a novel. 4 Acknowledgments The open source concept made both my career and this book possible. I would like to thank all those people whose voluntary efforts continue to defy the received wisdom. Particular thanks to the PHP community, especially contributors to the PHP mailing lists whose postings revealed pitfalls, suggested techniques, and kept me amused. From Macmillan, I would like to thank Randi Roger for suggesting me for this project as well as Jeff Schultz, Paul Schneider, and Scott Meyers for support and tolerance as deadlines loomed and panic set in. Thanks must also go to all at Corrosive for putting up with my continued absence and my extreme vagueness on any matter not pertaining to PHP. In particular, my business partner Massimo Guglielmino, who kept the Corrosive show on the road under the usual stressful circumstances, and Dave Urmson, who took over formatting when the going got tough. Other Corrosive stars include Anisa Swaffield, Jeff Coburn, Mai Chokelumlerd, and Moira Govern. I must also thank Small Planet (http://www.smallpla.net) for providing me with additional development space and allowing me to use it to play with beta software. Particular thanks to Mohammed Abba and Clive Hills, who recompiled PHP on the Small Planet system more times than we care to remember. One of the best ways to test a tutorial text is to use it in class. Thanks to my PHP students who graciously agreed to act as guinea pigs. Thanks also to my partner Louise and our new daughter Holly for being there, and bearing the grumpy, hunched, and obsessed character I became while writing this book. As my social life took second place to PHP, my local became a refuge for last minute pint and proofing sessions. Thanks to Alan and Dora of the Prince Arthur for running the perfect pub. Finally, thanks to the fishes, who cheered up a lurker. 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 fax, email, or write me directly to let me know what you did or didn't like about this book— as well as what we can do to make our books stronger. Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able to reply to every message. When you write, please be sure to include this book's title and author as well as your name and phone or fax number. I will carefully review your comments and share them with the author and editors who worked on the book. Fax: 317-581-4770 5 Email: <webdev_sams@mcp.com> Mail: Mark Taber Associate Publisher Sams Publishing 201 West 103rd Street Indianapolis, IN 46290 USA 6 Introduction This is a book about PHP, the open source Web scripting language that has joined Perl, ASP, and Java on the select list of languages that can be used to create dynamic online environments. It is also a book about programming. In the space available, it is neither possible to create a complete guide to programming in PHP nor to cover every function and technique that PHP offers. Nevertheless, whether you are an experienced programmer considering a move to PHP or a newcomer to scripting, the steps in this book should provide enough information to get your journey off to a good start. Who Should Read This Book? This book will take you from the first principles through to a good working knowledge of the PHP4 programming language. No prior experience of programming is assumed, though if you have worked with a language such as C or Perl in the past, you will find the going much easier. PHP4 is a Web programming language. To get the most from this book, you should have some understanding of the World Wide Web and of HTML in particular. If you are just starting out, you will still be able to use this book, though you should consider acquiring an HTML tutorial. If you are comfortable creating basic documents and can build a basic HTML table, you will be fine. PHP4 is designed to integrate well with databases. Some of the examples in this book are written to work with MySQL, a SQL database that is free for personal use on some platforms. We include a short introduction to SQL, but if you intend to use PHP to work with databases, you might want to spend some time reading up on the subject. Numerous introductory SQL tutorials are available online. If you intend to work with a database other than MySQL, many of the examples in this book will be relatively easy to reproduce with the equivalent PHP functions designed to query your database. How This Book Is Organized This book is divided into four parts: Part 1 is an introduction to PHP4. Part 2 covers the basic features of the language. Pay particular attention to this section if you are new to programming. 7 Part 3 covers PHP4 in more detail, looking at the functions and techniques you will need to become a proficient PHP programmer. Part 4 illustrates a complete self-contained example. Part 1 contains Hours 1 through 3 and handles the information you will need to get your first script up and running: Hour 1, "PHP: From Home Page to Portal," describes the history and capabilities of PHP and looks at some of the compelling reasons for deciding to learn this scripting language. Hour 2, "Installing PHP," explains how to install PHP on a UNIX system and discusses some of the configuration options you might want to choose when compiling PHP. In this hour, we also look at PHP configuration options. Hour 3, "A First Script," looks at the different ways in which you can embed a PHP script in a document and create a script that writes text to the user's browser. Part 2 comprises Hours 4 through 8. In this part, you will learn the basic components of the PHP language: Hour 4, "The Building Blocks," covers the basics of PHP. You will learn about variables, data types, operators, and expressions. Hour 5, "Going with the Flow," covers the syntax for controlling program flow in your scripts. In addition to if and switch constructs, you will learn about loops using for and while statements. Hour 6, "Functions," explores the use of functions to organize your code. Hour 7, "Arrays," discusses the array data type that can be used to hold list information. We will also look at some of the functions that PHP4 provides to manipulate arrays. Hour 8, "Objects," introduces PHP4's support for classes and objects. Throughout the course of the hour, we will develop a working example. Part 3 consists of Hours 9 through 22. In this part, you will come to grips with the features and techniques of the language: Hour 9, "Working with Forms," introduces the dimension of user input through the mechanism of the HTML form. You will learn how to gather data submitted via a form. Hour 10, "Working with Files," shows you how to work with files and directories on the local machine. Hour 11, "Working with the DBM Functions," demonstrates PHP4's support for DBM database systems, versions of which are available on most systems. Hour 12, "Database Integration— MySQL," provides a brief introduction to SQL syntax and introduces the PHP4 functions that can be used to work with the MySQL database. Hour 13, "Beyond the Box," covers some of the details of HTTP requests and looks at PHP network functions. 8 Hour 14, "Working with Dynamic Images" explores PHP's image functions. With these, you can create GIF or PNG files dynamically. Hour 15, "Working with Dates," covers the functions and techniques you can use for date arithmetic. We create a calendar example. Hour 16, "Working with Data," revisits data types and explores some more of the functions you can use to work with data in your scripts. More array functions are also covered. Hour 17, "Working with Strings," covers the functions that you can use to manipulate strings. Hour 18, "Working with Regular Expressions," introduces regular expression functions. You can use these to find and replace complex patterns in strings. Hour 19, "Saving State with Cookies and Query Strings," shows you some techniques for passing information across scripts and requests. Hour 20, "Saving State with Session Functions," extends the techniques explored in Hour 19, using PHP4's built-in session functions. Hour 21, "Working with the Server Environment," shows you how to call external programs from your scripts and incorporate their output into your own. Hour 22, "Debugging," shows you some techniques that you can use to track down problems in your code. We also examine some common errors. Part 4 consists of Hours 23 and 24. In these, we build a working example that incorporates some of the techniques that were introduced earlier in the book. Hour 23, "An Example (Part 1)," creates a brief for a club listings script. We build the code that will allow users to create accounts and enter listings. Hour 24, "An Example (Part 2)," concludes the project, building the code for nonmembers to browse the listings and look at club profiles. 9 SAMS Teach Yourself PHP4 in 24 Hours 2 Acknowledgments 4 Tell Us What You Think! 4 Introduction 6 Who Should Read This Book? 6 How This Book Is Organized 6 Hour 1: PHP: From Home Page to Portal 22 Overview 22 What Is PHP? 22 How Did PHP Evolve? 23 What's New in PHP4 24 The Zend Engine 24 Why Choose PHP? 25 Speed of Development 25 PHP Is Open Source 26 Performance 26 Portability 26 Summary 27 Q&A 27 Workshop 27 Quiz 27 Activity 28 Hour 2: Installing PHP 29 Overview 29 Platforms, Servers, Databases, and PHP 29 Where to Find PHP and More 30 Installing PHP4 for Linux and Apache 30 Some configure Options 32 enable-track-vars 32 with-gd 32 with-mysql 33 Configuring Apache 33 php.ini 34 short_open_tag 35 Error Reporting Directives 35 10 Variable Directives 36 Help! 36 Summary 38 Q&A 38 Workshop 38 Quiz 38 Activity 39 Hour 3: A First Script 40 Overview 40 Our First Script 40 Beginning and Ending a Block of PHP Statements 42 The print() Function 44 Combining HTML and PHP 44 Adding Comments to PHP Code 46 Summary 47 Q&A 47 Workshop 47 Quiz 48 Activity 48 Hour 4: The Building Blocks 49 Overview 49 Variables 49 Dynamic Variables 50 References to Variables 52 Data Types 53 Changing Type with settype() 55 Changing Type by Casting 57 Operators and Expressions 58 The Assignment Operator 59 Arithmetic Operators 59 The Concatenation Operator 60 More Assignment Operators 60 Comparison Operators 61 Creating More Complex Test Expressions with the Logical Operators 62 Automatically Incrementing and Decrementing an Integer Variable 63 Operator Precedence 65 [...]... Function 11 1 Directly Defining or Adding to an Associative Array 11 1 Multidimensional Arrays 11 2 Accessing Arrays 11 3 Getting the Size of an Array 11 3 Looping Through an Array 11 4 Looping Through an Associative Array 11 5 Outputting a Multidimensional Array 11 6 Manipulating Arrays 118 Joining Two Arrays with array_merge() 11 9 Adding Multiple Variables to an Array with array_push() 11 9 Removing the First... Activities 312 Hour 17 : Working with Strings 313 Overview 313 Formatting Strings 313 Working with printf() 313 printf() and Type Specifiers 314 Padding Output with the Padding Specifier 317 18 Specifying a Field Width 318 Specifying Precision 319 Conversion Specifications: A Recap 320 Storing a Formatted String 322 Investigating Strings 323 A Note About Indexing Strings 323 Finding the Length of a String with... Associative Array 15 9 Distinguishing Between GET and POST Transactions 16 1 Combining HTML and PHP Code on a Single Page 16 2 Using Hidden Fields to Save State 16 5 14 Redirecting the User 16 7 File Upload Forms and Scripts 16 9 Summary 17 3 Q&A 17 3 Workshop 17 3 Quiz 17 4 Activities 17 4 Hour 10 : Working with Files Overview 17 5 17 5 Including Files with include() 17 5 Testing Files 17 8 Checking for Existence... Workshop 19 4 Quiz 19 4 Activities 19 5 Hour 11 : Working with the DBM Functions 19 6 15 Overview 19 6 Opening a DBM Database 19 6 Adding Data to the Database 19 7 Amending Elements in a Database 19 8 Reading from a DBM Database 19 9 Determining Whether an Item Exists in a Database 2 01 Deleting an Item from a Database 2 01 Adding Complex Data Structures to a DBM Database 2 01 An Example205 Summary 211 Q&A 211 Workshop... Workshop 211 Quiz 211 Activities 212 Hour 12 : Database Integration— MySQL 213 Overview 213 A (Very) Brief Introduction to SQL 213 Connecting to the Database Server 214 Selecting a Database 215 Finding Out About Errors 215 Adding Data to a Table 216 Acquiring the Value of an Automatically Incremented Field 220 Accessing Information 2 21 Finding the Number of Rows Found by a Query 2 21 Accessing a Resultset... Example132 Defining the Class's Properties 13 3 Creating a Constructor 13 3 The addRow() Method 13 4 The addRowAssocArray() Method 13 4 The output() Method 13 5 Bringing It All Together 13 6 What's Missing ?13 9 Why a Class? 13 9 Inheritance 14 0 Overriding the Method of a Parent Class 14 1 Calling an Overridden Method 14 3 Inheritance: An Example 14 4 Defining HTMLTable's Properties144 Creating the Constructor 14 5... Debugging 4 01 Overview 4 01 Getting Information About PHP and Your Script 4 01 phpinfo() 4 01 Viewing Source with Syntax Coloring 405 PHP Error Messages 407 Writing Error Messages to a Log File 410 Getting the Error String 412 Manual Debugging 412 Common Errors 414 Summary 416 Q&A 417 Workshop 417 Quiz 417 Activity 417 Hour 23: An Example (Part 1) 418 Overview 418 The Brief 418 The Structure 418 Designing... More About Arguments 10 0 Setting Default Values for Arguments 10 0 Passing References to Variables to Functions 10 2 12 Summary 10 5 Q&A 10 5 Workshop 10 5 Quiz 10 6 Activity 10 7 Hour 7: Arrays 10 8 Overview 10 8 What Is an Array? 10 8 Creating Arrays 10 9 Defining Arrays with the array() Function 10 9 Defining or Adding to Arrays with the Array Identifier 11 0 Associative Arrays 11 0 Defining Associative Arrays... array_shift() 12 0 Slicing Arrays with array_slice() Sorting Arrays 12 2 12 1 Sorting Numerically Indexed Arrays with sort() 12 2 Sorting an Associative Array by Value with asort() 12 3 Sorting an Associative Array by Key with ksort() 12 3 Summary 12 4 Q&A 12 4 Workshop 12 5 Quiz 12 5 Activities 12 5 Hour 8: Objects126 Overview 12 6 13 What Is an Object? 12 6 Creating an Object 12 7 Object Properties 12 8 Object Methods 12 9... file_exists() 17 9 A File or a Directory? 17 9 Checking the Status of a File 17 9 Determining File Size with filesize() 18 0 Getting Date Information About a File 18 0 Creating a Function That Performs Multiple File Tests 18 1 Creating and Deleting Files 18 3 Opening a File for Writing, Reading, or Appending 18 3 Reading from Files 18 4 Reading Lines from a File with fgets() and feof() 18 5 Reading Arbitrary . Associative Array 11 1 Multidimensional Arrays 11 2 Accessing Arrays 11 3 Getting the Size of an Array 11 3 Looping Through an Array 11 4 Looping Through an Associative Array 11 5 Outputting a Multidimensional. 311 Activities 312 Hour 17 : Working with Strings 313 Overview 313 Formatting Strings 313 Working with printf() 313 printf() and Type Specifiers 314 Padding Output with the Padding. 205 Summary 211 Q&A 211 Workshop 211 Quiz 211 Activities 212 Hour 12 : Database Integration— MySQL 213 Overview 213 A (Very) Brief Introduction to SQL 213 Connecting to the Database