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.
Each recipe includes code solutions that you can freely use, along with a discussion of how and why they work. Whether you’re an experienced PHP programmer or coming to PHP from another language, this book is an ideal on-the-job resource.
Designing robust applications: security and encryption, error handling, debugging and testing, and performance tuning
Preface xv
1 Strings 1 (34)
1.1 Accessing Substrings 5 (1)
1.2 Extracting Substrings 6 (1)
1.3 Replacing Substrings 7 (2)
1.4 Processing a String One Byte at a Time 9 (1)
1.5 Reversing a String by Word or Byte 10 (1)
1.6 Generating a Random String 11 (1)
1.7 Expanding and Compressing Tabs 12 (2)
1.8 Controlling Case 14 (2)
1.9 Interpolating Functions and Expressions 16 (1)
Within Strings
1.10 Trimming Blanks from a String 17 (2)
1.11 Generating Comma-Separated Data 19 (1)
1.12 Parsing Comma-Separated Data 20 (1)
1.13 Generating Fixed-Width Field Data Records 21 (1)
1.14 Parsing Fixed-Width Field Data Records 22 (3)
1.15 Taking Strings Apart 25 (2)
1.16 Wrapping Text at a Certain Line Length 27 (2)
1.17 Storing Binary Data in Strings 29 (2)
1.18 Program: Downloadable CSV File 31 (4)
2 Numbers 35 (26)
2.1 Checking Whether a Variable Contains a 36 (1)
Valid Number
2.2 Comparing Floating-Point Numbers 37 (1)
2.3 Rounding Floating-Point Numbers 38 (2)
2.4 Operating on a Series of Integers 40 (2)
2.5 Generating Random Numbers Within a Range 42 (1)
2.6 Generating Predictable Random Numbers 43 (1)
2.7 Generating Biased Random Numbers 44 (2)
2.8 Taking Logarithms 46 (1)
2.9 Calculating Exponents 46 (1)
2.10 Formatting Numbers 47 (2)
2.11 Formatting Monetary Values 49 (1)
2.12 Printing Correct Plurals 50 (1)
2.13 Calculating Trigonometric Functions 51 (1)
2.14 Doing Trigonometry in Degrees, Not 52 (1)
Radians
2.15 Handling Very Large or Very Small Numbers 53 (2)
2.16 Converting Between Bases 55 (1)
2.17 Calculating Using Numbers in Bases Other 56 (2)
Than Decimal
2.18 Finding the Distance Between Two Places 58 (3)
3 Dates and limes 61 (34)
3.1 Finding the Current Date and Time 63 (3)
3.2 Converting Time and Date Parts to an 66 (2)
Epoch Timestamp
3.3 Converting an Epoch Timestamp to Time and 68 (1)
Date Parts
3.4 Printing a Date or Time in a Specified 69 (3)
Format
3.5 Finding the Difference of Two Dates 72 (2)
3.6 Finding the Day in a Week, Month, or Year 74 (2)
3.7 Validating a Date 76 (1)
3.8 Parsing Dates and Times from Strings 77 (3)
3.9 Adding to or Subtracting from a Date 80 (1)
3.10 Calculating Time with Time Zones and 81 (2)
Daylight Saving Time
3.11 Generating a High-Precision Time 83 (1)
3.12 Generating Time Ranges 84 (1)
3.13 Using Non-Gregorian Calendars 85 (3)
3.14 Program: Calendar 88 (7)
4 Arrays 95 (42)
4.1 Specifying an Array Not Beginning at 98 (1)
Element 0
4.2 Storing Multiple Elements per Key in an 99 (2)
Array
4.3 Initializing an Array to a Range of 101(1)
Integers
4.4 Iterating Through an Array 101(3)
4.5 Deleting Elements from an Array 104(2)
4.6 Changing Array Size 106(2)
4.7 Appending One Array to Another 108(2)
4.8 Turning an Array into a String 110(1)
4.9 Printing an Array with Commas 111(2)
4.10 Checking if a Key Is in an Array 113(1)
4.11 Checking if an Element Is in an Array 113(2)
4.12 Finding the Position of a Value in an 115(1)
Array
4.13 Finding Elements That Pass a Certain Test 116(1)
4.14 Finding the Largest or Smallest Valued 117(1)
Element in an Array
4.15 Reversing an Array 118(1)
4.16 Sorting an Array 119(1)
4.17 Sorting an Array by a Computable Field 120(3)
4.18 Sorting Multiple Arrays 123(1)
4.19 Sorting an Array Using a Method Instead 124(1)
of a Function
4.20 Randomizing an Array 125(1)
4.21 Removing Duplicate Elements from an Array 126(1)
4.22 Applying a Function to Each Element in 127(2)
an Array
4.23 Finding the Union, Intersection, or 129(2)
Difference of Two Arrays
4.24 Iterating Efficiently over Large or 131(2)
Expensive Datasets
4.25 Accessing an Object Using Array Syntax 133(4)
5 Variables 137(22)
5.1 Avoiding = Versus = Confusion 139(1)
5.2 Establishing a Default Value 140(1)
5.3 Exchanging Values Without Using Temporary 141(1)
Variables
5.4 Creating a Dynamic Variable Name 142(1)
5.5 Persisting a Local Variable's Value 143(2)
Across Function Invocations
5.6 Sharing Variables Between Processes 145(7)
5.7 Encapsulating Complex Data Types in a 152(1)
String
5.8 Dumping Variable Contents as Strings 153(6)
6 Functions 159(22)
6.1 Accessing Function Parameters 160(1)
6.2 Setting Default Values for Function 161(2)
Parameters
6.3 Passing Values by Reference 163(1)
6.4 Using Named Parameters 164(1)
6.5 Enforcing Types of Function Arguments 165(1)
6.6 Creating Functions That Take a Variable 166(3)
Number of Arguments
6.7 Returning Values by Reference 169(2)
6.8 Returning More Than One Value 171(1)
6.9 Skipping Selected Return Values 172(1)
6.10 Returning Failure 173(1)
6.11 Calling Variable Functions 174(3)
6.12 Accessing a Global Variable Inside a 177(1)
Function
6.13 Creating Dynamic Functions 178(3)
7 Classes and Objects 181(56)
7.1 Instantiating Objects 185(1)
7.2 Defining Object Constructors 186(1)
7.3 Defining Object Destructors 187(1)
7.4 Implementing Access Control 188(3)
7.5 Preventing Changes to Classes and Methods 191(1)
7.6 Defining Object Stringification 192(1)
7.7 Requiring Multiple Classes to Behave 193(4)
Similarly
7.8 Creating Abstract Base Classes 197(2)
7.9 Assigning Object References 199(1)
7.10 Cloning Objects 200(3)
7.11 Overriding Property Accesses 203(4)
7.12 Calling Methods on an Object Returned by 207(1)
Another Method
7.13 Aggregating Objects 208(4)
7.14 Accessing Overridden Methods 212(2)
7.15 Creating Methods Dynamically 214(1)
7.16 Using Method Polymorphism 215(2)
7.17 Defining Class Constants 217(2)
7.18 Defining Static Properties and Methods 219(3)
7.19 Controlling Object Serialization 222(2)
7.20 Introspecting Objects 224(4)
7.21 Checking If an Object Is an Instance of 228(3)
a Specific Class
7.22 Autoloading Class Files upon Object 231(1)
Instantiation
7.23 Instantiating an Object Dynamically 232(1)
7.24 Program: whereis 233(4)
8 Web Fundamentals 237(40)
8.1 Setting Cookies 238(2)
8.2 Reading Cookie Values 240(1)
8.3 Deleting Cookies 240(1)
8.4 Building a Query String 241(1)
8.5 Reading the POST Request Body 242(1)
8.6 Using HTTP Basic or Digest Authentication 243(4)
8.7 Using Cookie Authentication 247(3)
8.8 Reading an HTTP Header 250(1)
8.9 Writing an HTTP Header 251(1)
8.10 Sending a Specific HTTP Status Code 252(1)
8.11 Redirecting to a Different Location 253(2)
8.12 Flushing Output to the Browser` 255(1)
8.13 Buffering Output to the Browser 255(2)
8.14 Compressing Web Output 257(1)
8.15 Reading Environment Variables 258(1)
8.16 Setting Environment Variables 258(1)
8.17 Communicating Within Apache 259(1)
8.18 Redirecting Mobile Browsers to a Mobile 260(1)
Optimized Site
8.19 Program: Website Account (De)activator 261(3)
8.20 Program: Tiny Wild 264(3)
8.21 Program: HTTP Range 267(10)
9 Forms 277(32)
9.1 Processing Form Input 279(2)
9.2 Validating Form Input: Required Fields 281(2)
9.3 Validating Form Input: Numbers 283(2)
9.4 Validating Form Input: Email Addresses 285(1)
9.5 Validating Form Input: Drop-Down Menus 286(1)
9.6 Validating Form Input: Radio Buttons 287(2)
9.7 Validating Form Input: Checkboxes 289(2)
9.8 Validating Form Input: Dates and Times 291(1)
9.9 Validating Form Input: Credit Cards 292(1)
9.10 Preventing Cross-Site Scripting 293(1)
9.11 Processing Uploaded Files 294(3)
9.12 Working with Multipage Forms 297(2)
9.13 Redisplaying Forms with Inline Error 299(2)
Messages
9.14 Guarding Against Multiple Submissions of 301(2)
the Same Form
9.15 Preventing Global Variable Injection 303(2)
9.16 Handling Remote Variables with Periods 305(1)
in Their Names
9.17 Using Form Elements with Multiple Options 306(1)
9.18 Creating Drop-Down Menus Based on the 307(2)
Current Date
10 Database Access 309(46)
10.1 Using DBM Databases 312(3)
10.2 Using an SQLite Database 315(2)
10.3 Connecting to an SQL Database 317(1)
10.4 Querying an SQL Database 318(3)
10.5 Retrieving Rows Without a Loop 321(1)
10.6 Modifying Data in an SQL Database 322(1)
10.7 Repeating Queries Efficiently 323(3)
10.8 Finding the Number of Rows Returned by a 326(1)
Query
10.9 Escaping Quotes 327(2)
10.10 Logging Debugging Information and Errors 329(2)
10.11 Creating Unique Identifiers 331(2)
10.12 Building Queries Programmatically 333(5)
10.13 Making Paginated Links for a Series of 338(3)
Records
10.14 Caching Queries and Results 341(3)
10.15 Accessing a Database Connection 344(2)
Anywhere in Your Program
10.16 Program: Storing a Threaded Message 346(7)
Board
10.17 Using Redis 353(2)
11 Sessions and Data Persistence 355(16)
11.1 Using Session Tracking 356(2)
11.2 Preventing Session Hijacking 358(1)
11.3 Preventing Session Fixation 359(1)
11.4 Storing Sessons in Memcached 360(1)
11.5 Storing Sessions in a Database 361(3)
11.6 Storing Arbitrary Data in Shared Memory 364(3)
11.7 Caching Calculated Results in Summary 367(4)
Tables
12 XML 371(44)
12.1 Generating XML as a String 374(1)
12.2 Generating XML with DOM 375(3)
12.3 Parsing Basic XML Documents 378(3)
12.4 Parsing Complex XML Documents 381(2)
12.5 Parsing Large XML Documents 383(6)
12.6 Extracting Information Using XPath 389(3)
12.7 Transforming XML with XSLT 392(2)
12.8 Setting XSLT Parameters from PHP 394(2)
12.9 Calling PHP Functions from XSLT 396(4)
Stylesheets
12.10 Validating XML Documents 400(2)
12.11 Handling Content Encoding 402(1)
12.12 Reading RSS and Atom Feeds 403(3)
12.13 Writing RSS Feeds 406(3)
12.14 Writing Atom Feeds 409(6)
13 Web Automation 415(26)
13.1 Marking Up a Web Page 416(3)
13.2 Cleaning Up Broken or Nonstandard HTML 419(3)
13.3 Extracting Links from an HTML File 422(3)
13.4 Converting Plain Text to HTML 425(1)
13.5 Converting HTML to Plain Text 426(1)
13.6 Removing HTML and PHP Tags 426(4)
13.7 Responding to an Ajax Request 430(2)
13.8 Integrating with JavaScript 432(3)
13.9 Program: Finding Stale Links 435(3)
13.10 Program: Finding Fresh Links 438(3)
14 Consuming RESTfuI APIs 441(26)
14.1 Fetching a URL with the GET Method 442(4)
14.2 Fetching a URL with the POST Method and 446(2)
Form Data
14.3 Fetching a URL with an Arbitrary Method 448(2)
and POST Body
14.4 Fetching a URL with Cookies 450(2)
14.5 Fetching a URL with Arbitrary Headers 452(2)
14.6 Fetching a URL with a Timeout 454(2)
14.7 Fetching an HTTPS URL 456(1)
14.8 Debugging the Raw HTTP Exchange 456(5)
14.9 Making an OAuth 1.0 Request 461(1)
14.10 Making an OAuth 2.0 Request 462(5)
15 Serving RESTful APIs 467(24)
15.1 Exposing and Routing to a Resource 470(3)
15.2 Exposing Clean Resource Paths 473(1)
15.3 Exposing a Resource for Reading 474(2)
15.4 Creating a Resource 476(5)
15.5 Editing a Resource 481(2)
15.6 Deleting a Resource 483(1)
15.7 Indicating Errors and Failures 484(2)
15.8 Supporting Multiple Formats 486(5)
16 Internet Services 491(22)
16.1 Sending Mail 492(2)
16.2 Sending MIME Mail 494(2)
16.3 Reading Mail with IMAP or POP3 496(4)
16.4 Getting and Putting Files with FTP 500(2)
16.5 Looking Up Addresses with LDAP 502(2)
16.6 Using LDAP for User Authentication 504(2)
16.7 Performing DNS Lookups 506(3)
16.8 Checking If a Host Is Alive 509(1)
16.9 Getting Information About a Domain Name 510(3)
17 Graphics 513(32)
17.1 Drawing Lines, Rectangles, and Polygons 516(3)
17.2 Drawing Arcs, Ellipses, and Circles 519(2)
17.3 Drawing with Patterned Lines 521(1)
17.4 Drawing Text 522(3)
17.5 Drawing Centered Text525(3)
17.6 Building Dynamic Images 528(3)
17.7 Getting and Setting a Transparent Color 531(1)
17.8 Overlaying Watermarks 532(2)
17.9 Creating Thumbnail Images 534(4)
17.10 Reading EXIF Data 538(1)
17.11 Serving Images Securely 539(2)
17.12 Program: Generating Bar Charts from 541(4)
Poll Results
18 Security and Encryption 545(26)
18.1 Preventing Session Fixation 546(1)
18.2 Protecting Against Form Spoofing 547(1)
18.3 Ensuring Input Is Filtered 548(1)
18.4 Avoiding Cross-Site Scripting 549(1)
18.5 Eliminating SQL Injection 550(1)
18.6 Keeping Passwords Out of Your Site Files 551(1)
18.7 Storing Passwords 552(3)
18.8 Dealing with Lost Passwords 555(2)
18.9 Verifying Data with Hashes 557(2)
18.10 Encrypting and Decrypting Data 559(2)
18.11 Storing Encrypted Data in a File or 561(3)
Database
18.12 Sharing Encrypted Data with Another 564(2)
Website
18.13 Detecting SSL 566(1)
18.14 Encrypting Email with GPG 567(4)
19 Internationalization and Localization 571(28)
19.1 Determining the User's Locale 573(1)
19.2 Localizing Text Messages 574(3)
19.3 Localizing Dates and Times 577(4)
19.4 Localizing Numbers 581(3)
19.5 Localizing Currency Values 584(1)
19.6 Localizing Images 585(2)
19.7 Localizing Included Files 587(1)
19.8 Sorting in a Locale-Aware Order 588(1)
19.9 Managing Localization Resources 589(2)
19.10 Setting the Character Encoding of 591(1)
Outgoing Data
19.11 Setting the Character Encoding of 592(1)
Incoming Data
19.12 Manipulating UTF-8 Text 593(6)
20 Error Handling 599(22)
20.1 Finding and Fixing Parse Errors 600(2)
20.2 Creating Your Own Exception Classes 602(3)
20.3 Printing a Stack Trace 605(3)
20.4 Reading Configuration Variables 608(2)
20.5 Setting Configuration Variables 610(1)
20.6 Hiding Error Messages from Users 610(2)
20.7 Tuning Error Handling 612(2)
20.8 Using a Custom Error Handler 614(1)
20.9 Logging Errors 615(2)
20.10 Eliminating "headers already sent" 617(1)
Errors
20.11 Logging Debugging Information 618(3)
21 Software Engineering 621(14)
21.1 Using a Debugger Extension 621(4)
21.2 Writing a Unit Test 625(1)
21.3 Writing a Unit Test Suite 626(2)
21.4 Applying a Unit Test to a Web Page 628(2)
21.5 Setting Up a Test Environment 630(1)
21.6 Using the Built-in Web Server 631(4)
22 Performance Tuning 635(18)
22.1 Using an Accelerator 636(1)
22.2 Timing Function Execution 637(1)
22.3 Timing Program Execution by Function 638(2)
22.4 Timing Program Execution by Statement 640(2)
22.5 Timing Program Execution by Section 642(2)
22.6 Profiling with a Debugger Extension 644(4)
22.7 Stress-Testing Your Website 648(1)
22.8 Avoiding Regular Expressions 649(4)
23 Regular Expressions 653(20)
23.1 Switching from ereg to preg 657(2)
23.2 Matching Words 659(1)
23.3 Finding the nth Occurrence of a Match 660(2)
23.4 Choosing Greedy or Nongreedy Matches 662(2)
23.5 Finding All Lines in a File That Match a 664(1)
Pattern
23.6 Capturing Text Inside HTML Tags 665(1)
23.7 Preventing Parentheses from Capturing 666(2)
Text
23.8 Escaping Special Characters in a Regular 668(1)
Expression
23.9 Reading Records with a Pattern Separator 669(1)
23.10 Using a PHP Function in a Regular 670(3)
Expression
24 Files 673(38)
24.1 Creating or Opening a Local File 677(1)
24.2 Creating a Temporary File 678(1)
24.3 Opening a Remote File 679(1)
24.4 Reading from Standard Input 680(1)
24.5 Reading a File into a String 681(1)
24.6 Counting Lines, Paragraphs, or Records 682(3)
in a File
24.7 Processing Every Word in a File 685(2)
24.8 Picking a Random Line from a File 687(1)
24.9 Randomizing All Lines in a File 687(1)
24.10 Processing Variable-Length Text Fields 688(2)
24.11 Reading Configuration Files 690(2)
24.12 Modifying a File in Place Without a 692(1)
Temporary File
24.13 Flushing Output to a File 693(1)
24.14 Writing to Standard Output 694(1)
24.15 Writing to Many Filehandles 695(1)
Simultaneously
24.16 Escaping Shell Metacharacters 696(1)
24.17 Passing Input to a Program 697(1)
24.18 Reading Standard Output from a Program 698(2)
24.19 Reading Standard Error from a Program 700(1)
24.20 Locking a File 701(2)
24.21 Reading and Writing Custom File Types 703(5)
24.22 Reading and Writing Compressed Files 708(3)
25 Directories 711(22)
25.1 Getting and Setting File-Timestamps 714(1)
25.2 Getting File Information 715(1)
25.3 Changing File Permissions or Ownership 716(1)
25.4 Splitting a Filename into Its Component 717(2)
Parts
25.5 Deleting a File 719(1)
25.6 Copying or Moving a File 719(1)
25.7 Processing All Files in a Directory 720(1)
25.8 Getting a List of Filenames Matching a 721(2)
Pattern
25.9 Processing All Files in a Directory 723(1)
Recursively
25.10 Making New Directories 723(1)
25.11 Removing a Directory and Its Contents 724(1)
25.12 Program: Web Server Directory Listing 725(4)
25.13 Program: Site Search 729(4)
26 Command-Line PHP 733(18)
26.1 Parsing Program Arguments 735(1)
26.2 Parsing Program Arguments with getopt 736(2)
26.3 Reading from the Keyboard 738(2)
26.4 Running PHP Code on Every Line of an 740(2)
Input File
26.5 Reading Passwords 742(2)
26.6 Colorizing Console Output 744(2)
26.7 Program: DOM Explorer 746(5)
27 Packages 751(22)
27.1 Defining and Installing Composer 754(1)
Dependencies
27.2 Finding Composer Packages 755(2)
27.3 Installing Composer Packages 757(3)
27.4 Using the PEAR Installer 760(3)
27.5 Finding PEAR Packages 763(2)
27.6 Finding Information About a Package 765(1)
27.7 Installing PEAR Packages 766(2)
27.8 Upgrading PEAR Packages 768(1)
27.9 Uninstalling PEAR Packages 769(1)
27.10 Installing PECL Packages 770(3)
Index 773