Programming PHP ,TITLE.18349 Page Iii Wednesday, March 13, 2002 11:52 AM
Total Page:16
File Type:pdf, Size:1020Kb
,TITLE.18349 Page i Wednesday, March 13, 2002 11:52 AM Programming PHP ,TITLE.18349 Page iii Wednesday, March 13, 2002 11:52 AM Programming PHP Rasmus Lerdorf and Kevin Tatroe with Bob Kaehms and Ric McGredy Beijing • Cambridge • Farnham • Köln • Paris • Sebastopol • Taipei • Tokyo ,COPYRIGHT.18224 Page iv Wednesday, March 13, 2002 11:52 AM Programming PHP by Rasmus Lerdorf and Kevin Tatroe with Bob Kaehms and Ric McGredy Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved. Printed in the United States of America. Published by O’Reilly & Associates, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly & Associates books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (safari.oreilly.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or [email protected]. Editors: Nathan Torkington and Paula Ferguson Production Editor: Rachel Wheeler Cover Designer: Ellie Volckhausen Interior Designer: Melanie Wang Printing History: March 2002: First Edition. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly & Associates, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly & Associates, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. The association between the image of a cuckoo and PHP is a trademark of O’Reilly & Associates, Inc. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. ISBN: 1-56592-610-2 [M] ,AUTHOR.COLO.18074 Page 1 Wednesday, March 13, 2002 11:52 AM About the Authors Rasmus Lerdorf was born in Godhavn/Qeqertarsuaq on Disco Island, off the coast of Greenland, in 1968. He has been dabbling with Unix-based solutions since 1985. He is known for having gotten the PHP project off the ground in 1995, and he can be blamed for the ANSI-92 SQL-defying LIMIT clause in mSQL 1.x, which has now, at least conceptually, crept into both MySQL and PostgreSQL. Rasmus tends to deny being a programmer, preferring to be seen as a techie who is adept at solving problems. If the solution requires a bit of coding and he can’t trick somebody else into writing the code, he will reluctantly give in and write it himself. He currently lives near San Francisco with his wife Christine. Kevin Tatroe has been a Macintosh and Unix programmer for 10 years. Being lazy, he’s attracted to languages and frameworks that do much of the work for you, such as the AppleScript, Perl, and PHP languages and the WebObjects and Cocoa programming environments. Kevin, his wife Jenn, his son Hadden, and their two cats live on the edge of the rural plains of Colorado, just far away enough from the mountains to avoid the worst snowfall, and just close enough to avoid tornadoes. The house is filled with LEGO creations, action figures, and numerous other toys. Bob Kaehms has spent most of his professional career working with computers. After a prolonged youth that he stretched into his late 20s as a professional scuba diver, ski patroller, and lifeguard, he went to work as a scientific programmer for Lockheed Missiles and Space Co. Frustrations with the lack of information-sharing within the defense industry led him first to groupware and then to the Web. Bob helped found the Internet Archive, where as Director of Computing he was responsible for the first full backup of all publicly available data on the Internet. Bob also served as Editor in Chief of Web Techniques Magazine, the leading technical magazine for web developers. He is presently CTO at Media Net Link, Inc. Bob has a degree in applied mathematics, and he uses that training to study the chaos that exists around his house. Ric McGredy founded Media Net Link, Inc. in 1994, after long stints at Bank of America, Apple Computer, and Sun Microsystems, to pursue excellence in customer- focused web-service construction and deployment. While he has been known to crank out a line or two of code, Ric prides himself first and foremost as being busi- ness-focused and on integrating technology into the business enterprise with high reliability at a reasonable cost. Ric received a BA in French from Ohio Wesleyan University and has been involved in the accounting and information-technology disciplines for over 25 years. Ric lives near San Francisco with his wife Sally and five children. ,AUTHOR.COLO.18074 Page 2 Wednesday, March 13, 2002 11:52 AM Colophon Our look is the result of reader comments, our own experimentation, and feedback from distribution channels. Distinctive covers complement our distinctive approach to technical topics, breathing personality and life into potentially dry subjects. The animal on the cover of Programming PHP is a cuckoo (Cuculus canorus). Cuckoos epitomize minimal effort. The common cuckoo doesn’t build a nest— instead, the female cuckoo finds another bird’s nest that already contains eggs and lays an egg in it (a process she may repeat up to 25 times, leaving 1 egg per nest). The nest mother rarely notices the addition, and usually incubates the egg and then feeds the hatchling as if it were her own. Why don’t nest mothers notice that the cuckoo’s eggs are different from their own? Recent research suggests that it’s because the eggs look the same in the ultraviolet spectrum, which birds can see. When they hatch, the baby cuckoos push all the other eggs out of the nest. If the other eggs hatched first, the babies are pushed out too. The host parents often continue to feed the cuckoo even after it grows to be much larger than they are, and cuckoo chicks sometimes use their call to lure other birds to feed them as well. Inter- estingly, only Old World (European) cuckoos colonize other nests—the New World (American) cuckoos build their own (untidy) nests. Like many Americans, these cuckoos migrate to the tropics for winter. Cuckoos have a long and glorious history in literature and the arts. The Bible mentions them, as do Pliny and Aristotle. Beethoven used the cuckoo’s distinctive call in his Pastoral Symphony. And here’s a bit of etymology for you: the word “cuckold” (a husband whose wife is cheating on him) comes from “cuckoo.” Presumably, the practice of laying one’s eggs in another’s nest seemed an appro- priate metaphor. Rachel Wheeler was the production editor and copyeditor for Programming PHP. Sue Willing and Jeffrey Holcomb provided quality control, and Sue Willing provided production assistance. Ellen Troutman-Zaig wrote the index. Ellie Volckhausen designed the cover of this book, based on a series design by Edie Freedman. The cover image is a 19th-century engraving from the Dover Pictorial Archive. Emma Colby produced the cover layout with QuarkXPress 4.1 using Adobe’s ITC Garamond font. Melanie Wang designed the interior layout, based on a series design by David Futato. Neil Walls converted the files from Microsoft Word to FrameMaker 5.5.6 using tools created by Mike Sierra. The text font is Linotype Birka; the heading font is Adobe Myriad Condensed; and the code font is LucasFont’s TheSans Mono Condensed. The illustrations that appear in the book were produced by Robert Romano and Jessamyn Read using Macromedia FreeHand 9 and Adobe Photoshop 6. This colophon was written by Nathan Torkington and Rachel Wheeler. ,progphpTOC.fm.17249 Page v Wednesday, March 13, 2002 11:46 AM Table of Contents Preface . ix 1. Introduction to PHP . 1 What Does PHP Do? 1 A Brief History of PHP 2 Installing PHP 7 A Walk Through PHP 9 2. Language Basics . 17 Lexical Structure 17 Data Types 23 Variables 30 Expressions and Operators 34 Flow-Control Statements 46 Including Code 54 Embedding PHP in Web Pages 56 3. Functions . 61 Calling a Function 61 Defining a Function 62 Variable Scope 64 Function Parameters 66 Return Values 69 Variable Functions 70 Anonymous Functions 71 4. Strings . 72 Quoting String Constants 72 Printing Strings 75 v ,progphpTOC.fm.17249 Page vi Wednesday, March 13, 2002 11:46 AM Accessing Individual Characters 79 Cleaning Strings 80 Encoding and Escaping 81 Comparing Strings 86 Manipulating and Searching Strings 89 Regular Expressions 95 POSIX-Style Regular Expressions 99 Perl-Compatible Regular Expressions 103 5. Arrays . 116 Indexed Versus Associative Arrays 116 Identifying Elements of an Array 117 Storing Data in Arrays 117 Multidimensional Arrays 120 Extracting Multiple Values 120 Converting Between Arrays and Variables 124 Traversing Arrays 125 Sorting 130 Acting on Entire Arrays 135 Using Arrays 136 6. Objects . 140 Terminology 141 Creating an Object 141 Accessing Properties and Methods 142 Declaring a Class 143 Introspection 147 Serialization 153 7. Web Techniques . 158 HTTP Basics 158 Variables 159 Server Information 160 Processing Forms 162 Setting Response Headers 175 Maintaining State 178 SSL 188 vi | Table of Contents ,progphpTOC.fm.17249 Page vii Wednesday, March 13, 2002 11:46 AM 8. Databases . 189 Using PHP to Access a Database 189 Relational Databases and SQL 190 PEAR DB Basics 192 Advanced Database Techniques 197 Sample Application 202 9. Graphics . 214 Embedding an Image in a Page 214 The GD Extension 215 Basic Graphics Concepts 216 Creating and Drawing Images 217 Images with Text 220 Dynamically Generated Buttons 223 Scaling Images 227 Color Handling 228 10. PDF . 233 PDF Extensions 233 Documents and Pages 233 Text 237 Images and Graphics 246 Navigation 255 Other PDF Features 259 11.