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 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.

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 submission of the same form. Chapter 10 explains the differences between DBM and SQL databases and, using PHP 5's 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 web site. This chapter also highlights some of the security issues associated with sessions. Chapter 12 discusses all things XML: PHP 5's SimpleXML extension and revamped 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 web sites 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, 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.

Other Resources

Web Sites

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: http://www.php.net/manual

Available in 17 languages, this site includes both official documentation of functions and language features as well as user-contributed comments.


PHP mailing lists: http://www.php.net/mailing-lists.php

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: http://talks.php.net

A collection of presentations on PHP given at various conferences.


PEAR: http://pear.php.net

PEAR calls itself "a framework and distribution system for reuseable PHP components." You'll find lots of useful PHP classes and sample code there. Read more about PEAR in Chapter 26.


PECL: http://pecl.php.net

PECL calls itself "a repository for PHP Extensions, providing a directory of all known extensions and hosting facilities for downloading and development of PHP extensions." Read more about PECL in Chapter 26.


PHP.net: 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: http://php.faqts.com

Many questions and answers from the PHP community, as well as links to other resources.


PHP DevCenter: http://www.onlamp.com/php

A collection of PHP articles and tutorials with a good mix of introductory and advanced topics.


Planet PHP: http://www.planet-php.net

An aggregation of blog posts by PHP developers and about PHP.


Zend Developer Zone: http://devzone.zend.com

A regularly updated collection of articles, tutorials, and code samples.


SitePoint Blogs on PHP: http://www.sitepoint.com/blogs/category/php

A good collection of information about and exploration of 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:

  • Learning PHP 5 by David Sklar (O'Reilly)

  • Upgrading to PHP 5 by Adam Trachtenberg (O'Reilly)

  • Programming PHP by Rasmus Lerdorf, Kevin Tatroe, and Peter MacIntyre (O'Reilly)

  • Essential PHP Tools by David Sklar (Apress)

  • Advanced PHP Programming by George Schlossnagle (Sams)

  • Extending and Embedding PHP by Sara Golemon (Sams)

  • 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)

  • 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

Programming Conventions

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.

Typesetting Conventions

The following typographic conventions are used in this book:


Italic

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 Media, 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:

http://www.oreilly.com/catalog/phpckbk2

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

bookquestions@oreilly.com

For more information about books, conferences, Resource Centers, and the O'Reilly Network, see the O'Reilly web site at:

http://www.oreilly.com

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: 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.

David Sklar

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.

Adam Trachtenberg

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.

Clay Loveless

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.

Chris Shiflett

Thanks to Adam and David for writing such a great book and for giving me the opportunity to contribute.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net