O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

PHP Cookbook, 2nd Edition

Book Description

When it comes to creating dynamic web sites, the open source PHP language is red-hot property: used on more than 20 million web sites today, PHP is now more popular than Microsoft's ASP.NET technology. With our Cookbook's unique format, you can learn how to build dynamic web applications that work on any web browser. This revised new edition makes it easy to find specific solutions for programming challenges.

PHP Cookbook has a wealth of solutions for problems that you'll face regularly. With topics that range from beginner questions to advanced web programming techniques, this guide contains practical examples -- or "recipes" -- for anyone who uses this scripting language to generate dynamic web content. Updated for PHP 5, this book provides solutions that explain how to use the new language features in detail, including the vastly improved object-oriented capabilities and the new PDO data access extension. New sections on classes and objects are included, along with new material on processing XML, building web services with PHP, and working with SOAP/REST architectures. With each recipe, the authors include a discussion that explains the logic and concepts underlying the solution.

Table of Contents

  1. A Note Regarding Supplemental Files
  2. Preface
    1. Who This Book Is For
    2. What Is in This Book
    3. Other Resources
    4. Conventions Used in This Book
    5. Comments and Questions
    6. Acknowledgments
  3. 1. Strings
    1. 1.0. Introduction
    2. 1.1. Accessing Substrings
    3. 1.2. Extracting Substrings
    4. 1.3. Replacing Substrings
    5. 1.4. Processing a String One Byte at a Time
    6. 1.5. Reversing a String by Word or Byte
    7. 1.6. Expanding and Compressing Tabs
    8. 1.7. Controlling Case
    9. 1.8. Interpolating Functions and Expressions Within Strings
    10. 1.9. Trimming Blanks from a String
    11. 1.10. Generating Comma-Separated Data
    12. 1.11. Parsing Comma-Separated Data
    13. 1.12. Generating Fixed-Width Field Data Records
    14. 1.13. Parsing Fixed-Width Field Data Records
    15. 1.14. Taking Strings Apart
    16. 1.15. Wrapping Text at a Certain Line Length
    17. 1.16. Storing Binary Data in Strings
    18. 1.17. Program: Downloadable CSV File
  4. 2. Numbers
    1. 2.0. Introduction
    2. 2.1. Checking Whether a Variable Contains a Valid Number
    3. 2.2. Comparing Floating-Point Numbers
    4. 2.3. Rounding Floating-Point Numbers
    5. 2.4. Operating on a Series of Integers
    6. 2.5. Generating Random Numbers Within a Range
    7. 2.6. Generating Biased Random Numbers
    8. 2.7. Taking Logarithms
    9. 2.8. Calculating Exponents
    10. 2.9. Formatting Numbers
    11. 2.10. Formatting Monetary Values
    12. 2.11. Printing Correct Plurals
    13. 2.12. Calculating Trigonometric Functions
    14. 2.13. Doing Trigonometry in Degrees, Not Radians
    15. 2.14. Handling Very Large or Very Small Numbers
    16. 2.15. Converting Between Bases
    17. 2.16. Calculating Using Numbers in Bases Other Than Decimal
    18. 2.17. Finding the Distance Between Two Places
  5. 3. Dates and Times
    1. 3.0. Introduction
    2. 3.1. Finding the Current Date and Time
    3. 3.2. Converting Time and Date Parts to an Epoch Timestamp
    4. 3.3. Converting an Epoch Timestamp to Time and Date Parts
    5. 3.4. Printing a Date or Time in a Specified Format
    6. 3.5. Finding the Difference of Two Dates
    7. 3.6. Finding the Difference of Two Dates with Julian Days
    8. 3.7. Finding the Day in a Week, Month, or Year
    9. 3.8. Validating a Date
    10. 3.9. Parsing Dates and Times from Strings
    11. 3.10. Adding to or Subtracting from a Date
    12. 3.11. Calculating Time with Time Zones
    13. 3.12. Accounting for Daylight Savings Time
    14. 3.13. Generating a High-Precision Time
    15. 3.14. Generating Time Ranges
    16. 3.15. Using Non-Gregorian Calendars
    17. 3.16. Using Dates Outside the Range of an Epoch Timestamp
    18. 3.17. Program: Calendar
  6. 4. Arrays
    1. 4.0. Introduction
    2. 4.1. Specifying an Array Not Beginning at Element 0
    3. 4.2. Storing Multiple Elements Per Key in an Array
    4. 4.3. Initializing an Array to a Range of Integers
    5. 4.4. Iterating Through an Array
    6. 4.5. Deleting Elements from an Array
    7. 4.6. Changing Array Size
    8. 4.7. Appending One Array to Another
    9. 4.8. Turning an Array into a String
    10. 4.9. Printing an Array with Commas
    11. 4.10. Checking if a Key Is in an Array
    12. 4.11. Checking if an Element Is in an Array
    13. 4.12. Finding the Position of a Value in an Array
    14. 4.13. Finding Elements That Pass a Certain Test
    15. 4.14. Finding the Largest or Smallest Valued Element in an Array
    16. 4.15. Reversing an Array
    17. 4.16. Sorting an Array
    18. 4.17. Sorting an Array by a Computable Field
    19. 4.18. Sorting Multiple Arrays
    20. 4.19. Sorting an Array Using a Method Instead of a Function
    21. 4.20. Randomizing an Array
    22. 4.21. Removing Duplicate Elements from an Array
    23. 4.22. Applying a Function to Each Element in an Array
    24. 4.23. Finding the Union, Intersection, or Difference of Two Arrays
    25. 4.24. Making an Object Act like an Array
    26. 4.25. Program: Printing a Horizontally Columned HTML Table
  7. 5. Variables
    1. 5.0. Introduction
    2. 5.1. Avoiding == Versus = Confusion
    3. 5.2. Establishing a Default Value
    4. 5.3. Exchanging Values Without Using Temporary Variables
    5. 5.4. Creating a Dynamic Variable Name
    6. 5.5. Using Static Variables
    7. 5.6. Sharing Variables Between Processes
    8. 5.7. Encapsulating Complex Data Types in a String
    9. 5.8. Dumping Variable Contents as Strings
  8. 6. Functions
    1. 6.0. Introduction
    2. 6.1. Accessing Function Parameters
    3. 6.2. Setting Default Values for Function Parameters
    4. 6.3. Passing Values by Reference
    5. 6.4. Using Named Parameters
    6. 6.5. Creating Functions That Take a Variable Number of Arguments
    7. 6.6. Returning Values by Reference
    8. 6.7. Returning More Than One Value
    9. 6.8. Skipping Selected Return Values
    10. 6.9. Returning Failure
    11. 6.10. Calling Variable Functions
    12. 6.11. Accessing a Global Variable Inside a Function
    13. 6.12. Creating Dynamic Functions
  9. 7. Classes and Objects
    1. 7.0. Introduction
    2. 7.1. Instantiating Objects
    3. 7.2. Defining Object Constructors
    4. 7.3. Defining Object Destructors
    5. 7.4. Implementing Access Control
    6. 7.5. Preventing Changes to Classes and Methods
    7. 7.6. Defining Object Stringification
    8. 7.7. Specifying Interfaces
    9. 7.8. Creating Abstract Base Classes
    10. 7.9. Assigning Object References
    11. 7.10. Cloning Objects
    12. 7.11. Overriding Property Accesses
    13. 7.12. Calling Methods on an Object Returned by Another Method
    14. 7.13. Aggregating Objects
    15. 7.14. Accessing Overridden Methods
    16. 7.15. Using Method Polymorphism
    17. 7.16. Defining Class Constants
    18. 7.17. Defining Static Properties and Methods
    19. 7.18. Controlling Object Serialization
    20. 7.19. Introspecting Objects
    21. 7.20. Checking if an Object Is an Instance of a Specific Class
    22. 7.21. Autoloading Class Files upon Object Instantiation
    23. 7.22. Instantiating an Object Dynamically
    24. 7.23. Program: whereis
  10. 8. Web Basics
    1. 8.0. Introduction
    2. 8.1. Setting Cookies
    3. 8.2. Reading Cookie Values
    4. 8.3. Deleting Cookies
    5. 8.4. Redirecting to a Different Location
    6. 8.5. Detecting Different Browsers
    7. 8.6. Building a Query String
    8. 8.7. Reading the Post Request Body
    9. 8.8. Generating HTML Tables with Alternating Row Styles
    10. 8.9. Using HTTP Basic or Digest Authentication
    11. 8.10. Using Cookie Authentication
    12. 8.11. Flushing Output to the Browser
    13. 8.12. Buffering Output to the Browser
    14. 8.13. Compressing Web Output
    15. 8.14. Reading Environment Variables
    16. 8.15. Setting Environment Variables
    17. 8.16. Communicating Within Apache
    18. 8.17. Program: Web Site Account (De)activator
    19. 8.18. Program: Tiny Wiki
  11. 9. Form
    1. 9.0. Introduction
    2. 9.1. Processing Form Input
    3. 9.2. Validating Form Input: Required Fields
    4. 9.3. Validating Form Input: Numbers
    5. 9.4. Validating Form Input: Email Addresses
    6. 9.5. Validating Form Input: Drop-Down Menus
    7. 9.6. Validating Form Input: Radio Buttons
    8. 9.7. Validating Form Input: Checkboxes
    9. 9.8. Validating Form Input: Dates and Times
    10. 9.9. Validating Form Input: Credit Cards
    11. 9.10. Preventing Cross-Site Scripting
    12. 9.11. Working with Multipage Forms
    13. 9.12. Redisplaying Forms with Inline Error Messages
    14. 9.13. Guarding Against Multiple Submission of the Same Form
    15. 9.14. Processing Uploaded Files
    16. 9.15. Preventing Global Variable Injection
    17. 9.16. Handling Remote Variables with Periods in Their Names
    18. 9.17. Using Form Elements with Multiple Options
    19. 9.18. Creating Drop-Down Menus Based on the Current Date
  12. 10. Database Access
    1. 10.0. Introduction
    2. 10.1. Using DBM Databases
    3. 10.2. Using an SQLite Database
    4. 10.3. Connecting to an SQL Database
    5. 10.4. Querying an SQL Database
    6. 10.5. Retrieving Rows Without a Loop
    7. 10.6. Modifying Data in an SQL Database
    8. 10.7. Repeating Queries Efficiently
    9. 10.8. Finding the Number of Rows Returned by a Query
    10. 10.9. Escaping Quotes
    11. 10.10. Logging Debugging Information and Errors
    12. 10.11. Creating Unique Identifiers
    13. 10.12. Building Queries Programmatically
    14. 10.13. Making Paginated Links for a Series of Records
    15. 10.14. Caching Queries and Results
    16. 10.15. Accessing a Database Connection Anywhere in Your Program
    17. 10.16. Program: Storing a Threaded Message Board
  13. 11. Sessions and Data Persistence
    1. 11.0. Introduction
    2. 11.1. Using Session Tracking
    3. 11.2. Preventing Session Hijacking
    4. 11.3. Preventing Session Fixation
    5. 11.4. Storing Sessions in a Database
    6. 11.5. Storing Sessions in Shared Memory
    7. 11.6. Storing Arbitrary Data in Shared Memory
    8. 11.7. Caching Calculated Results in Summary Tables
  14. 12. XML
    1. 12.0. Introduction
    2. 12.1. Generating XML as a String
    3. 12.2. Generating XML with the DOM
    4. 12.3. Parsing Basic XML Documents
    5. 12.4. Parsing Complex XML Documents
    6. 12.5. Parsing Large XML Documents
    7. 12.6. Extracting Information Using XPath
    8. 12.7. Transforming XML with XSLT
    9. 12.8. Setting XSLT Parameters from PHP
    10. 12.9. Calling PHP Functions from XSLT Stylesheets
    11. 12.10. Validating XML Documents
    12. 12.11. Handling Content Encoding
    13. 12.12. Reading RSS and Atom Feeds
    14. 12.13. Writing RSS Feeds
    15. 12.14. Writing Atom Feeds
  15. 13. Web Automation
    1. 13.0. Introduction
    2. 13.1. Fetching a URL with the Get Method
    3. 13.2. Fetching a URL with the Post Method
    4. 13.3. Fetching a URL with Cookies
    5. 13.4. Fetching a URL with Arbitrary Headers
    6. 13.5. Fetching a URL with an Arbitrary Method
    7. 13.6. Fetching a URL with a Timeout
    8. 13.7. Fetching an HTTPS URL
    9. 13.8. Debugging the Raw HTTP Exchange
    10. 13.9. Marking Up a Web Page
    11. 13.10. Cleaning Up Broken or Nonstandard HTML
    12. 13.11. Extracting Links from an HTML File
    13. 13.12. Converting Plain Text to HTML
    14. 13.13. Converting HTML to Plain Text
    15. 13.14. Removing HTML and PHP Tags
    16. 13.15. Responding to an Ajax Request
    17. 13.16. Integrating with JavaScript
    18. 13.17. Program: Finding Stale Links
    19. 13.18. Program: Finding Fresh Links
  16. 14. Consuming Web Services
    1. 14.0. Introduction
    2. 14.1. Calling a REST Method
    3. 14.2. Calling a SOAP Method with WSDL
    4. 14.3. Calling a SOAP Method Without WSDL
    5. 14.4. Debugging SOAP Requests
    6. 14.5. Using Complex SOAP Types
    7. 14.6. Setting SOAP Types
    8. 14.7. Using SOAP Headers
    9. 14.8. Using Authentication with SOAP
    10. 14.9. Redefining an Endpoint
    11. 14.10. Catching SOAP Faults
    12. 14.11. Mapping XML Schema Data Types to PHP Classes
    13. 14.12. Calling an XML-RPC Method
    14. 14.13. Using Authentication with XML-RPC
  17. 15. Building Web Services
    1. 15.0. Introduction
    2. 15.1. Serving a REST Method
    3. 15.2. Serving a SOAP Method
    4. 15.3. Accepting Arguments in a SOAP Method
    5. 15.4. Generating WSDL Automatically
    6. 15.5. Throwing SOAP Faults
    7. 15.6. Processing a SOAP Header
    8. 15.7. Generating a SOAP Header
    9. 15.8. Using Authentication with SOAP
    10. 15.9. Serving an XML-RPC Method
  18. 16. Internet Services
    1. 16.0. Introduction
    2. 16.1. Sending Mail
    3. 16.2. Sending MIME Mail
    4. 16.3. Reading Mail with IMAP or POP3
    5. 16.4. Posting Messages to Usenet Newsgroups
    6. 16.5. Reading Usenet News Messages
    7. 16.6. Getting and Putting Files with FTP
    8. 16.7. Looking Up Addresses with LDAP
    9. 16.8. Using LDAP for User Authentication
    10. 16.9. Performing DNS Lookups
    11. 16.10. Checking if a Host Is Alive
    12. 16.11. Getting Information About a Domain Name
  19. 17. Graphics
    1. 17.0. Introduction
    2. 17.1. Drawing Lines, Rectangles, and Polygons
    3. 17.2. Drawing Arcs, Ellipses, and Circles
    4. 17.3. Drawing with Patterned Lines
    5. 17.4. Drawing Text
    6. 17.5. Drawing Centered Text
    7. 17.6. Building Dynamic Images
    8. 17.7. Getting and Setting a Transparent Color
    9. 17.8. Reading EXIF Data
    10. 17.9. Serving Images Securely
    11. 17.10. Program: Generating Bar Charts from Poll Results
  20. 18. Security and Encryption
    1. 18.0. Introduction
    2. 18.1. Preventing Session Fixation
    3. 18.2. Protecting Against Form Spoofing
    4. 18.3. Ensuring Input Is Filtered
    5. 18.4. Avoiding Cross-Site Scripting
    6. 18.5. Eliminating SQL Injection
    7. 18.6. Keeping Passwords Out of Your Site Files
    8. 18.7. Storing Passwords
    9. 18.8. Dealing with Lost Passwords
    10. 18.9. Verifying Data with Hashes
    11. 18.10. Encrypting and Decrypting Data
    12. 18.11. Storing Encrypted Data in a File or Database
    13. 18.12. Sharing Encrypted Data with Another Web Site
    14. 18.13. Detecting SSL
    15. 18.14. Encrypting Email with GPG
  21. 19. Internationalization and Localization
    1. 19.0. Introduction
    2. 19.1. Listing Available Locales
    3. 19.2. Using a Particular Locale
    4. 19.3. Setting the Default Locale
    5. 19.4. Localizing Text Messages
    6. 19.5. Localizing Dates and Times
    7. 19.6. Localizing Currency Values
    8. 19.7. Localizing Images
    9. 19.8. Localizing Included Files
    10. 19.9. Managing Localization Resources
    11. 19.10. Using gettext
    12. 19.11. Setting the Character Encoding of Outgoing Data
    13. 19.12. Setting the Character Encoding of Incoming Data
    14. 19.13. Manipulating UTF-8 Text
  22. 20. Error Handling, Debugging, andTesting
    1. 20.0. Introduction
    2. 20.1. Finding and Fixing Parse Errors
    3. 20.2. Creating Your Own Exception Classes
    4. 20.3. Printing a Stack Trace
    5. 20.4. Reading Configuration Variables
    6. 20.5. Setting Configuration Variables
    7. 20.6. Hiding Error Messages from Users
    8. 20.7. Tuning Error Handling
    9. 20.8. Using a Custom Error Handler
    10. 20.9. Logging Errors
    11. 20.10. Eliminating “headers already sent” Errors
    12. 20.11. Logging Debugging Information
    13. 20.12. Using a Debugger Extension
    14. 20.13. Writing a Unit Test
    15. 20.14. Writing a Unit Test Suite
    16. 20.15. Applying a Unit Test to a Web Page
    17. 20.16. Setting Up a Test Environment
  23. 21. Performance Tuning and Load Testing
    1. 21.0. Introduction
    2. 21.1. Timing Function Execution
    3. 21.2. Timing Program Execution
    4. 21.3. Profiling with a Debugger Extension
    5. 21.4. Stress Testing Your Web Site
    6. 21.5. Avoiding Regular Expressions
    7. 21.6. Using an Accelerator
  24. 22. Regular Expressions
    1. 22.0. Introduction
    2. 22.1. Switching from ereg to preg
    3. 22.2. Matching Words
    4. 22.3. Finding the nth Occurrence of a Match
    5. 22.4. Choosing Greedy or Nongreedy Matches
    6. 22.5. Finding All Lines in a File That Match a Pattern
    7. 22.6. Capturing Text Inside HTML Tags
    8. 22.7. Preventing Parentheses from Capturing Text
    9. 22.8. Escaping Special Characters in a Regular Expression
    10. 22.9. Reading Records with a Pattern Separator
    11. 22.10. Using a PHP Function in a Regular Expression
  25. 23. Files
    1. 23.0. Introduction
    2. 23.1. Creating or Opening a Local File
    3. 23.2. Creating a Temporary File
    4. 23.3. Opening a Remote File
    5. 23.4. Reading from Standard Input
    6. 23.5. Reading a File into a String
    7. 23.6. Counting Lines, Paragraphs, or Records in a File
    8. 23.7. Processing Every Word in a File
    9. 23.8. Picking a Random Line from a File
    10. 23.9. Randomizing All Lines in a File
    11. 23.10. Processing Variable-Length Text Fields
    12. 23.11. Reading Configuration Files
    13. 23.12. Modifying a File in Place Without a Temporary File
    14. 23.13. Flushing Output to a File
    15. 23.14. Writing to Standard Output
    16. 23.15. Writing to Many Filehandles Simultaneously
    17. 23.16. Escaping Shell Metacharacters
    18. 23.17. Passing Input to a Program
    19. 23.18. Reading Standard Output from a Program
    20. 23.19. Reading Standard Error from a Program
    21. 23.20. Locking a File
    22. 23.21. Reading and Writing Custom File Types
    23. 23.22. Reading and Writing Compressed Files
  26. 24. Directories
    1. 24.0. Introduction
    2. 24.1. Getting and Setting File Timestamps
    3. 24.2. Getting File Information
    4. 24.3. Changing File Permissions or Ownership
    5. 24.4. Splitting a Filename into Its Component Parts
    6. 24.5. Deleting a File
    7. 24.6. Copying or Moving a File
    8. 24.7. Processing All Files in a Directory
    9. 24.8. Getting a List of Filenames Matching a Pattern
    10. 24.9. Processing All Files in a Directory Recursively
    11. 24.10. Making New Directories
    12. 24.11. Removing a Directory and Its Contents
    13. 24.12. Program: Web Server Directory Listing
    14. 24.13. Program: Site Search
  27. 25. Command-Line PHP
    1. 25.0. Introduction
    2. 25.1. Parsing Program Arguments
    3. 25.2. Parsing Program Arguments with getopt
    4. 25.3. Reading from the Keyboard
    5. 25.4. Running PHP Code on Every Line of an Input File
    6. 25.5. Reading Passwords
    7. 25.6. Program: Command Shell
  28. 26. PEAR and PECL
    1. 26.0. Introduction
    2. 26.1. Using the PEAR Installer
    3. 26.2. Finding PEAR Packages
    4. 26.3. Finding Information About a Package
    5. 26.4. Installing PEAR Packages
    6. 26.5. Upgrading PEAR Packages
    7. 26.6. Uninstalling PEAR Packages
    8. 26.7. Installing PECL Packages
  29. Index
  30. About the Authors
  31. Colophon
  32. Copyright