You are previewing PHP Cookbook, 3rd Edition, one of over 35,000 titles on Safari
O'Reilly logo
PHP Cookbook, 3rd Edition

Book Description

Want to understand a certain PHP programming technique? Or learn how to accomplish a particular task? This cookbook is the first place to look. With more than 350 code-rich recipes revised for PHP 5.4 and 5.5, this third edition provides updated solutions for generating dynamic web content—everything from using basic data types to querying databases, and from calling RESTful APIs to testing and securing your site.

Table of Contents

  1. 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
  2. 1. Strings
    1. Introduction
    2. Accessing Substrings
    3. Extracting Substrings
    4. Replacing Substrings
    5. Processing a String One Byte at a Time
    6. Reversing a String by Word or Byte
    7. Generating a Random String
    8. Expanding and Compressing Tabs
    9. Controlling Case
    10. Interpolating Functions and Expressions Within Strings
    11. Trimming Blanks from a String
    12. Generating Comma-Separated Data
    13. Parsing Comma-Separated Data
    14. Generating Fixed-Width Field Data Records
    15. Parsing Fixed-Width Field Data Records
    16. Taking Strings Apart
    17. Wrapping Text at a Certain Line Length
    18. Storing Binary Data in Strings
    19. Program: Downloadable CSV File
  3. 2. Numbers
    1. Introduction
    2. Checking Whether a Variable Contains a Valid Number
    3. Comparing Floating-Point Numbers
    4. Rounding Floating-Point Numbers
    5. Operating on a Series of Integers
    6. Generating Random Numbers Within a Range
    7. Generating Predictable Random Numbers
    8. Generating Biased Random Numbers
    9. Taking Logarithms
    10. Calculating Exponents
    11. Formatting Numbers
    12. Formatting Monetary Values
    13. Printing Correct Plurals
    14. Calculating Trigonometric Functions
    15. Doing Trigonometry in Degrees, Not Radians
    16. Handling Very Large or Very Small Numbers
    17. Converting Between Bases
    18. Calculating Using Numbers in Bases Other Than Decimal
    19. Finding the Distance Between Two Places
  4. 3. Dates and Times
    1. Introduction
    2. Finding the Current Date and Time
    3. Converting Time and Date Parts to an Epoch Timestamp
    4. Converting an Epoch Timestamp to Time and Date Parts
    5. Printing a Date or Time in a Specified Format
    6. Finding the Difference of Two Dates
    7. Finding the Day in a Week, Month, or Year
    8. Validating a Date
    9. Parsing Dates and Times from Strings
    10. Adding to or Subtracting from a Date
    11. Calculating Time with Time Zones and Daylight Saving Time
    12. Generating a High-Precision Time
    13. Generating Time Ranges
    14. Using Non-Gregorian Calendars
    15. Program: Calendar
  5. 4. Arrays
    1. Introduction
    2. Specifying an Array Not Beginning at Element 0
    3. Storing Multiple Elements per Key in an Array
    4. Initializing an Array to a Range of Integers
    5. Iterating Through an Array
    6. Deleting Elements from an Array
    7. Changing Array Size
    8. Appending One Array to Another
    9. Turning an Array into a String
    10. Printing an Array with Commas
    11. Checking if a Key Is in an Array
    12. Checking if an Element Is in an Array
    13. Finding the Position of a Value in an Array
    14. Finding Elements That Pass a Certain Test
    15. Finding the Largest or Smallest Valued Element in an Array
    16. Reversing an Array
    17. Sorting an Array
    18. Sorting an Array by a Computable Field
    19. Sorting Multiple Arrays
    20. Sorting an Array Using a Method Instead of a Function
    21. Randomizing an Array
    22. Removing Duplicate Elements from an Array
    23. Applying a Function to Each Element in an Array
    24. Finding the Union, Intersection, or Difference of Two Arrays
    25. Iterating Efficiently over Large or Expensive Datasets
    26. Accessing an Object Using Array Syntax
  6. 5. Variables
    1. Introduction
    2. Avoiding == Versus = Confusion
    3. Establishing a Default Value
    4. Exchanging Values Without Using Temporary Variables
    5. Creating a Dynamic Variable Name
    6. Persisting a Local Variable’s Value Across Function Invocations
    7. Sharing Variables Between Processes
    8. Encapsulating Complex Data Types in a String
    9. Dumping Variable Contents as Strings
  7. 6. Functions
    1. Introduction
    2. Accessing Function Parameters
    3. Setting Default Values for Function Parameters
    4. Passing Values by Reference
    5. Using Named Parameters
    6. Enforcing Types of Function Arguments
    7. Creating Functions That Take a Variable Number of Arguments
    8. Returning Values by Reference
    9. Returning More Than One Value
    10. Skipping Selected Return Values
    11. Returning Failure
    12. Calling Variable Functions
    13. Accessing a Global Variable Inside a Function
    14. Creating Dynamic Functions
  8. 7. Classes and Objects
    1. Introduction
    2. Instantiating Objects
    3. Defining Object Constructors
    4. Defining Object Destructors
    5. Implementing Access Control
    6. Preventing Changes to Classes and Methods
    7. Defining Object Stringification
    8. Requiring Multiple Classes to Behave Similarly
    9. Creating Abstract Base Classes
    10. Assigning Object References
    11. Cloning Objects
    12. Overriding Property Accesses
    13. Calling Methods on an Object Returned by Another Method
    14. Aggregating Objects
    15. Accessing Overridden Methods
    16. Creating Methods Dynamically
    17. Using Method Polymorphism
    18. Defining Class Constants
    19. Defining Static Properties and Methods
    20. Controlling Object Serialization
    21. Introspecting Objects
    22. Checking If an Object Is an Instance of a Specific Class
    23. Autoloading Class Files upon Object Instantiation
    24. Instantiating an Object Dynamically
    25. Program: whereis
  9. 8. Web Fundamentals
    1. Introduction
    2. Setting Cookies
    3. Reading Cookie Values
    4. Deleting Cookies
    5. Building a Query String
    6. Reading the POST Request Body
    7. Using HTTP Basic or Digest Authentication
    8. Using Cookie Authentication
    9. Reading an HTTP Header
    10. Writing an HTTP Header
    11. Sending a Specific HTTP Status Code
    12. Redirecting to a Different Location
    13. Flushing Output to the Browser
    14. Buffering Output to the Browser
    15. Compressing Web Output
    16. Reading Environment Variables
    17. Setting Environment Variables
    18. Communicating Within Apache
    19. Redirecting Mobile Browsers to a Mobile Optimized Site
    20. Program: Website Account (De)activator
    21. Program: Tiny Wiki
    22. Program: HTTP Range
  10. 9. Forms
    1. Introduction
    2. Processing Form Input
    3. Validating Form Input: Required Fields
    4. Validating Form Input: Numbers
    5. Validating Form Input: Email Addresses
    6. Validating Form Input: Drop-Down Menus
    7. Validating Form Input: Radio Buttons
    8. Validating Form Input: Checkboxes
    9. Validating Form Input: Dates and Times
    10. Validating Form Input: Credit Cards
    11. Preventing Cross-Site Scripting
    12. Processing Uploaded Files
    13. Working with Multipage Forms
    14. Redisplaying Forms with Inline Error Messages
    15. Guarding Against Multiple Submissions of the Same Form
    16. Preventing Global Variable Injection
    17. Handling Remote Variables with Periods in Their Names
    18. Using Form Elements with Multiple Options
    19. Creating Drop-Down Menus Based on the Current Date
  11. 10. Database Access
    1. Introduction
    2. Using DBM Databases
    3. Using an SQLite Database
    4. Connecting to an SQL Database
    5. Querying an SQL Database
    6. Retrieving Rows Without a Loop
    7. Modifying Data in an SQL Database
    8. Repeating Queries Efficiently
    9. Finding the Number of Rows Returned by a Query
    10. Escaping Quotes
    11. Logging Debugging Information and Errors
    12. Creating Unique Identifiers
    13. Building Queries Programmatically
    14. Making Paginated Links for a Series of Records
    15. Caching Queries and Results
    16. Accessing a Database Connection Anywhere in Your Program
    17. Program: Storing a Threaded Message Board
    18. Using Redis
  12. 11. Sessions and Data Persistence
    1. Introduction
    2. Using Session Tracking
    3. Preventing Session Hijacking
    4. Preventing Session Fixation
    5. Storing Sessons in Memcached
    6. Storing Sessions in a Database
    7. Storing Arbitrary Data in Shared Memory
    8. Caching Calculated Results in Summary Tables
  13. 12. XML
    1. Introduction
    2. Generating XML as a String
    3. Generating XML with DOM
    4. Parsing Basic XML Documents
    5. Parsing Complex XML Documents
    6. Parsing Large XML Documents
    7. Extracting Information Using XPath
    8. Transforming XML with XSLT
    9. Setting XSLT Parameters from PHP
    10. Calling PHP Functions from XSLT Stylesheets
    11. Validating XML Documents
    12. Handling Content Encoding
    13. Reading RSS and Atom Feeds
    14. Writing RSS Feeds
    15. Writing Atom Feeds
  14. 13. Web Automation
    1. Introduction
    2. Marking Up a Web Page
    3. Cleaning Up Broken or Nonstandard HTML
    4. Extracting Links from an HTML File
    5. Converting Plain Text to HTML
    6. Converting HTML to Plain Text
    7. Removing HTML and PHP Tags
    8. Responding to an Ajax Request
    9. Integrating with JavaScript
    10. Program: Finding Stale Links
    11. Program: Finding Fresh Links
  15. 14. Consuming RESTful APIs
    1. Introduction
    2. Fetching a URL with the GET Method
    3. Fetching a URL with the POST Method and Form Data
    4. Fetching a URL with an Arbitrary Method and POST Body
    5. Fetching a URL with Cookies
    6. Fetching a URL with Arbitrary Headers
    7. Fetching a URL with a Timeout
    8. Fetching an HTTPS URL
    9. Debugging the Raw HTTP Exchange
    10. Making an OAuth 1.0 Request
    11. Making an OAuth 2.0 Request
  16. 15. Serving RESTful APIs
    1. Introduction
    2. Exposing and Routing to a Resource
    3. Exposing Clean Resource Paths
    4. Exposing a Resource for Reading
    5. Creating a Resource
    6. Editing a Resource
    7. Deleting a Resource
    8. Indicating Errors and Failures
    9. Supporting Multiple Formats
  17. 16. Internet Services
    1. Introduction
    2. Sending Mail
    3. Sending MIME Mail
    4. Reading Mail with IMAP or POP3
    5. Getting and Putting Files with FTP
    6. Looking Up Addresses with LDAP
    7. Using LDAP for User Authentication
    8. Performing DNS Lookups
    9. Checking If a Host Is Alive
    10. Getting Information About a Domain Name
  18. 17. Graphics
    1. Introduction
    2. Drawing Lines, Rectangles, and Polygons
    3. Drawing Arcs, Ellipses, and Circles
    4. Drawing with Patterned Lines
    5. Drawing Text
    6. Drawing Centered Text
    7. Building Dynamic Images
    8. Getting and Setting a Transparent Color
    9. Overlaying Watermarks
    10. Creating Thumbnail Images
    11. Reading EXIF Data
    12. Serving Images Securely
    13. Program: Generating Bar Charts from Poll Results
  19. 18. Security and Encryption
    1. Introduction
    2. Preventing Session Fixation
    3. Protecting Against Form Spoofing
    4. Ensuring Input Is Filtered
    5. Avoiding Cross-Site Scripting
    6. Eliminating SQL Injection
    7. Keeping Passwords Out of Your Site Files
    8. Storing Passwords
    9. Dealing with Lost Passwords
    10. Verifying Data with Hashes
    11. Encrypting and Decrypting Data
    12. Storing Encrypted Data in a File or Database
    13. Sharing Encrypted Data with Another Website
    14. Detecting SSL
    15. Encrypting Email with GPG
  20. 19. Internationalization and Localization
    1. Introduction
    2. Determining the User’s Locale
    3. Localizing Text Messages
    4. Localizing Dates and Times
    5. Localizing Numbers
    6. Localizing Currency Values
    7. Localizing Images
    8. Localizing Included Files
    9. Sorting in a Locale-Aware Order
    10. Managing Localization Resources
    11. Setting the Character Encoding of Outgoing Data
    12. Setting the Character Encoding of Incoming Data
    13. Manipulating UTF-8 Text
  21. 20. Error Handling
    1. Introduction
    2. Finding and Fixing Parse Errors
    3. Creating Your Own Exception Classes
    4. Printing a Stack Trace
    5. Reading Configuration Variables
    6. Setting Configuration Variables
    7. Hiding Error Messages from Users
    8. Tuning Error Handling
    9. Using a Custom Error Handler
    10. Logging Errors
    11. Eliminating “headers already sent” Errors
    12. Logging Debugging Information
  22. 21. Software Engineering
    1. Introduction
    2. Using a Debugger Extension
    3. Writing a Unit Test
    4. Writing a Unit Test Suite
    5. Applying a Unit Test to a Web Page
    6. Setting Up a Test Environment
    7. Using the Built-in Web Server
  23. 22. Performance Tuning
    1. Introduction
    2. Using an Accelerator
    3. Timing Function Execution
    4. Timing Program Execution by Function
    5. Timing Program Execution by Statement
    6. Timing Program Execution by Section
    7. Profiling with a Debugger Extension
    8. Stress-Testing Your Website
    9. Avoiding Regular Expressions
  24. 23. Regular Expressions
    1. Introduction
    2. Switching from ereg to preg
    3. Matching Words
    4. Finding the nth Occurrence of a Match
    5. Choosing Greedy or Nongreedy Matches
    6. Finding All Lines in a File That Match a Pattern
    7. Capturing Text Inside HTML Tags
    8. Preventing Parentheses from Capturing Text
    9. Escaping Special Characters in a Regular Expression
    10. Reading Records with a Pattern Separator
    11. Using a PHP Function in a Regular Expression
  25. 24. Files
    1. Introduction
    2. Creating or Opening a Local File
    3. Creating a Temporary File
    4. Opening a Remote File
    5. Reading from Standard Input
    6. Reading a File into a String
    7. Counting Lines, Paragraphs, or Records in a File
    8. Processing Every Word in a File
    9. Picking a Random Line from a File
    10. Randomizing All Lines in a File
    11. Processing Variable-Length Text Fields
    12. Reading Configuration Files
    13. Modifying a File in Place Without a Temporary File
    14. Flushing Output to a File
    15. Writing to Standard Output
    16. Writing to Many Filehandles Simultaneously
    17. Escaping Shell Metacharacters
    18. Passing Input to a Program
    19. Reading Standard Output from a Program
    20. Reading Standard Error from a Program
    21. Locking a File
    22. Reading and Writing Custom File Types
    23. Reading and Writing Compressed Files
  26. 25. Directories
    1. Introduction
    2. Getting and Setting File Timestamps
    3. Getting File Information
    4. Changing File Permissions or Ownership
    5. Splitting a Filename into Its Component Parts
    6. Deleting a File
    7. Copying or Moving a File
    8. Processing All Files in a Directory
    9. Getting a List of Filenames Matching a Pattern
    10. Processing All Files in a Directory Recursively
    11. Making New Directories
    12. Removing a Directory and Its Contents
    13. Program: Web Server Directory Listing
    14. Program: Site Search
  27. 26. Command-Line PHP
    1. Introduction
    2. Parsing Program Arguments
    3. Parsing Program Arguments with getopt
    4. Reading from the Keyboard
    5. Running PHP Code on Every Line of an Input File
    6. Reading Passwords
    7. Colorizing Console Output
    8. Program: DOM Explorer
  28. 27. Packages
    1. Introduction
    2. Defining and Installing Composer Dependencies
    3. Finding Composer Packages
    4. Installing Composer Packages
    5. Using the PEAR Installer
    6. Finding PEAR Packages
    7. Finding Information About a Package
    8. Installing PEAR Packages
    9. Upgrading PEAR Packages
    10. Uninstalling PEAR Packages
    11. Installing PECL Packages
  29. Index
  30. Colophon
  31. Copyright