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 eagerly promiscuous when it comes to external applications and libraries. PHP can speak to a multitude of databases, and it knows numerous Internet protocols. PHP also makes it simple to parse form 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 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 Learning PHP 5, also from O'Reilly.
If you're already familiar with PHP, this book helps 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, such as 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 toward 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. Chpater 5 covers notable features of PHP's variable handling, such as default values, static variables, and producing string representations of complex data types. The recipes in Chpater 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 OOP basics as well as PHP 5's new features, such as magic methods, destructors, access control, and reflection.
The next three chapters are all about network interaction. Chapter 14 details the ins and outs of consuming a web service'using an external REST, SOAP, or XML-RPC service from within your code. Chapter 15 handles the other side of the web services equation'serving up REST, SOAP, or XML-RPC requests to others. Both chapters discuss WSDL, authentication, headers, and error handling. Chapter 16 discusses other network services such as sending email messages, using LDAP, and doing DNS lookups.
The next section of the book is a series of chapters on features and extensions of PHP that help you build applications that are robust, secure, user-friendly, and efficient. Chpater 17 shows you how to create graphics, with recipes on drawing text, lines, polygons, and curves. Chapter 18 focuses on security topics such as avoiding session fixation and cross-site scripting, working with passwords, and encrypting data. Chapter 19 helps you make your applications globally friendly and includes recipes localizing text, dates and times, currency values, and images, as well as working with text in different character encodings, including UTF-8. Chapter 20 goes into detail on error handling, debugging techniques, and writing tests for your code. Chapter 21 explains how to compare the performance of two functions and provides tips on getting your programs to run at maximum speed. Chapter 22 covers regular expressions, including capturing text inside of HTML tags, calling a PHP function from inside a regular expression, and using greedy and nongreedy matching.
Chapters 23 and 24 cover the filesystem. Chapter 23 focuses on files: opening and closing them, using temporary files, locking file, sending compressed files, and processing the contents of files. Chapter 24 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 25 covers using PHP outside of web programming. Its recipes cover command-line topics such as parsing program arguments and reading passwords. Chapter 26 covers PEAR (the PHP Extension and Application Repository) and PECL (the PHP Extension Community Library). PEAR is a collection of PHP code that provides functions and extensions to PHP. PECL is a similar collection, but of extensions to PHP written in C. We use PEAR and PECL modules throughout the book and Chapter 26 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:
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:
Conventions Used in This Book
The examples in this book were written to run under PHP version 5.1.4. Sample code should work on both Unix and Windows, except where noted in the text. We've generally noted in the text when we depend on a feature added to PHP after version 4.3.0 or 5.0.0.
We also call out when a feature will be available in an yet-to-be-unreleased version of PHP, including PHP 6. In those cases, please double check our code, as things can change during the development cycle.
The following typographic conventions are used in this book:
Comments and Questions
Please address comments and questions concerning this book to the publisher:
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, a huge 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: Wez Furlong, James Nash, and Mark Oglia.
Thanks to Chris Shiflett and Clay Loveless for their important contributions. Without Chris, Chapter 18 would be much slimmer. Without Clay, there'd be no Chapters 11, 20, 21, or 26. A special thanks to our tireless editor Tatiana Apandi. Her masterful synthesis of the iron fist and the velvet glove provided the necessary glue to orchestrate the successful completion of this edition. Without Tatiana, this book would have ended up as a 27-page pamphlet completed sometime in 2012.
Thanks once again to Adam. We've been working together (in one way or another) for 11 years and PHPing together for 10. There is no one with whom I'd rather have written this book (except, to be completely honest, maybe Ben Franklin, if he could somehow be brought back to life).
Thanks to the folks at Ning for providing (among other things) an opportunity to do fun things with PHP.
To my parents and my sister'thank you for your steady support and love, as well as for being unwitting test subjects when I need to try out explanations of technical things that I hope are intelligible to non-geeks.
For patience, inspiration, and a toad, thanks to Susannah, who continually amazes me.
I can't believe I've been using PHP for 10 years. I still remember the first time I used the language formerly known as PHP/FI. Writing web applications in PHP was so much easier than what I had used before that I immediately dumped everything else. The defining moment for me was when writing text to the error log didn't require a complicated sequence of steps involving file handles, but sending a string of text to function straightforwardly named error_log( ). Genius.
A big shout out to David. I would not'and could not'have written this without him. I, and PHP Cookbook, owe you a big debt of gratitude.
It's tough to complete with Ben Franklin. However, please know that I, too, support the turkey as the official animal of PHP.
Thanks to everyone at eBay for providing me with such a great opportunity to work with so many amazing people that make up the entire eBay community.
Thanks to my parents, family, and friends for their support and encouragement.
Thanks to Elizabeth Hondl. I love you so very much. Stay tuned for my next book, the Maritime Disaster Cookbook.
I would like to thank Adam Trachtenberg, David Sklar, Tatiana Apandi and the rest of the crew at O'Reilly for making this book possible, and for including me in the process. Special thanks to my wife, Kendra, and my son, Wade, for allowing the time for me to be included.
Thanks to Adam and David for writing such a great book and for giving me the opportunity to contribute.