📄 Page
1
Kevin Tatroe & Peter MacIntyre Foreword by Michael Stowe Programming PHP Creating Dynamic Web Pages 4th Edition Covers Version 7.4
📄 Page
2
(This page has no text content)
📄 Page
3
Praise for the 4th Edition of Programming PHP PHP 7 has rejuvenated the PHP ecosystem, providing a powerful mix of world-class performance and highly anticipated features. If you’re after the book that would help you unlock this potential, look no further than the new edition of Programming PHP! —Zeev Suraski, Cocreator of PHP By selecting Programming PHP you have taken that first step not only into PHP and its basics but into the future of website and web application development. With a firm understanding of the PHP programming language, and the tools available to you, the only limitations will be your imagination and your willingness to continue to grow and immerse yourself in the community. —Michael Stowe, Author, Speaker, and Technologist Covers all the details you’d expect in a programming language book and gets into more advanced topics that seasoned veterans would find interesting. —James Thoms, Senior Developer at ClearDev
📄 Page
4
(This page has no text content)
📄 Page
5
Kevin Tatroe and Peter MacIntyre Programming PHP Creating Dynamic Web Pages FOURTH EDITION Boston Farnham Sebastopol TokyoBeijing
📄 Page
6
978-1-492-05413-9 [LSI] Programming PHP by Kevin Tatroe and Peter MacIntyre Copyright © 2020 Kevin Tatroe and Peter MacIntyre. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://oreilly.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com. Acquisitions Editor: Jennifer Pollock Development Editor: Angela Rufino Production Editor: Christopher Faucher Copyeditor: Rachel Monaghan Proofreader: Tom Sullivan Indexer: Potomac Indexing, LLC Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Rebecca Demarest March 2002: First Edition April 2006: Second Edition February 2013: Third Edition March 2020: Fourth Edition Revision History for the Fourth Edition 2020-03-12: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781492054139 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Programming PHP, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. The views expressed in this work are those of the authors, and do not represent the publisher’s views. While the publisher and the authors have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the authors disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights.
📄 Page
7
To Jenn —KT I would like to dedicate my portions of this book to my still wonderful wife, Dawn Etta Riley. I love you! —PBM
📄 Page
8
(This page has no text content)
📄 Page
9
Table of Contents Foreword. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix 1. Introduction to PHP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 What Does PHP Do? 1 A Brief History of PHP 2 The Evolution of PHP 2 The Widespread Use of PHP 7 Installing PHP 7 A Walk Through PHP 8 Configuration Page 9 Forms 10 Databases 11 Graphics 13 What’s Next 14 2. Language Basics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 Lexical Structure 15 Case Sensitivity 15 Statements and Semicolons 16 Whitespace and Line Breaks 16 Comments 17 Literals 20 Identifiers 20 Keywords 21 Data Types 22 vii
📄 Page
10
Integers 22 Floating-Point Numbers 23 Strings 24 Booleans 25 Arrays 26 Objects 27 Resources 28 Callbacks 29 NULL 29 Variables 30 Variable Variables 30 Variable References 30 Variable Scope 31 Garbage Collection 33 Expressions and Operators 35 Number of Operands 36 Operator Precedence 36 Operator Associativity 37 Implicit Casting 37 Arithmetic Operators 38 String Concatenation Operator 39 Auto-Increment and Auto-Decrement Operators 40 Comparison Operators 41 Bitwise Operators 42 Logical Operators 44 Casting Operators 45 Assignment Operators 46 Miscellaneous Operators 48 Flow-Control Statements 49 if 49 switch 51 while 53 for 55 foreach 57 try...catch 57 declare 58 exit and return 58 goto 59 Including Code 59 Embedding PHP in Web Pages 61 Standard (XML) Style 62 viii | Table of Contents
📄 Page
11
SGML Style 63 Echoing Content Directly 63 What’s Next 64 3. Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 Calling a Function 65 Defining a Function 67 Variable Scope 69 Global Variables 69 Static Variables 70 Function Parameters 71 Passing Parameters by Value 71 Passing Parameters by Reference 71 Default Parameters 72 Variable Parameters 73 Missing Parameters 74 Type Hinting 74 Return Values 75 Variable Functions 76 Anonymous Functions 77 What’s Next 79 4. Strings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 Quoting String Constants 81 Variable Interpolation 81 Single-Quoted Strings 82 Double-Quoted Strings 83 Here Documents 83 Printing Strings 85 echo 85 print() 86 printf() 86 print_r() and var_dump() 88 Accessing Individual Characters 89 Cleaning Strings 90 Removing Whitespace 90 Changing Case 91 Encoding and Escaping 91 HTML 92 URLs 94 SQL 96 Table of Contents | ix
📄 Page
12
C-String Encoding 96 Comparing Strings 97 Exact Comparisons 97 Approximate Equality 99 Manipulating and Searching Strings 100 Substrings 100 Miscellaneous String Functions 101 Decomposing a String 102 String-Searching Functions 104 Regular Expressions 106 The Basics 107 Character Classes 108 Alternatives 109 Repeating Sequences 109 Subpatterns 110 Delimiters 110 Match Behavior 111 Character Classes 111 Anchors 112 Quantifiers and Greed 113 Noncapturing Groups 114 Backreferences 114 Trailing Options 114 Inline Options 116 Lookahead and Lookbehind 116 Cut 118 Conditional Expressions 118 Functions 119 Differences from Perl Regular Expressions 124 What’s Next 124 5. Arrays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 Indexed Versus Associative Arrays 125 Identifying Elements of an Array 126 Storing Data in Arrays 127 Appending Values to an Array 128 Assigning a Range of Values 128 Getting the Size of an Array 129 Padding an Array 129 Multidimensional Arrays 129 Extracting Multiple Values 130 x | Table of Contents
📄 Page
13
Slicing an Array 131 Splitting an Array into Chunks 131 Keys and Values 132 Checking Whether an Element Exists 132 Removing and Inserting Elements in an Array 133 Converting Between Arrays and Variables 134 Creating Variables from an Array 135 Creating an Array from Variables 135 Traversing Arrays 135 The foreach Construct 136 The Iterator Functions 136 Using a for Loop 138 Calling a Function for Each Array Element 138 Reducing an Array 139 Searching for Values 140 Sorting 142 Sorting One Array at a Time 142 Natural-Order Sorting 144 Sorting Multiple Arrays at Once 145 Reversing Arrays 145 Randomizing Order 146 Acting on Entire Arrays 147 Calculating the Sum of an Array 147 Merging Two Arrays 147 Calculating the Difference Between Two Arrays 147 Filtering Elements from an Array 148 Using Arrays to Implement Data Types 149 Sets 149 Stacks 149 Implementing the Iterator Interface 151 What’s Next 153 6. Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 Objects 155 Terminology 156 Creating an Object 157 Accessing Properties and Methods 157 Declaring a Class 159 Declaring Methods 159 Declaring Properties 162 Declaring Constants 163 Table of Contents | xi
📄 Page
14
Inheritance 164 Interfaces 165 Traits 165 Abstract Methods 168 Constructors 169 Destructors 170 Anonymous Classes 171 Introspection 171 Examining Classes 171 Examining an Object 173 Sample Introspection Program 174 Serialization 177 What’s Next 180 7. Dates and Times. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 What’s Next 185 8. Web Techniques. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 HTTP Basics 187 Variables 188 Server Information 189 Processing Forms 191 Methods 191 Parameters 192 Self-Processing Pages 194 Sticky Forms 196 Multivalued Parameters 197 Sticky Multivalued Parameters 199 File Uploads 200 Form Validation 202 Setting Response Headers 204 Different Content Types 205 Redirections 205 Expiration 205 Authentication 206 Maintaining State 207 Cookies 208 Sessions 212 Combining Cookies and Sessions 215 SSL 216 What’s Next 216 xii | Table of Contents
📄 Page
15
9. Databases. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 Using PHP to Access a Database 217 Relational Databases and SQL 218 PHP Data Objects 219 MySQLi Object Interface 223 Retrieving Data for Display 225 SQLite 226 Direct File-Level Manipulation 229 MongoDB 237 Retrieving Data 241 Inserting More Complex Data 242 What’s Next 245 10. Graphics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247 Embedding an Image in a Page 247 Basic Graphics Concepts 248 Creating and Drawing Images 249 The Structure of a Graphics Program 250 Changing the Output Format 251 Testing for Supported Image Formats 252 Reading an Existing File 252 Basic Drawing Functions 253 Images with Text 254 Fonts 255 TrueType Fonts 256 Dynamically Generated Buttons 258 Caching the Dynamically Generated Buttons 259 A Faster Cache 260 Scaling Images 262 Color Handling 264 Using the Alpha Channel 265 Identifying Colors 266 True Color Indexes 267 Text Representation of an Image 268 What’s Next 269 11. PDF. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271 PDF Extensions 271 Documents and Pages 271 A Simple Example 272 Initializing the Document 272 Table of Contents | xiii
📄 Page
16
Outputting Basic Text Cells 273 Text 273 Coordinates 273 Text Attributes 276 Page Headers, Footers, and Class Extension 278 Images and Links 280 Tables and Data 283 What’s Next 285 12. XML. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287 Lightning Guide to XML 287 Generating XML 289 Parsing XML 291 Element Handlers 291 Character Data Handler 292 Processing Instructions 293 Entity Handlers 293 Default Handler 295 Options 296 Using the Parser 297 Errors 298 Methods as Handlers 299 Sample Parsing Application 300 Parsing XML with the DOM 304 Parsing XML with SimpleXML 305 Transforming XML with XSLT 306 What’s Next 308 13. JSON. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309 Using JSON 309 Serializing PHP Objects 310 Options 312 What’s Next 313 14. Security. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 Safeguards 315 Filtering Input 316 Escaping Output Data 318 Security Vulnerabilities 322 Cross-Site Scripting 322 SQL Injection 323 xiv | Table of Contents
📄 Page
17
Filename Vulnerabilities 324 Session Fixation 326 File Upload Traps 327 Unauthorized File Access 328 PHP Code Issues 331 Shell Command Weaknesses 332 Data Encryption Concerns 333 Further Resources 333 Security Recap 333 What’s Next 334 15. Application Techniques. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335 Code Libraries 335 Templating Systems 336 Handling Output 339 Output Buffering 339 Output Compression 341 Performance Tuning 342 Benchmarking 343 Profiling 344 Optimizing Execution Time 346 Optimizing Memory Requirements 346 Reverse Proxies and Replication 347 What’s Next 349 16. Web Services. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 REST Clients 351 Responses 353 Retrieving Resources 354 Updating Resources 355 Creating Resources 356 Deleting Resources 356 XML-RPC 357 Servers 357 Clients 359 What’s Next 360 17. Debugging PHP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361 The Development Environment 361 The Staging Environment 362 The Production Environment 363 Table of Contents | xv
📄 Page
18
php.ini Settings 363 Error Handling 365 Error Reporting 365 Exceptions 366 Error Suppression 367 Triggering Errors 367 Defining Error Handlers 368 Manual Debugging 371 Error Logs 373 IDE Debugging 374 Additional Debugging Techniques 376 What’s Next 376 18. PHP on Disparate Platforms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377 Writing Portable Code for Windows and Unix 377 Determining the Platform 378 Handling Paths Across Platforms 378 Navigating the Server Environment 378 Sending Mail 379 End-of-Line Handling 380 End-of-File Handling 380 Using External Commands 381 Accessing Platform-Specific Extensions 381 Interfacing with COM 381 Background 381 PHP Functions 383 API Specifications 384 Function Reference. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493 xvi | Table of Contents
📄 Page
19
Foreword It’s hard to believe that nearly 20 years ago I picked up my first PHP book. I had an interest in programming, extending beyond Netscape Composer and static HTML. I knew PHP would enable me to create dynamic, smarter websites—and to store and fetch data to create interactive web applications. What I didn’t know was the journey that unlocking these new capabilities with PHP would take me on, or how PHP would evolve 20 years later to become the program‐ ming language powering roughly 80% of the web, and backed by one of the nicest, friendliest, and most engaging communities. A journey of a thousand miles begins with a single step. By selecting Programming PHP by Peter MacIntyre and Kevin Tatroe, you have taken that first step not only into PHP and its basics, but also into the future of website and web application develop‐ ment. With the available tools and a firm understanding of the PHP programming language, the only limitation will be your imagination and your willingness to con‐ tinue to grow and immerse yourself in the community. The journey is yours, the pos‐ sibilities endless, and the future for you to define. As you get ready to begin this journey, I would like to share a couple tidbits of advice. First, take each chapter and put it into practice, try different things, and don’t be afraid of breaking something or failing. While Programming PHP will establish a strong foundation, it’s up to you to explore the language and find new and creative ways to pull together all of these components. My second piece of advice: be an active part of the PHP community. Take advantage of online communities, user groups, and PHP conferences as you are able. As you try new things, share them with the community for their feedback and advice. Not only are you sure to find a community of support—a group of some of the nicest people, who want you to succeed and are more than happy to take their time to help you through your journey—but you’ll also establish a baseline of continuous learning, helping you grasp the core skills of PHP more quickly and keeping you up to date on xvii
📄 Page
20
new programming theories, technologies, tools, and changes. Not to mention, you’ll encounter an onslaught of terrible puns (including from yours truly). With that, I would like to be among the first to welcome you and to wish you the very best on your journey—a journey that couldn’t start off better than with this book! — Michael Stowe, author, speaker, and technologist San Francisco, California, Winter 2020 xviii | Foreword