PHP Cookbook


PHP Cookbook The PHP Cookbook is a collection of problems, solutions, and practical examples for PHP programmers. The book contains a unique and extensive collection of best practices for everyday PHP programming dilemmas. It contains over 250 recipes, ranging from simple tasks to entire programs that demonstrate complex tasks, such as printing HTML tables and generating bar charts — a treasure trove of useful code for PHP programmers, from novices to advanced practitioners. 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 hapter 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.


Copyright Preface

    Who This Book Is For What Is in This Book Other Resources Conventions Used in This Book Comments and Questions Acknowledgments

Chapter 1. Strings

    Section 1.1. Introduction Recipe 1.2. Accessing Substrings Recipe 1.3. Replacing Substrings Recipe 1.4. Processing a String One Character at a Time Recipe 1.5. Reversing a String by Word or Character Recipe 1.6. Expanding and Compressing Tabs Recipe 1.7. Controlling Case Recipe 1.8. Interpolating Functions and Expressions Within Strings Recipe 1.9. Trimming Blanks from a String Recipe 1.10. Parsing Comma-Separated Data Recipe 1.11. Parsing Fixed-Width Delimited Data Recipe 1.12. Taking Strings Apart Recipe 1.13. Wrapping Text at a Certain Line Length Recipe 1.14. Storing Binary Data in Strings

Chapter 2. Numbers

    Section 2.1. Introduction Recipe 2.2. Checking Whether a String Contains a Valid Number Recipe 2.3. Comparing Floating-Point Numbers Recipe 2.4. Rounding Floating-Point Numbers Recipe 2.5. Operating on a Series of Integers Recipe 2.6. Generating Random Numbers Within a Range Recipe 2.7. Generating Biased Random Numbers Recipe 2.8. Taking Logarithms Recipe 2.9. Calculating Exponents Recipe 2.10. Formatting Numbers Recipe 2.11. Printing Correct Plurals Recipe 2.12. Calculating Trigonometric Functions Recipe 2.13. Doing Trigonometry in Degrees, not Radians Recipe 2.14. Handling Very Large or Very Small Numbers Recipe 2.15. Converting Between Bases Recipe 2.16. Calculating Using Numbers in Bases Other Than Decimal

Chapter 3. Dates and Times

    Section 3.1. Introduction Recipe 3.2. Finding the Current Date and Time Recipe 3.3. Converting Time and Date Parts to an Epoch Timestamp Recipe 3.4. Converting an Epoch Timestamp to Time and Date Parts Recipe 3.5. Printing a Date or Time in a Specified Format Recipe 3.6. Finding the Difference of Two Dates Recipe 3.7. Finding the Difference of Two Dates with Julian Days Recipe 3.8. Finding the Day in a Week, Month, Year, or the Week Number in a Year Recipe 3.9. Validating a Date Recipe 3.10. Parsing Dates and Times from Strings Recipe 3.11. Adding to or Subtracting from a Date Recipe 3.12. Calculating Time with Time Zones Recipe 3.13. Accounting for Daylight Saving Time Recipe 3.14. Generating a High-Precision Time Recipe 3.15. Generating Time Ranges Recipe 3.16. Using Non-Gregorian Calendars Recipe 3.17. Program: Calendar

Chapter 4. Arrays

    Section 4.1. Introduction Recipe 4.2. Specifying an Array Not Beginning at Element 0 Recipe 4.3. Storing Multiple Elements per Key in an Array Recipe 4.4. Initializing an Array to a Range of Integers Recipe 4.5. Iterating Through an Array Recipe 4.6. Deleting Elements from an Array Recipe 4.7. Changing Array Size Recipe 4.8. Appending One Array to Another Recipe 4.9. Turning an Array into a String Recipe 4.10. Printing an Array with Commas Recipe 4.11. Checking if a Key Is in an Array Recipe 4.12. Checking if an Element Is in an Array Recipe 4.13. Finding the Position of an Element in an Array Recipe 4.14. Finding Elements That Pass a Certain Test Recipe 4.15. Finding the Largest or Smallest Valued Element in an Array Recipe 4.16. Reversing an Array Recipe 4.17. Sorting an Array Recipe 4.18. Sorting an Array by a Computable Field Recipe 4.19. Sorting Multiple Arrays Recipe 4.20. Sorting an Array Using a Method Instead of a Function Recipe 4.21. Randomizing an Array Recipe 4.22. Shuffling a Deck of Cards Recipe 4.23. Removing Duplicate Elements from an Array Recipe 4.24. Finding the Union, Intersection, or Difference of Two Arrays Recipe 4.25. Finding All Element Combinations of an Array Recipe 4.26. Finding All Permutations of an Array Recipe 4.27. Program: Printing an Array in a Horizontally Columned HTML Table

