PHP is the engine behind millions of dynamic web applications. Its broad feature set, approachable syntax, and support for different operating systems and web servers have made it an ideal language for both rapid web development and the methodical construction of complex systems.
One of the major reasons for PHP's success as a web scripting language is its origins as a tool to process HTML forms and create web pages. This makes PHP very web-friendly. Additionally, it is a polyglot. PHP can speak to a multitude of databases, and it knows numerous Internet protocols. PHP also makes it simple to parse browser data and make HTTP requests. This web-specific focus carries over to the recipes and examples in the PHP Cookbook.
This book is a collection of solutions to common tasks in PHP. We've tried to include material that will appeal to everyone from newbies to wizards. If we've succeeded, you'll learn something (or perhaps many things) from the PHP Cookbook. There are tips in here for everyday PHP programmers as well as for people coming to PHP with experience in another language.
PHP, in source-code and binary forms, is available for download for free from http://www.php.net/. The PHP web site also contains installation instructions, comprehensive documentation, and pointers to online resources, user groups, mailing lists, and other PHP resources.
Who This Book Is For
This book is for programmers who need to solve problems with PHP. If you don't know any PHP, make this your second PHP book. The first should be Programming PHP, also from O'Reilly & Associates.
If you're already familiar with PHP, this book will help you overcome a specific problem and get on with your life (or at least your programming activities.) The PHP Cookbook can also show you how to accomplish a particular task in PHP, like sending email or writing a SOAP server, that you may already know how to do in another language. Programmers converting applications from other languages to PHP will find this book a trusty companion.
What Is in This Book
We don't expect that you'll sit down and read this book from cover to cover. (although we'll be happy if you do!). PHP programmers are constantly faced with a wide variety of challenges on a wide range of subjects. Turn to the PHP Cookbook when you encounter a problem you need to solve. Each recipe is a self-contained explanation that gives you a head start towards finishing your task. When a recipe refers to topics outside its scope, it contains pointers to related recipes and other online and offline resources.
If you choose to read an entire chapter at once, that's okay. The recipes generally flow from easy to hard, with example programs that "put it all together" at the end of many chapters. The chapter introduction provides an overview of the material covered in the chapter, including relevant background material, and points out a few highlighted recipes of special interest.
The book begins with four chapters about basic data types. Chapter 1 covers details like processing substrings, manipulating case, taking strings apart into smaller pieces, and parsing comma-separated data. Chapter 2 explains operations with floating-point numbers, random numbers, converting between bases, and number formatting. Chapter 3 shows you how to manipulate dates and times, format them, handle time zones and daylight saving time, and find time to microsecond precision. Chapter 4 covers array operations like iterating, merging, reversing, sorting, and extracting particular elements.
Next are three chapters that discuss program building blocks. Chapter 5 covers notable features of PHP's variable handling, like default values, static variables, and producing string representations of complex data types. The recipes in Chapter 6 deal with using functions in PHP: processing arguments, passing and returning variables by reference, creating functions at runtime, and scoping variables. Chapter 7 covers PHP's object-oriented capabilities, with recipes on using overloading and polymorphism, defining constructors, and cloning objects.
The heart of the book is five chapters devoted to topics that are central to web programming. Chapter 8 covers cookies, headers, authentication, configuration variables, and other fundamentals of web applications. Chapter 9 covers processing and validating form input, displaying multi-page forms, showing forms with error messages, and escaping special characters in user data. Chapter 10 explains the differences between text-file, DBM, and SQL databases and, using the PEAR DB database abstraction layer, shows how to assign unique ID values, retrieve rows, change data, escape quotes, and log debugging information. Chapter 11 focuses on retrieving URLs and processing HTML but also touches on using templates and parsing server access logs. Chapter 12 covers XML and related formats, including the DOM, SAX, XSLT, XML-RPC, and SOAP.
The next section of the book is a series of chapters on other features and extensions of PHP that provide a lot of useful functionality. These are recipes that help you build applications that are more robust, secure, user-friendly, and efficient. Chapter 13 covers regular expressions, including matching a valid email address, capturing text inside of HTML tags, and using greedy or non-greedy matching. Chapter 14 discusses encryption, including generating and storing passwords, sharing encrypted data with others, storing encrypted data in a file or database, and using SSL. Chapter 15 shows you how to create graphics, with recipes on drawing text, lines, polygons, and curves. Chapter 16 helps you make your applications globally friendly and includes recipes on using locales and localizing text, dates and times, currency values, and images. Chapter 17 discusses network-related tasks, like reading and sending email messages and newsgroup posts, using FTP and LDAP, and doing DNS and Whois lookups.
Chapter 18 and Chapter 19 cover the filesystem. Chapter 18 focuses on files: opening and closing them, using temporary files, locking file, sending compressed files, and processing the contents of files. Chapter 19 deals with directories and file metadata, with recipes on changing file permissions and ownership, moving or deleting a file, and processing all files in a directory.
Last, there are two chapters on topics that extend the reach of what PHP can do. Chapter 20 covers using PHP outside of web programming. Its recipes cover command-line topics like parsing program arguments and reading passwords, as well as topics related to building client-side GUI applications with PHP-GTK like displaying widgets, responding to user actions, and displaying menus. Chapter 21 covers PEAR, the PHP Extension and Application Repository. PEAR is a collection of PHP code that provides various functions and extensions to PHP. We use PEAR modules throughout the book and Chapter 21 shows you how to install and upgrade them.
There is a tremendous amount of PHP reference material online. With everything from the annotated PHP manual to sites with periodic articles and tutorials, a fast Internet connection rivals a large bookshelf in PHP documentary usefulness. Here are some key sites:
- The Annotated PHP Manual
- Available in seventeen languages, this includes both official documentation of functions and language features as well as user-contributed comments.
- PHP mailing lists
- There are many PHP mailing lists covering installation, programming, extending PHP, and various other topics. A read-only web interface to the mailing lists is at http://news.php.net/.
- PHP Presentation archive
- A collection of presentations on PHP given at various conferences.
- PEAR calls itself "a framework and distribution system for reuseable PHP components." You'll find lots of useful PHP classes and sample code there.
- A Tourist's Guide: http://www.php.net/sites.php
- This is a guide to the various web sites under the php.net umbrella.
- PHP Knowledge Base
- Many questions and answers from the PHP community, as well as links to other resources.
- PHP DevCenter
- A collection of PHP articles and tutorials with a good mix of introductory and advanced topics.
This section lists books that are helpful references and tutorials for building applications with PHP. Most are specific to web-related programming; look for books on MySQL, HTML, XML, and HTTP.
At the end of the section, we've included a few books that are useful for every programmer regardless of language of choice. These works can make you a better programmer by teaching you how to think about programming as part of a larger pattern of problem solving.
- Programming PHP by Kevin Tatroe and Rasmus Lerdorf (O'Reilly).
- HTML and XHTML: The Definitive Guide by Chuck Musciano and Bill Kennedy (O'Reilly).
- Dynamic HTML: The Definitive Guide by Danny Goodman (O'Reilly).
- Mastering Regular Expressions by Jeffrey E. F. Friedl (O'Reilly).
- XML in a Nutshell by Elliotte Rusty Harold and W. Scott Means (O'Reilly).
- MySQL Reference Manual, by Michael "Monty" Widenius, David Axmark, and MySQL AB (O'Reilly); also available at http://www.mysql.com/documentation/.
- MySQL, by Paul DuBois (New Riders).
- Web Security, Privacy, and Commerce by Simson Garfinkel and Gene Spafford (O'Reilly).
- Web Services Essentials, by Ethan Cerami (O'Reilly).
- HTTP Pocket Reference, by Clinton Wong (O'Reilly).
- The Practice of Programming, by Brian W. Kernighan and Rob Pike (Addison-Wesley).
- Programming Pearls by Jon Louis Bentley (Addison-Wesley).
- The Mythical Man-Month, by Frederick P. Brooks (Addison-Wesley).
Conventions Used in This Book
We've generally omitted from examples in this book the <?php and ?> opening and closing markers that begin and end a PHP program, except in examples where the body of the code includes an opening or closing marker. To minimize naming conflicts, function and class names in the PHP Cookbook begin with pc_.
The examples in this book were written to run under PHP Version 4.2.2. Sample code should work on both Unix and Windows, except where noted in the text. Some functions, notably the XML-related ones, were written to run under PHP Version 4.3.0. We've noted in the text when we depend on a feature not present in PHP Version 4.2.2.
The following typographic conventions are used in this book:
- Used for file and directory names, email addresses, and URLs, as well as for new terms where they are defined.
- Constant width
- Used for code listings and for keywords, variables, functions, command options, parameters, class names, and HTML tags where they appear in the text.
- Constant width bold
- Used to mark lines of output in code listings and command lines to be typed by the user.
- Constant width italic
- Used as a general placeholder to indicate items that should be replaced by actual values in your own programs.
Comments and Questions
Please address comments and questions concerning this book to the publisher:
O'Reilly & Associates, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
(800) 998-9938 (in the United States or Canada)
(707) 829-0515 (international/local)
(707) 829-0104 (fax)
We have a web page for this book, where we list errata, examples, or any additional information. You can access this page at:
To comment or ask technical questions about this book, send email to:
For more information about books, conferences, Resource Centers, and the O'Reilly Network, see the O'Reilly web site at:
Most importantly, thanks to everyone who has contributed their time, creativity, and skills to making PHP what it is today. This amazing volunteer effort has created not only hundreds of thousands of lines of source code, but also comprehensive documentation, a QA infrastructure, lots of add-on applications and libraries, and a thriving user community worldwide. It's a thrill and an honor to add the PHP Cookbook to the world of PHP.
Thanks also to our reviewers: Stig Bakken, Shane Caraveo, Ike DeLorenzo, Rasmus Lerdorf, Adam Morton, Ophir Prusak, Kevin Tatroe, and Nathan Torkington. They caught plenty of bugs and offered many helpful suggestions for making the book better. We would like to specially single out Nat Torkington for flooding us with a plethora of useful changes and suggested additions.
All the folks at Student.Net Publishing, Student.Com, and TVGrid.Com provided a fertile environment for exploring PHP. Our experiences there in large part made this book possible. Bret Martin and Miranda Productions provided hosting and infrastructure that let us collaborate remotely while writing. We're only four miles from each other, but in Manhattan, that's remote.
Last, but far from least, thanks to our editor Paula Ferguson. From her shockingly quick (to our friends) acceptance of our modest book proposal to her final handling of our requests for last-minute revisions, she's guided the PHP Cookbook with a steady hand through the O'Reilly publishing process. Without her, this book would never have made the transformation from idea into reality.
Thanks to Adam for writing this book with me (and catching all the places I used too many parentheses).
Thanks to my parents, who didn't really know what they were getting into when they bought me that 4K Radio Shack Color Computer 20 years ago.
Thanks to Susannah for unwavering love and support, and for reminding me at crucial moments that life's not a paragraph.
It is hard to express the size of my debt to David for putting up with me over the course of working together on the PHP Cookbook. His comments drastically improved my writing and his unwavering punctuality helped keep me close to schedule.
Thanks to Coleco and its Adam computer, for making me the first kid on the block able to own a computer named after himself.
Thanks to all my friends and business-school classmates who grew tired of hearing me say "Sorry, I've got to go work on the book tonight" and who still talked to me after I took two weeks to return their phone calls.
A special thanks to Elizabeth Hondl. Her childlike fascination with web technologies proves that if you ask often enough, you just might make it in the book.
Thanks to my brother, parents, and entire family. So much of me comes from them. Their encouragement and love sustains me.