Preface

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 free from http://www.php.net/. The PHP website 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 parsing JSON, 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 OK. 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, such as 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 OOP basics as well as more advanced features, such as magic methods, destructors, access control, reflection, traits, and namespaces.

After the data types and building blocks come six chapters devoted to topics that are central to web programming. Chapter 8 covers cookies, headers, authentication, working with query strings, and other fundamentals of web applications. Chapter 9 covers processing and validating form input, displaying multipage forms, showing forms with error messages, and guarding against problems such as cross-site scripting and multiple submissions of the same form. Chapter 10 explains the differences between DBM and SQL databases and, using the PDO database access abstraction layer, shows how to connect to a database, assign unique ID values, retrieve rows, change data, escape quotes, and log debugging information. Chapter 11 covers PHP’s built-in sessions module, which lets you maintain information about a user as he moves from page to page on your website. This chapter also highlights some of the security issues associated with sessions. Chapter 12 discusses all things XML: the SimpleXML extension and DOM functions, using XPath and XSLT, and reading and writing both RSS and Atom feeds. Chapter 13 explores topics useful to PHP applications that integrate with external websites and client-side JavaScript such as retrieving remote URLs, cleaning up HTML, and responding to an Ajax request.

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 service from within your code. Chapter 15 handles the other side of the web services equation—serving up REST requests to others. Both chapters discuss 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. Chapter 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 for localizing text, dates and times, currency values, and images, as well as a recipe working with text in UTF-8 character encoding. Chapter 20 goes into detail on error handling and logging, while Chapter 21 discusses debugging techniques, writing tests for your code, and using PHP’s built-in web server. Chapter 22 explains how to compare the performance of two functions and provides tips on getting your programs to run at maximum speed. Chapter 23 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 24 and 25 cover the filesystem. Chapter 24 focuses on files: opening and closing them, using temporary files, locking files, sending compressed files, and processing the contents of files. Chapter 25 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 26 covers using PHP outside of web programming. Its recipes cover command-line topics such as parsing program arguments and reading passwords. Chapter 27 covers Composer, PEAR (PHP Extension and Application Repository), and PECL (PHP Extension Community Library). Composer and PEAR provide access to 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 27 shows you how to install and upgrade them.

Other Resources

Websites

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 11 languages, this site 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; there is also a read-only web interface to the mailing lists.
PHP support resources
This handy collection of support resources has information on PHP user groups, events, and other support channels.
Composer
Composer is a dependency manager for PHP that provides a structured way both to declare dependencies in your project and to install them.
PEAR
PEAR calls itself “a framework and distribution system for reusable PHP components.” You’ll find lots of useful PHP classes and sample code there. Read more about PEAR in Chapter 27.
PECL
PECL calls itself “a repository for PHP Extensions, providing a directory of extensions and hosting facilities for downloading and development of PHP extensions.” Read more about PECL in Chapter 27.
PHP.net: A Tourist’s Guide
This is a guide to the various websites under the php.net umbrella.
PHP: The Right Way
A quick reference that attempts to be a comprehensive source of PHP best practices. A great place to start if you’re wondering about the idiomatic way to do something in PHP.
Planet PHP
An aggregation of blog posts by PHP developers, about PHP.
SitePoint Blogs on PHP
A good collection of information that explores PHP.

Books

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

Programming Conventions

The examples in this book were written to run under PHP version 5.4.28 (and, where applicable, PHP 5.5.12). 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 in or after 5.5.

Some examples rely on the $php_errormsg variable, which is only available when the track_errors configuration directive is turned on.

Typesetting Conventions

The following typographic conventions are used in this book:

Italic
Used for commands, filenames, and example URLs. It is also used to define new terms when they first appear in the text.
Constant width
Used in code examples to show partial or complete PHP source code program listings. It is also used for class names, method names, variable names, and other fragments of PHP code.
Constant width bold
Used for user input, such as commands that you type on the command line.
Constant width italic
Shows text that should be replaced with user-supplied values or by values determined by context.

Comments and Questions

Please address comments and questions concerning this book to the publisher:

O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)

We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at http://bit.ly/phpckbk3.

To comment or ask technical questions about this book, send email to .

For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com.

Find us on Facebook: http://facebook.com/oreilly

Follow us on Twitter: http://twitter.com/oreillymedia

Watch us on YouTube: http://www.youtube.com/oreillymedia

Acknowledgments

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: Paul Huff, Peter MacIntyre, Simon MacIntyre, and Russ Uman. Special mention to Chris Shiflett and Clay Lovelace for their contributions to the second edition of this book.

And big thanks to the folks at O’Reilly that made this book a reality: Rachel Roumeliotis, Allyson MacDonald, Melanie Yarbrough, and Maria Gulick as well as the nameless orcs and dwarves that toil in the subterranean caverns of Sebastopol and Cambridge to make sure that the production process runs smoothly.

David Sklar

Thanks twice again to Adam. We’ve been working together (in one way or another) for 18 years and PHPing together for 17. There is still 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 my family members of all ages. You gave me the time and space to focus on the book. Now I will give you time and space to read the entire thing!

Adam Trachtenberg

David: It’s tough to complete with Ben Franklin. Please know that I support the turkey as the official animal of PHP instead of the elephant. Many thanks for your support over all these years, beginning long ago in the days of PHP/FI. Without you, this book would merely be a dream.

Thanks to my family and friends for their support and encouragement over these many months. All my love to my two sons, even the one who helped me relearn that human children don’t give you extensions after 40 weeks if your work on PHP Cookbook isn’t complete. Finally, special thanks to my wife Elizabeth Anne; I should take your good advice more often.

Get PHP Cookbook, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.