Chapter 5. Variables

    Section 5.1. Introduction Recipe 5.2. Avoiding == Versus = Confusion Recipe 5.3. Establishing a Default Value Recipe 5.4. Exchanging Values Without Using Temporary Variables Recipe 5.5. Creating a Dynamic Variable Name Recipe 5.6. Using Static Variables Recipe 5.7. Sharing Variables Between Processes Recipe 5.8. Encapsulating Complex Data Types as a String Recipe 5.9. Dumping Variable Contents as Strings

Chapter 6. Functions

    Section 6.1. Introduction Recipe 6.2. Accessing Function Parameters Recipe 6.3. Setting Default Values for Function Parameters Recipe 6.4. Passing Values by Reference Recipe 6.5. Using Named Parameters Recipe 6.6. Creating Functions That Take a Variable Number of Arguments Recipe 6.7. Returning Values by Reference Recipe 6.8. Returning More Than One Value Recipe 6.9. Skipping Selected Return Values Recipe 6.10. Returning Failure Recipe 6.11. Calling Variable Functions Recipe 6.12. Accessing a Global Variable Inside a Function Recipe 6.13. Creating Dynamic Functions

Chapter 7. Classes and Objects

    Section 7.1. Introduction Recipe 7.2. Instantiating Objects Recipe 7.3. Defining Object Constructors Recipe 7.4. Destroying an Object Recipe 7.5. Cloning Objects Recipe 7.6. Assigning Object References Recipe 7.7. Calling Methods on an Object Returned by Another Method Recipe 7.8. Accessing Overridden Methods Recipe 7.9. Using Property Overloading Recipe 7.10. Using Method Polymorphism Recipe 7.11. Finding the Methods and Properties of an Object Recipe 7.12. Adding Properties to a Base Object Recipe 7.13. Creating a Class Dynamically Recipe 7.14. Instantiating an Object Dynamically

Chapter 8. Web Basics

    Section 8.1. Introduction Recipe 8.2. Setting Cookies Recipe 8.3. Reading Cookie Values Recipe 8.4. Deleting Cookies Recipe 8.5. Redirecting to a Different Location Recipe 8.6. Using Session Tracking Recipe 8.7. Storing Sessions in a Database Recipe 8.8. Detecting Different Browsers Recipe 8.9. Building a GET Query String Recipe 8.10. Using HTTP Basic Authentication Recipe 8.11. Using Cookie Authentication Recipe 8.12. Flushing Output to the Browser Recipe 8.13. Buffering Output to the Browser Recipe 8.14. Compressing Web Output with gzip Recipe 8.15. Hiding Error Messages from Users Recipe 8.16. Tuning Error Handling Recipe 8.17. Using a Custom Error Handler Recipe 8.18. Logging Errors Recipe 8.19. Eliminating “headers already sent” Errors Recipe 8.20. Logging Debugging Information Recipe 8.21. Reading Environment Variables Recipe 8.22. Setting Environment Variables Recipe 8.23. Reading Configuration Variables Recipe 8.24. Setting Configuration Variables Recipe 8.25. Communicating Within Apache Recipe 8.26. Profiling Code Recipe 8.27. Program: Website Account (De)activator Recipe 8.28. Program: Abusive User Checker

Chapter 9. Forms

    Section 9.1. Introduction Recipe 9.2. Processing Form Input Recipe 9.3. Validating Form Input Recipe 9.4. Working with Multipage Forms Recipe 9.5. Redisplaying Forms with Preserved Information and Error Messages Recipe 9.6. Guarding Against Multiple Submission of the Same Form Recipe 9.7. Processing Uploaded Files Recipe 9.8. Securing PHP’s Form Processing Recipe 9.9. Escaping Control Characters from User Data Recipe 9.10. Handling Remote Variables with Periods in Their Names Recipe 9.11. Using Form Elements with Multiple Options Recipe 9.12. Creating Dropdown Menus Based on the Current Date

