Cover image for 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. 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
  2. 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
  3. 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
  4. 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. Making an Object Act like an Array
  5. 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
  6. 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
  7. 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 (Specifying Interfaces or Traits)
    9. Specifying Traits
    10. Creating Abstract Base Classes
    11. Assigning Object References
    12. Cloning Objects
    13. Overriding Property Accesses
    14. Calling Methods on an Object Returned by Another
    15. Aggregating Objects
    16. Accessing Overridden Methods
    17. Creating Methods Dynamically
    18. Using Method Polymorphism
    19. Defining Class Constants
    20. Defining Static Properties and Methods
    21. Controlling Object Serialization
    22. Introspecting Objects
    23. Checking if an Object Is an Instance of a Specific Class
    24. Autoloading Class Files upon Object Instantiation
    25. Instantiating an Object Dynamically
    26. Program: whereis
  8. 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: Web Site Account (De)activator
    21. Program: Tiny Wiki
    22. Program: HTTP Range
  9. 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. Working with Multipage Forms
    13. Redisplaying Forms with Inline Error Messages
    14. Guarding Against Multiple Submission of the Same Form
    15. Processing Uploaded Files
    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
  10. 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
    17. Program: Storing a Threaded Message Board
    18. Using Redis
  11. 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
  12. 12. XML
    1. Introduction
    2. Generating XML as a String
    3. Generating XML with the 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
  13. 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
  14. 14. 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 Web Site
    14. Detecting SSL
    15. Encrypting Email with GPG
  15. 15. 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
  16. 16. 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
    12. Logging Debugging Information
  17. About the Authors
  18. Copyright