Chapter 10. Database Access

    Section 10.1. Introduction Recipe 10.2. Using Text-File Databases Recipe 10.3. Using DBM Databases Recipe 10.4. Connecting to a SQL Database Recipe 10.5. Querying a SQL Database Recipe 10.6. Retrieving Rows Without a Loop Recipe 10.7. Modifying Data in a SQL Database Recipe 10.8. Repeating Queries Efficiently Recipe 10.9. Finding the Number of Rows Returned by a Query Recipe 10.10. Escaping Quotes Recipe 10.11. Logging Debugging Information and Errors Recipe 10.12. Assigning Unique ID Values Automatically Recipe 10.13. Building Queries Programmatically Recipe 10.14. Making Paginated Links for a Series of Records Recipe 10.15. Caching Queries and Results Recipe 10.16. Program: Storing a Threaded Message Board

Chapter 11. Web Automation

    Section 11.1. Introduction Recipe 11.2. Fetching a URL with the GET Method Recipe 11.3. Fetching a URL with the POST Method Recipe 11.4. Fetching a URL with Cookies Recipe 11.5. Fetching a URL with Headers Recipe 11.6. Fetching an HTTPS URL Recipe 11.7. Debugging the Raw HTTP Exchange Recipe 11.8. Marking Up a Web Page Recipe 11.9. Extracting Links from an HTML File Recipe 11.10. Converting ASCII to HTML Recipe 11.11. Converting HTML to ASCII Recipe 11.12. Removing HTML and PHP Tags Recipe 11.13. Using Smarty Templates Recipe 11.14. Parsing a Web Server Log File Recipe 11.15. Program: Finding Stale Links Recipe 11.16. Program: Finding Fresh Links Chapter 12. XML Section 12.1. Introduction Recipe 12.2. Generating XML Manually Recipe 12.3. Generating XML with the DOM Recipe 12.4. Parsing XML with the DOM Recipe 12.5. Parsing XML with SAX Recipe 12.6. Transforming XML with XSLT Recipe 12.7. Sending XML-RPC Requests Recipe 12.8. Receiving XML-RPC Requests Recipe 12.9. Sending SOAP Requests Recipe 12.10. Receiving SOAP Requests Recipe 12.11. Exchanging Data with WDDX Recipe 12.12. Reading RSS Feeds Chapter 13. Regular Expressions Section 13.1. Introduction Recipe 13.2. Switching From ereg to preg Recipe 13.3. Matching Words Recipe 13.4. Finding the nth Occurrence of a Match Recipe 13.5. Choosing Greedy or Nongreedy Matches Recipe 13.6. Matching a Valid Email Address Recipe 13.7. Finding All Lines in a File That Match a Pattern Recipe 13.8. Capturing Text Inside HTML Tags Recipe 13.9. Escaping Special Characters in a Regular Expression Recipe 13.10. Reading Records with a Pattern Separator

Chapter 14. Encryption and Security

    Section 14.1. Introduction Recipe 14.2. Keeping Passwords Out of Your Site Files Recipe 14.3. Obscuring Data with Encoding Recipe 14.4. Verifying Data with Hashes Recipe 14.5. Storing Passwords Recipe 14.6. Checking Password Strength Recipe 14.7. Dealing with Lost Passwords Recipe 14.8. Encrypting and Decrypting Data Recipe 14.9. Storing Encrypted Data in a File or Database Recipe 14.10. Sharing Encrypted Data with Another Web Site Recipe 14.11. Detecting SSL Recipe 14.12. Encrypting Email with GPG

Chapter 15. Graphics

    Section 15.1. Introduction Recipe 15.2. Drawing Lines, Rectangles, and Polygons Recipe 15.3. Drawing Arcs, Ellipses, and Circles Recipe 15.4. Drawing with Patterned Lines Recipe 15.5. Drawing Text Recipe 15.6. Drawing Centered Text Recipe 15.7. Building Dynamic Images Recipe 15.8. Getting and Setting a Transparent Color Recipe 15.9. Serving Images Securely Recipe 15.10. Program: Generating Bar Charts from Poll Results

Chapter 16. Internationalization and Localization

    Section 16.1. Introduction Recipe 16.2. Listing Available Locales Recipe 16.3. Using a Particular Locale Recipe 16.4. Setting the Default Locale Recipe 16.5. Localizing Text Messages Recipe 16.6. Localizing Dates and Times Recipe 16.7. Localizing Currency Values Recipe 16.8. Localizing Images Recipe 16.9. Localizing Included Files Recipe 16.10. Managing Localization Resources Recipe 16.11. Using gettext Recipe 16.12. Reading or Writing Unicode Characters
    Chapter 17. Internet Services Section 17.1. Introduction Recipe 17.2. Sending Mail Recipe 17.3. Sending MIME Mail Recipe 17.4. Reading Mail with IMAP or POP3 Recipe 17.5. Posting Messages to Usenet Newsgroups Recipe 17.6. Reading Usenet News Messages Recipe 17.7. Getting and Putting Files with FTP Recipe 17.8. Looking Up Addresses with LDAP Recipe 17.9. Using LDAP for User Authentication Recipe 17.10. Performing DNS Lookups Recipe 17.11. Checking if a Host Is Alive Recipe 17.12. Getting Information About a Domain Name

Chapter 18. Files

    Section 18.1. Introduction Recipe 18.2. Creating or Opening a Local File Recipe 18.3. Creating a Temporary File Recipe 18.4. Opening a Remote File Recipe 18.5. Reading from Standard Input Recipe 18.6. Reading a File into a String Recipe 18.7. Counting Lines, Paragraphs, or Records in a File Recipe 18.8. Processing Every Word in a File Recipe 18.9. Reading a Particular Line in a File Recipe 18.10. Processing a File Backward by Line or Paragraph Recipe 18.11. Picking a Random Line from a File Recipe 18.12. Randomizing All Lines in a File Recipe 18.13. Processing Variable Length Text Fields Recipe 18.14. Reading Configuration Files Recipe 18.15. Reading from or Writing to a Specific Location in a File Recipe 18.16. Removing the Last Line of a File Recipe 18.17. Modifying a File in Place Without a Temporary File Recipe 18.18. Flushing Output to a File Recipe 18.19. Writing to Standard Output Recipe 18.20. Writing to Many Filehandles Simultaneously Recipe 18.21. Escaping Shell Metacharacters Recipe 18.22. Passing Input to a Program Recipe 18.23. Reading Standard Output from a Program Recipe 18.24. Reading Standard Error from a Program Recipe 18.25. Locking a File Recipe 18.26. Reading and Writing Compressed Files Recipe 18.27. Program: Unzip

Chapter 19. Directories

    Section 19.1. Introduction Recipe 19.2. Getting and Setting File Timestamps Recipe 19.3. Getting File Information Recipe 19.4. Changing File Permissions or Ownership Recipe 19.5. Splitting a Filename into Its Component Parts Recipe 19.6. Deleting a File Recipe 19.7. Copying or Moving a File Recipe 19.8. Processing All Files in a Directory Recipe 19.9. Getting a List of Filenames Matching a Pattern Recipe 19.10. Processing All Files in a Directory Recipe 19.11. Making New Directories Recipe 19.12. Removing a Directory and Its Contents Recipe 19.13. Program: Web Server Directory Listing Recipe 19.14. Program: Site Search

Chapter 20. Client-Side PHP

    Section 20.1. Introduction Recipe 20.2. Parsing Program Arguments Recipe 20.3. Parsing Program Arguments with getopt Recipe 20.4. Reading from the Keyboard Recipe 20.5. Reading Passwords Recipe 20.6. Displaying a GUI Widget in a Window Recipe 20.7. Displaying Multiple GUI Widgets in a Window Recipe 20.8. Responding to User Actions Recipe 20.9. Displaying Menus Recipe 20.10. Program: Command Shell Recipe 20.11. Program: Displaying Weather Conditions

Chapter 21. PEAR

    Section 21.1. Introduction Recipe 21.2. Using the PEAR Package Manager Recipe 21.3. Finding PEAR Packages Recipe 21.4. Finding Information About a Package Recipe 21.5. Installing PEAR Packages Recipe 21.6. Installing PECL Packages Recipe 21.7. Upgrading PEAR Packages Recipe 21.8. Uninstalling PEAR Packages Recipe 21.9. Documenting Classes with PHPDoc

Colophon Index


Leave a Reply

Your email address will not be published. Required fields are marked *