Statistics
50
Views
0
Downloads
0
Donations
Uploader

高宏飞

Shared on 2025-12-05
Support
Share

AuthorGoalKicker.com

No description

Tags
No tags
Publisher: PHP group(s), company(s)
Publish Year: 2018
Language: 英文
Pages: 481
File Format: PDF
File Size: 3.5 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

PHP Notes for ProfessionalsPHP Notes for Professionals GoalKicker.com Free Programming Books Disclaimer This is an unocial free book created for educational purposes and is not aliated with ocial PHP group(s) or company(s). All trademarks and registered trademarks are the property of their respective owners 400+ pages of professional hints and tricks
Contents About 1 ................................................................................................................................................................................... Chapter 1: Getting started with PHP 2 ................................................................................................................... Section 1.1: HTML output from web server 2 .................................................................................................................. Section 1.2: Hello, World! 3 ............................................................................................................................................... Section 1.3: Non-HTML output from web server 3 ........................................................................................................ Section 1.4: PHP built-in server 5 ..................................................................................................................................... Section 1.5: PHP CLI 5 ....................................................................................................................................................... Section 1.6: Instruction Separation 6 ............................................................................................................................... Section 1.7: PHP Tags 7 .................................................................................................................................................... Chapter 2: Variables 9 .................................................................................................................................................... Section 2.1: Accessing A Variable Dynamically By Name (Variable variables) 9 ...................................................... Section 2.2: Data Types 10 .............................................................................................................................................. Section 2.3: Global variable best practices 13 ............................................................................................................... Section 2.4: Default values of uninitialized variables 14 .............................................................................................. Section 2.5: Variable Value Truthiness and Identical Operator 15 ............................................................................. Chapter 3: Variable Scope 18 ..................................................................................................................................... Section 3.1: Superglobal variables 18 ............................................................................................................................. Section 3.2: Static properties and variables 18 ............................................................................................................. Section 3.3: User-defined global variables 19 ............................................................................................................... Chapter 4: Outputting the Value of a Variable 21 .......................................................................................... Section 4.1: echo and print 21 .......................................................................................................................................... Section 4.2: Outputting a structured view of arrays and objects 22 .......................................................................... Section 4.3: String concatenation with echo 24 ............................................................................................................. Section 4.4: printf vs sprintf 25 ........................................................................................................................................ Section 4.5: Outputting large integers 25 ...................................................................................................................... Section 4.6: Output a Multidimensional Array with index and value and print into the table 26 ............................. Chapter 5: Constants 28 ................................................................................................................................................ Section 5.1: Defining constants 28 .................................................................................................................................. Section 5.2: Class Constants 29 ...................................................................................................................................... Section 5.3: Checking if constant is defined 29 ............................................................................................................. Section 5.4: Using constants 31 ...................................................................................................................................... Section 5.5: Constant arrays 31 ...................................................................................................................................... Chapter 6: Comments 32 ............................................................................................................................................... Section 6.1: Single Line Comments 32 ............................................................................................................................ Section 6.2: Multi Line Comments 32 .............................................................................................................................. Chapter 7: Types 33 ......................................................................................................................................................... Section 7.1: Type Comparison 33 .................................................................................................................................... Section 7.2: Boolean 33 .................................................................................................................................................... Section 7.3: Float 34 ......................................................................................................................................................... Section 7.4: Strings 35 ...................................................................................................................................................... Section 7.5: Callable 37 .................................................................................................................................................... Section 7.6: Resources 37 ................................................................................................................................................ Section 7.7: Type Casting 38 ........................................................................................................................................... Section 7.8: Type Juggling 38 ......................................................................................................................................... Section 7.9: Null 39 ........................................................................................................................................................... Section 7.10: Integers 39 ...................................................................................................................................................
Chapter 8: Operators 41 ............................................................................................................................................... Section 8.1: Null Coalescing Operator (??) 41 ................................................................................................................ Section 8.2: Spaceship Operator (<=>) 42 ...................................................................................................................... Section 8.3: Execution Operator (``) 42 ........................................................................................................................... Section 8.4: Incrementing (++) and Decrementing Operators (--) 42 ........................................................................ Section 8.5: Ternary Operator (?:) 43 ............................................................................................................................. Section 8.6: Logical Operators (&&/AND and ||/OR) 44 .............................................................................................. Section 8.7: String Operators (. and .=) 44 ..................................................................................................................... Section 8.8: Object and Class Operators 44 .................................................................................................................. Section 8.9: Combined Assignment (+= etc) 46 ............................................................................................................. Section 8.10: Altering operator precedence (with parentheses) 46 ............................................................................ Section 8.11: Basic Assignment (=) 47 ............................................................................................................................. Section 8.12: Association 47 ............................................................................................................................................. Section 8.13: Comparison Operators 47 ......................................................................................................................... Section 8.14: Bitwise Operators 49 .................................................................................................................................. Section 8.15: instanceof (type operator) 51 ................................................................................................................... Chapter 9: References 54 ............................................................................................................................................. Section 9.1: Assign by Reference 54 ............................................................................................................................... Section 9.2: Return by Reference 54 .............................................................................................................................. Section 9.3: Pass by Reference 55 .................................................................................................................................. Chapter 10: Arrays 58 ...................................................................................................................................................... Section 10.1: Initializing an Array 58 ................................................................................................................................ Section 10.2: Check if key exists 60 ................................................................................................................................. Section 10.3: Validating the array type 61 ..................................................................................................................... Section 10.4: Creating an array of variables 61 ............................................................................................................ Section 10.5: Checking if a value exists in array 61 ....................................................................................................... Section 10.6: ArrayAccess and Iterator Interfaces 62 ................................................................................................... Chapter 11: Array iteration 66 ..................................................................................................................................... Section 11.1: Iterating multiple arrays together 66 ......................................................................................................... Section 11.2: Using an incremental index 67 .................................................................................................................. Section 11.3: Using internal array pointers 67 ................................................................................................................ Section 11.4: Using foreach 68 ......................................................................................................................................... Section 11.5: Using ArrayObject Iterator 70 .................................................................................................................... Chapter 12: Executing Upon an Array 71 .............................................................................................................. Section 12.1: Applying a function to each element of an array 71 .............................................................................. Section 12.2: Split array into chunks 72 .......................................................................................................................... Section 12.3: Imploding an array into string 73 ............................................................................................................. Section 12.4: "Destructuring" arrays using list() 73 ....................................................................................................... Section 12.5: array_reduce 73 ......................................................................................................................................... Section 12.6: Push a Value on an Array 74 ..................................................................................................................... Chapter 13: Manipulating an Array 76 .................................................................................................................... Section 13.1: Filtering an array 76 .................................................................................................................................... Section 13.2: Removing elements from an array 77 ..................................................................................................... Section 13.3: Sorting an Array 78 .................................................................................................................................... Section 13.4: Whitelist only some array keys 83 ............................................................................................................ Section 13.5: Adding element to start of array 83 ......................................................................................................... Section 13.6: Exchange values with keys 84 ................................................................................................................... Section 13.7: Merge two arrays into one array 84 ......................................................................................................... Chapter 14: Processing Multiple Arrays Together 86 .....................................................................................
Section 14.1: Array intersection 86 ................................................................................................................................... Section 14.2: Merge or concatenate arrays 86 .............................................................................................................. Section 14.3: Changing a multidimensional array to associative array 87 ................................................................ Section 14.4: Combining two arrays (keys from one, values from another) 87 ........................................................ Chapter 15: Datetime Class 89 ................................................................................................................................... Section 15.1: Create Immutable version of DateTime from Mutable prior PHP 5.6 89 .............................................. Section 15.2: Add or Subtract Date Intervals 89 ............................................................................................................ Section 15.3: getTimestamp 89 ........................................................................................................................................ Section 15.4: setDate 90 ................................................................................................................................................... Section 15.5: Create DateTime from custom format 90 ............................................................................................... Section 15.6: Printing DateTimes 90 ................................................................................................................................ Chapter 16: Working with Dates and Time 92 .................................................................................................... Section 16.1: Getting the dierence between two dates / times 92 ............................................................................. Section 16.2: Convert a date into another format 92 .................................................................................................... Section 16.3: Parse English date descriptions into a Date format 94 .......................................................................... Section 16.4: Using Predefined Constants for Date Format 94 .................................................................................... Chapter 17: Loops 96 ....................................................................................................................................................... Section 17.1: continue 96 ................................................................................................................................................... Section 17.2: break 97 ....................................................................................................................................................... Section 17.3: foreach 98 ................................................................................................................................................... Section 17.4: do...while 98 .................................................................................................................................................. Section 17.5: for 99 ............................................................................................................................................................ Section 17.6: while 100 ...................................................................................................................................................... Chapter 18: Functions 101 ............................................................................................................................................. Section 18.1: Variable-length argument lists 101 ........................................................................................................... Section 18.2: Optional Parameters 102 .......................................................................................................................... Section 18.3: Passing Arguments by Reference 103 ..................................................................................................... Section 18.4: Basic Function Usage 104 ......................................................................................................................... Section 18.5: Function Scope 104 .................................................................................................................................... Chapter 19: Functional Programming 105 ............................................................................................................ Section 19.1: Closures 105 ................................................................................................................................................. Section 19.2: Assignment to variables 106 ..................................................................................................................... Section 19.3: Objects as a function 106 .......................................................................................................................... Section 19.4: Using outside variables 107 ...................................................................................................................... Section 19.5: Anonymous function 107 ........................................................................................................................... Section 19.6: Pure functions 108 ...................................................................................................................................... Section 19.7: Common functional methods in PHP 108 ................................................................................................ Section 19.8: Using built-in functions as callbacks 109 ................................................................................................. Section 19.9: Scope 109 .................................................................................................................................................... Section 19.10: Passing a callback function as a parameter 109 .................................................................................. Chapter 20: Control Structures 111 ......................................................................................................................... Section 20.1: if else 111 .................................................................................................................................................... Section 20.2: Alternative syntax for control structures 111 ......................................................................................... Section 20.3: while 111 ..................................................................................................................................................... Section 20.4: do-while 112 ............................................................................................................................................... Section 20.5: goto 112 ..................................................................................................................................................... Section 20.6: declare 112 ................................................................................................................................................. Section 20.7: include & require 113 ................................................................................................................................ Section 20.8: return 114 ................................................................................................................................................... Section 20.9: for 114 ........................................................................................................................................................
Section 20.10: foreach 115 ............................................................................................................................................... Section 20.11: if elseif else 115 ......................................................................................................................................... Section 20.12: if 116 .......................................................................................................................................................... Section 20.13: switch 116 .................................................................................................................................................. Chapter 21: Alternative Syntax for Control Structures 118 ......................................................................... Section 21.1: Alternative if/else statement 118 .............................................................................................................. Section 21.2: Alternative for statement 118 ................................................................................................................... Section 21.3: Alternative while statement 118 ............................................................................................................... Section 21.4: Alternative foreach statement 118 ........................................................................................................... Section 21.5: Alternative switch statement 119 ............................................................................................................. Chapter 22: String Parsing 120 ................................................................................................................................... Section 22.1: Splitting a string by separators 120 ......................................................................................................... Section 22.2: Substring 120 ............................................................................................................................................. Section 22.3: Searching a substring with strpos 122 .................................................................................................... Section 22.4: Parsing string using regular expressions 123 ......................................................................................... Chapter 23: String formatting 124 ........................................................................................................................... Section 23.1: String interpolation 124 ............................................................................................................................. Section 23.2: Extracting/replacing substrings 125 ....................................................................................................... Chapter 24: Exception Handling and Error Reporting 127 .......................................................................... Section 24.1: Setting error reporting and where to display them 127 ........................................................................ Section 24.2: Logging fatal errors 127 ........................................................................................................................... Chapter 25: Sending Email 129 ................................................................................................................................... Section 25.1: Sending Email - The basics, more details, and a full example 129 ....................................................... Section 25.2: Sending HTML Email Using mail() 131 .................................................................................................... Section 25.3: Sending Email With An Attachment Using mail() 132 ............................................................................ Section 25.4: Sending Plain Text Email Using PHPMailer 133 ...................................................................................... Section 25.5: Sending HTML Email Using PHPMailer 134 ............................................................................................ Section 25.6: Sending Email With An Attachment Using PHPMailer 135 .................................................................... Section 25.7: Sending Plain Text Email Using Sendgrid 135 ........................................................................................ Section 25.8: Sending Email With An Attachment Using Sendgrid 136 ...................................................................... Chapter 26: Sessions 137 ............................................................................................................................................... Section 26.1: session_start() Options 137 ...................................................................................................................... Section 26.2: Session Locking 137 .................................................................................................................................. Section 26.3: Manipulating session data 138 ................................................................................................................. Section 26.4: Destroy an entire session 138 .................................................................................................................. Section 26.5: Safe Session Start With no Errors 139 ..................................................................................................... Section 26.6: Session name 139 ...................................................................................................................................... Chapter 27: Cookies 141 ................................................................................................................................................ Section 27.1: Modifying a Cookie 141 ............................................................................................................................. Section 27.2: Setting a Cookie 141 ................................................................................................................................. Section 27.3: Checking if a Cookie is Set 142 ................................................................................................................. Section 27.4: Removing a Cookie 142 ............................................................................................................................ Section 27.5: Retrieving a Cookie 142 ............................................................................................................................ Chapter 28: Classes and Objects 143 ...................................................................................................................... Section 28.1: Class Constants 143 ................................................................................................................................... Section 28.2: Abstract Classes 145 ................................................................................................................................. Section 28.3: Late static binding 147 .............................................................................................................................. Section 28.4: Namespacing and Autoloading 148 ........................................................................................................ Section 28.5: Method and Property Visibility 150 ..........................................................................................................
Section 28.6: Interfaces 152 ............................................................................................................................................ Section 28.7: Final Keyword 155 ..................................................................................................................................... Section 28.8: Autoloading 156 ......................................................................................................................................... Section 28.9: Calling a parent constructor when instantiating a child 157 ................................................................ Section 28.10: Dynamic Binding 158 ............................................................................................................................... Section 28.11: $this, self and static plus the singleton 159 ............................................................................................ Section 28.12: Defining a Basic Class 162 ...................................................................................................................... Section 28.13: Anonymous Classes 163 .......................................................................................................................... Chapter 29: Namespaces 165 ...................................................................................................................................... Section 29.1: Declaring namespaces 165 ....................................................................................................................... Section 29.2: Referencing a class or function in a namespace 165 ........................................................................... Section 29.3: Declaring sub-namespaces 166 .............................................................................................................. Section 29.4: What are Namespaces? 167 .................................................................................................................... Chapter 30: Output Buering 168 ............................................................................................................................ Section 30.1: Basic usage getting content between buers and clearing 168 .......................................................... Section 30.2: Processing the buer via a callback 168 ................................................................................................ Section 30.3: Nested output buers 169 ........................................................................................................................ Section 30.4: Running output buer before any content 170 ..................................................................................... Section 30.5: Stream output to client 171 ...................................................................................................................... Section 30.6: Using Output buer to store contents in a file, useful for reports, invoices etc 171 .......................... Section 30.7: Typical usage and reasons for using ob_start 171 ............................................................................... Section 30.8: Capturing the output buer to re-use later 172 .................................................................................... Chapter 31: Superglobal Variables PHP 174 ........................................................................................................ Section 31.1: Suberglobals explained 174 ....................................................................................................................... Section 31.2: PHP5 SuperGlobals 181 ............................................................................................................................. Chapter 32: JSON 185 ...................................................................................................................................................... Section 32.1: Decoding a JSON string 185 ..................................................................................................................... Section 32.2: Encoding a JSON string 188 ..................................................................................................................... Section 32.3: Debugging JSON errors 191 .................................................................................................................... Section 32.4: Using JsonSerializable in an Object 192 ................................................................................................. Section 32.5: Header json and the returned response 193 .......................................................................................... Chapter 33: SOAP Client 195 ........................................................................................................................................ Section 33.1: WSDL Mode 195 .......................................................................................................................................... Section 33.2: Non-WSDL Mode 195 ................................................................................................................................ Section 33.3: Classmaps 195 ........................................................................................................................................... Section 33.4: Tracing SOAP request and response 196 ............................................................................................... Chapter 34: Using cURL in PHP 198 ......................................................................................................................... Section 34.1: Basic Usage (GET Requests) 198 ............................................................................................................. Section 34.2: POST Requests 198 ................................................................................................................................... Section 34.3: Using Cookies 199 ...................................................................................................................................... Section 34.4: Using multi_curl to make multiple POST requests 200 ......................................................................... Section 34.5: Sending multi-dimensional data and multiple files with CurlFile in one request 201 ......................... Section 34.6: Creating and sending a request with a custom method 204 ................................................................ Section 34.7: Get and Set custom http headers in php 204 ......................................................................................... Chapter 35: Reflection 206 ........................................................................................................................................... Section 35.1: Feature detection of classes or objects 206 ............................................................................................ Section 35.2: Testing private/protected methods 206 ................................................................................................. Section 35.3: Accessing private and protected member variables 208 ..................................................................... Chapter 36: Dependency Injection 210 ...................................................................................................................
Section 36.1: Constructor Injection 210 ........................................................................................................................... Section 36.2: Setter Injection 210 .................................................................................................................................... Section 36.3: Container Injection 212 .............................................................................................................................. Chapter 37: XML 213 ........................................................................................................................................................ Section 37.1: Create a XML using DomDocument 213 .................................................................................................. Section 37.2: Read a XML document with DOMDocument 214 ................................................................................... Section 37.3: Leveraging XML with PHP's SimpleXML Library 215 .............................................................................. Section 37.4: Create an XML file using XMLWriter 217 ................................................................................................. Section 37.5: Read a XML document with SimpleXML 218 .......................................................................................... Chapter 38: Parsing HTML 220 ................................................................................................................................... Section 38.1: Parsing HTML from a string 220 ............................................................................................................... Section 38.2: Using XPath 220 ......................................................................................................................................... Section 38.3: SimpleXML 220 ........................................................................................................................................... Chapter 39: SimpleXML 222 .......................................................................................................................................... Section 39.1: Loading XML data into simplexml 222 ..................................................................................................... Chapter 40: Regular Expressions (regexp/PCRE) 223 ................................................................................... Section 40.1: Global RegExp match 223 ......................................................................................................................... Section 40.2: String matching with regular expressions 224 ....................................................................................... Section 40.3: Split string into array by a regular expression 225 ................................................................................ Section 40.4: String replacing with regular expression 225 ......................................................................................... Section 40.5: String replace with callback 225 .............................................................................................................. Chapter 41: Traits 227 ..................................................................................................................................................... Section 41.1: What is a Trait? 227 .................................................................................................................................... Section 41.2: Traits to facilitate horizontal code reuse 228 .......................................................................................... Section 41.3: Conflict Resolution 229 .............................................................................................................................. Section 41.4: Implementing a Singleton using Traits 230 ............................................................................................. Section 41.5: Traits to keep classes clean 231 ............................................................................................................... Section 41.6: Multiple Traits Usage 232 .......................................................................................................................... Section 41.7: Changing Method Visibility 232 ................................................................................................................. Chapter 42: Composer Dependency Manager 234 .......................................................................................... Section 42.1: What is Composer? 234 ............................................................................................................................. Section 42.2: Autoloading with Composer 235 .............................................................................................................. Section 42.3: Dierence between 'composer install' and 'composer update' 235 .................................................... Section 42.4: Composer Available Commands 236 ...................................................................................................... Section 42.5: Benefits of Using Composer 237 ............................................................................................................. Section 42.6: Installation 238 ........................................................................................................................................... Chapter 43: Magic Methods 239 ................................................................................................................................ Section 43.1: __call() and __callStatic() 239 ................................................................................................................. Section 43.2: __get(), __set(), __isset() and __unset() 240 ...................................................................................... Section 43.3: __construct() and __destruct() 241 ....................................................................................................... Section 43.4: __toString() 242 ........................................................................................................................................ Section 43.5: __clone() 243 ............................................................................................................................................. Section 43.6: __invoke() 243 ........................................................................................................................................... Section 43.7: __sleep() and __wakeup() 244 ............................................................................................................... Section 43.8: __debugInfo() 244 .................................................................................................................................... Chapter 44: File handling 246 .................................................................................................................................... Section 44.1: Convenience functions 246 ....................................................................................................................... Section 44.2: Deleting files and directories 248 ............................................................................................................ Section 44.3: Getting file information 248 ......................................................................................................................
Section 44.4: Stream-based file IO 250 .......................................................................................................................... Section 44.5: Moving and Copying files and directories 252 ....................................................................................... Section 44.6: Minimize memory usage when dealing with large files 253 ................................................................. Chapter 45: Magic Constants 254 ............................................................................................................................. Section 45.1: Dierence between __FUNCTION__ and __METHOD__ 254 ............................................................ Section 45.2: Dierence between __CLASS__, get_class() and get_called_class() 254 ....................................... Section 45.3: File & Directory Constants 255 ................................................................................................................. Chapter 46: Type hinting 256 ...................................................................................................................................... Section 46.1: Type hinting classes and interfaces 256 .................................................................................................. Section 46.2: Type hinting scalar types, arrays and callables 257 ............................................................................. Section 46.3: Nullable type hints 258 .............................................................................................................................. Section 46.4: Type hinting generic objects 259 ............................................................................................................. Section 46.5: Type Hinting No Return(Void) 260 .......................................................................................................... Chapter 47: Autoloading Primer 261 ...................................................................................................................... Section 47.1: Autoloading as part of a framework solution 261 .................................................................................. Section 47.2: Inline class definition, no loading required 261 ...................................................................................... Section 47.3: Manual class loading with require 262 .................................................................................................... Section 47.4: Autoloading replaces manual class definition loading 262 .................................................................. Section 47.5: Autoloading with Composer 263 .............................................................................................................. Chapter 48: Multi Threading Extension 264 ........................................................................................................ Section 48.1: Getting Started 264 .................................................................................................................................... Section 48.2: Using Pools and Workers 264 .................................................................................................................. Chapter 49: Filters & Filter Functions 266 ............................................................................................................ Section 49.1: Validating Boolean Values 266 ................................................................................................................. Section 49.2: Validating A Number Is A Float 266 ........................................................................................................ Section 49.3: Validate A MAC Address 267 .................................................................................................................... Section 49.4: Sanitze Email Addresses 267 .................................................................................................................... Section 49.5: Sanitize Integers 268 ................................................................................................................................. Section 49.6: Sanitize URLs 268 ...................................................................................................................................... Section 49.7: Validate Email Address 269 ...................................................................................................................... Section 49.8: Validating A Value Is An Integer 269 ....................................................................................................... Section 49.9: Validating An Integer Falls In A Range 270 ............................................................................................ Section 49.10: Validate a URL 270 .................................................................................................................................. Section 49.11: Sanitize Floats 272 .................................................................................................................................... Section 49.12: Validate IP Addresses 274 ....................................................................................................................... Section 49.13: Sanitize filters 275 ..................................................................................................................................... Chapter 50: Generators 276 ........................................................................................................................................ Section 50.1: The Yield Keyword 276 .............................................................................................................................. Section 50.2: Reading a large file with a generator 277 .............................................................................................. Section 50.3: Why use a generator? 277 ....................................................................................................................... Section 50.4: Using the send()-function to pass values to a generator 278 .............................................................. Chapter 51: UTF-8 280 ..................................................................................................................................................... Section 51.1: Input 280 ....................................................................................................................................................... Section 51.2: Output 280 .................................................................................................................................................. Section 51.3: Data Storage and Access 280 ................................................................................................................... Chapter 52: URLs 282 ...................................................................................................................................................... Section 52.1: Parsing a URL 282 ...................................................................................................................................... Section 52.2: Build an URL-encoded query string from an array 282 ....................................................................... Section 52.3: Redirecting to another URL 283 ...............................................................................................................
Chapter 53: Object Serialization 285 ....................................................................................................................... Section 53.1: Serialize / Unserialize 285 .......................................................................................................................... Section 53.2: The Serializable interface 285 .................................................................................................................. Chapter 54: PHPDoc 287 ............................................................................................................................................... Section 54.1: Describing a variable 287 .......................................................................................................................... Section 54.2: Adding metadata to functions 287 .......................................................................................................... Section 54.3: Describing parameters 288 ...................................................................................................................... Section 54.4: Collections 289 ........................................................................................................................................... Section 54.5: Adding metadata to files 290 ................................................................................................................... Section 54.6: Inheriting metadata from parent structures 290 ................................................................................... Chapter 55: Serialization 292 ...................................................................................................................................... Section 55.1: Serialization of dierent types 292 ........................................................................................................... Section 55.2: Security Issues with unserialize 293 ......................................................................................................... Chapter 56: Closure 296 ................................................................................................................................................. Section 56.1: Basic usage of a closure 296 .................................................................................................................... Section 56.2: Using external variables 296 .................................................................................................................... Section 56.3: Basic closure binding 297 ......................................................................................................................... Section 56.4: Closure binding and scope 297 ................................................................................................................ Section 56.5: Binding a closure for one call 299 ........................................................................................................... Section 56.6: Use closures to implement observer pattern 299 .................................................................................. Chapter 57: Reading Request Data 302 ................................................................................................................ Section 57.1: Reading raw POST data 302 ..................................................................................................................... Section 57.2: Reading POST data 302 ............................................................................................................................ Section 57.3: Reading GET data 302 .............................................................................................................................. Section 57.4: Handling file upload errors 303 ................................................................................................................ Section 57.5: Passing arrays by POST 303 .................................................................................................................... Section 57.6: Uploading files with HTTP PUT 305 ......................................................................................................... Chapter 58: Type juggling and Non-Strict Comparison Issues 306 ......................................................... Section 58.1: What is Type Juggling? 306 ...................................................................................................................... Section 58.2: Reading from a file 306 ............................................................................................................................ Section 58.3: Switch surprises 307 .................................................................................................................................. Section 58.4: Strict typing 308 ......................................................................................................................................... Chapter 59: Sockets 310 ................................................................................................................................................ Section 59.1: TCP client socket 310 ................................................................................................................................. Section 59.2: TCP server socket 311 .............................................................................................................................. Section 59.3: UDP server socket 311 .............................................................................................................................. Section 59.4: Handling socket errors 312 ...................................................................................................................... Chapter 60: PDO 313 ........................................................................................................................................................ Section 60.1: Preventing SQL injection with Parameterized Queries 313 ................................................................... Section 60.2: Basic PDO Connection and Retrieval 314 ............................................................................................... Section 60.3: Database Transactions with PDO 315 ..................................................................................................... Section 60.4: PDO: connecting to MySQL/MariaDB server 317 .................................................................................. Section 60.5: PDO: Get number of aected rows by a query 318 .............................................................................. Section 60.6: PDO::lastInsertId() 318 ............................................................................................................................... Chapter 61: PHP MySQLi 320 ........................................................................................................................................ Section 61.1: Close connection 320 .................................................................................................................................. Section 61.2: MySQLi connect 320 ................................................................................................................................... Section 61.3: Loop through MySQLi results 321 ............................................................................................................. Section 61.4: Prepared statements in MySQLi 321 ........................................................................................................
Section 61.5: Escaping Strings 322 .................................................................................................................................. Section 61.6: Debugging SQL in MySQLi 323 ................................................................................................................. Section 61.7: MySQLi query 323 ....................................................................................................................................... Section 61.8: How to get data from a prepared statement 324 .................................................................................. Section 61.9: MySQLi Insert ID 326 .................................................................................................................................. Chapter 62: SQLite3 328 ................................................................................................................................................. Section 62.1: SQLite3 Quickstart Tutorial 328 ................................................................................................................ Section 62.2: Querying a database 329 ......................................................................................................................... Section 62.3: Retrieving only one result 330 .................................................................................................................. Chapter 63: Using SQLSRV 331 ................................................................................................................................... Section 63.1: Retrieving Error Messages 331 ................................................................................................................. Section 63.2: Fetching Query Results 331 ...................................................................................................................... Section 63.3: Creating a Connection 332 ....................................................................................................................... Section 63.4: Making a Simple Query 332 ...................................................................................................................... Section 63.5: Invoking a Stored Procedure 332 ............................................................................................................. Section 63.6: Making a Parameterised Query 333 ........................................................................................................ Chapter 64: Command Line Interface (CLI) 334 ................................................................................................ Section 64.1: Handling Program Options 334 ................................................................................................................ Section 64.2: Argument Handling 335 ............................................................................................................................ Section 64.3: Input and Output Handling 336 ................................................................................................................ Section 64.4: Return Codes 337 ...................................................................................................................................... Section 64.5: Restrict script execution to command line 337 ...................................................................................... Section 64.6: Behavioural dierences on the command line 337 ............................................................................... Section 64.7: Running your script 338 ............................................................................................................................ Section 64.8: Edge Cases of getopt() 338 ...................................................................................................................... Section 64.9: Running built-in web server 339 ............................................................................................................... Chapter 65: Localization 341 ....................................................................................................................................... Section 65.1: Localizing strings with gettext() 341 ......................................................................................................... Chapter 66: Debugging 342 .......................................................................................................................................... Section 66.1: Dumping variables 342 .............................................................................................................................. Section 66.2: Displaying errors 342 ................................................................................................................................ Section 66.3: phpinfo() 343 .............................................................................................................................................. Section 66.4: Xdebug 343 ................................................................................................................................................ Section 66.5: Error Reporting (use them both) 344 ...................................................................................................... Section 66.6: phpversion() 344 ........................................................................................................................................ Chapter 67: Unit Testing 345 ....................................................................................................................................... Section 67.1: Testing class rules 345 ............................................................................................................................... Section 67.2: PHPUnit Data Providers 348 ..................................................................................................................... Section 67.3: Test exceptions 351 ................................................................................................................................... Chapter 68: Compilation of Errors and Warnings 353 ................................................................................... Section 68.1: Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM 353 ......................................... Section 68.2: Notice: Undefined index 353 ..................................................................................................................... Section 68.3: Warning: Cannot modify header information - headers already sent 353 ......................................... Chapter 69: Headers Manipulation 355 .................................................................................................................. Section 69.1: Basic Setting of a Header 355 .................................................................................................................. Chapter 70: Contributing to the PHP Core 356 .................................................................................................. Section 70.1: Setting up a basic development environment 356 ................................................................................. Chapter 71: Coding Conventions 357 ....................................................................................................................... Section 71.1: PHP Tags 357 ...............................................................................................................................................
Chapter 72: Using MongoDB 358 ............................................................................................................................... Section 72.1: Connect to MongoDB 358 ......................................................................................................................... Section 72.2: Get multiple documents - find() 358 ........................................................................................................ Section 72.3: Get one document - findOne() 358 .......................................................................................................... Section 72.4: Insert document 358 ................................................................................................................................. Section 72.5: Update a document 358 ........................................................................................................................... Section 72.6: Delete a document 359 ............................................................................................................................. Chapter 73: mongo-php 360 ........................................................................................................................................ Section 73.1: Everything in between MongoDB and Php 360 ....................................................................................... Chapter 74: Asynchronous programming 363 ................................................................................................... Section 74.1: Advantages of Generators 363 ................................................................................................................. Section 74.2: Using Icicle event loop 363 ....................................................................................................................... Section 74.3: Spawning non-blocking processes with proc_open() 364 .................................................................... Section 74.4: Reading serial port with Event and DIO 365 ........................................................................................... Section 74.5: HTTP Client Based on Event Extension 367 ............................................................................................ Section 74.6: HTTP Client Based on Ev Extension 370 .................................................................................................. Section 74.7: Using Amp event loop 374 ........................................................................................................................ Chapter 75: Unicode Support in PHP 376 .............................................................................................................. Section 75.1: Converting Unicode characters to “\uxxxx” format using PHP 376 ...................................................... Section 75.2: Converting Unicode characters to their numeric value and/or HTML entities using PHP 376 ............................................................................................................................................................................. Section 75.3: Intl extention for Unicode support 378 .................................................................................................... Chapter 76: How to break down an URL 379 ...................................................................................................... Section 76.1: Using parse_url() 379 ................................................................................................................................ Section 76.2: Using explode() 380 ................................................................................................................................... Section 76.3: Using basename() 380 .............................................................................................................................. Chapter 77: Create PDF files in PHP 382 ............................................................................................................... Section 77.1: Getting Started with PDFlib 382 ................................................................................................................ Chapter 78: How to Detect Client IP Address 383 ............................................................................................ Section 78.1: Proper use of HTTP_X_FORWARDED_FOR 383 .................................................................................... Chapter 79: YAML in PHP 385 ...................................................................................................................................... Section 79.1: Installing YAML extension 385 ................................................................................................................... Section 79.2: Using YAML to store application configuration 385 ............................................................................... Chapter 80: Image Processing with GD 387 ......................................................................................................... Section 80.1: Image output 387 ....................................................................................................................................... Section 80.2: Creating an image 388 ............................................................................................................................. Section 80.3: Image Cropping and Resizing 389 ........................................................................................................... Chapter 81: Imagick 392 ................................................................................................................................................. Section 81.1: First Steps 392 ............................................................................................................................................. Section 81.2: Convert Image into base64 String 392 .................................................................................................... Chapter 82: Multiprocessing 394 ............................................................................................................................... Section 82.1: Multiprocessing using built-in fork functions 394 ................................................................................... Section 82.2: Creating child process using fork 394 ..................................................................................................... Section 82.3: Inter-Process Communication 395 .......................................................................................................... Chapter 83: SOAP Server 396 ...................................................................................................................................... Section 83.1: Basic SOAP Server 396 .............................................................................................................................. Chapter 84: Machine learning 397 ........................................................................................................................... Section 84.1: Classification using PHP-ML 397 ...............................................................................................................
Section 84.2: Regression 398 .......................................................................................................................................... Section 84.3: Clustering 400 ............................................................................................................................................ Chapter 85: Cache 402 .................................................................................................................................................... Section 85.1: Caching using memcache 402 .................................................................................................................. Section 85.2: Cache Using APC Cache 403 .................................................................................................................... Chapter 86: Streams 405 ............................................................................................................................................... Section 86.1: Registering a stream wrapper 405 ........................................................................................................... Chapter 87: SPL data structures 407 ...................................................................................................................... Section 87.1: SplFixedArray 407 ....................................................................................................................................... Chapter 88: IMAP 411 ...................................................................................................................................................... Section 88.1: Connecting to a mailbox 411 .................................................................................................................... Section 88.2: Install IMAP extension 412 ........................................................................................................................ Section 88.3: List all folders in the mailbox 412 ............................................................................................................. Section 88.4: Finding messages in the mailbox 413 ..................................................................................................... Chapter 89: Using Redis with PHP 415 .................................................................................................................... Section 89.1: Connecting to a Redis instance 415 ......................................................................................................... Section 89.2: Installing PHP Redis on Ubuntu 415 ........................................................................................................ Section 89.3: Executing Redis commands in PHP 415 .................................................................................................. Chapter 90: HTTP Authentication 416 .................................................................................................................... Section 90.1: Simple authenticate 416 ............................................................................................................................ Chapter 91: BC Math (Binary Calculator) 417 ...................................................................................................... Section 91.1: Using bcmath to read/write a binary long on 32-bit system 417 ......................................................... Section 91.2: Comparison between BCMath and float arithmetic operations 418 .................................................... Chapter 92: Docker deployment 420 ...................................................................................................................... Section 92.1: Get docker image for php 420 .................................................................................................................. Section 92.2: Writing dockerfile 420 ............................................................................................................................... Section 92.3: Building image 420 .................................................................................................................................... Section 92.4: Starting application container 421 .......................................................................................................... Chapter 93: WebSockets 422 ....................................................................................................................................... Section 93.1: Simple TCP/IP server 422 .......................................................................................................................... Chapter 94: APCu 424 ..................................................................................................................................................... Section 94.1: Iterating over Entries 424 .......................................................................................................................... Section 94.2: Simple storage and retrieval 424 ............................................................................................................. Section 94.3: Store information 424 ............................................................................................................................... Chapter 95: Design Patterns 425 ............................................................................................................................... Section 95.1: Method Chaining in PHP 425 ..................................................................................................................... Chapter 96: PHP Built in server 427 ......................................................................................................................... Section 96.1: Running the built in server 427 ................................................................................................................. Section 96.2: built in server with specific directory and router script 427 .................................................................. Chapter 97: PSR 428 ......................................................................................................................................................... Section 97.1: PSR-4: Autoloader 428 ............................................................................................................................... Section 97.2: PSR-1: Basic Coding Standard 429 ........................................................................................................... Chapter 98: Compile PHP Extensions 430 .............................................................................................................. Section 98.1: Compiling on Linux 430 .............................................................................................................................. Chapter 99: Common Errors 431 ............................................................................................................................... Section 99.1: Call fetch_assoc on boolean 431 ............................................................................................................. Section 99.2: Unexpected $end 431 ............................................................................................................................... Chapter 100: Performance 433 ...................................................................................................................................
Section 100.1: Profiling with Xdebug 433 ........................................................................................................................ Section 100.2: Memory Usage 434 ................................................................................................................................. Section 100.3: Profiling with XHProf 435 ......................................................................................................................... Chapter 101: Secure Remeber Me 437 ..................................................................................................................... Section 101.1: “Keep Me Logged In” - the best approach 437 ...................................................................................... Chapter 102: Security 438 .............................................................................................................................................. Section 102.1: PHP Version Leakage 438 ........................................................................................................................ Section 102.2: Cross-Site Scripting (XSS) 438 ................................................................................................................ Section 102.3: Cross-Site Request Forgery 440 ............................................................................................................. Section 102.4: Command Line Injection 441 .................................................................................................................. Section 102.5: Stripping Tags 442 ................................................................................................................................... Section 102.6: File Inclusion 443 ...................................................................................................................................... Section 102.7: Error Reporting 443 ................................................................................................................................. Section 102.8: Uploading files 444 .................................................................................................................................. Chapter 103: Cryptography 447 ................................................................................................................................. Section 103.1: Symmetric Encryption and Decryption of large Files with OpenSSL 447 ........................................... Section 103.2: Symmetric Cipher 449 ............................................................................................................................. Chapter 104: Password Hashing Functions 450 ................................................................................................. Section 104.1: Creating a password hash 450 ................................................................................................................ Section 104.2: Determine if an existing password hash can be upgraded to a stronger algorithm 451 ................ Section 104.3: Verifying a password against a hash 452 ............................................................................................. Chapter 105: Contributing to the PHP Manual 453 ........................................................................................... Section 105.1: Improve the ocial documentation 453 ................................................................................................ Section 105.2: Tips for contributing to the manual 453 ................................................................................................ Appendix A: Installing a PHP environment on Windows 454 ....................................................................... Section A.1: Download, Install and use WAMP 454 ........................................................................................................ Section A.2: Install PHP and use it with IIS 454 .............................................................................................................. Section A.3: Download and Install XAMPP 455 .............................................................................................................. Appendix B: Installing on Linux/Unix Environments 458 ............................................................................... Section B.1: Command Line Install Using APT for PHP 7 458 ....................................................................................... Section B.2: Installing in Enterprise Linux distributions (CentOS, Scientific Linux, etc) 458 ....................................... Credits 460 ............................................................................................................................................................................ You may also like 468 ......................................................................................................................................................
GoalKicker.com – PHP Notes for Professionals 1 About Please feel free to share this PDF with anyone for free, latest version of this book can be downloaded from: https://goalkicker.com/PHPBook This PHP Notes for Professionals book is compiled from Stack Overflow Documentation, the content is written by the beautiful people at Stack Overflow. Text content is released under Creative Commons BY-SA, see credits at the end of this book whom contributed to the various chapters. Images may be copyright of their respective owners unless otherwise specified This is an unofficial free book created for educational purposes and is not affiliated with official PHP group(s) or company(s) nor Stack Overflow. All trademarks and registered trademarks are the property of their respective company owners The information presented in this book is not guaranteed to be correct nor accurate, use at your own risk Please send feedback and corrections to web@petercv.com
GoalKicker.com – PHP Notes for Professionals 2 Chapter 1: Getting started with PHP PHP 7.x Version Supported Until Release Date 7.1 2019-12-01 2016-12-01 7.0 2018-12-03 2015-12-03 PHP 5.x Version Supported Until Release Date 5.6 2018-12-31 2014-08-28 5.5 2016-07-21 2013-06-20 5.4 2015-09-03 2012-03-01 5.3 2014-08-14 2009-06-30 5.2 2011-01-06 2006-11-02 5.1 2006-08-24 2005-11-24 5.0 2005-09-05 2004-07-13 PHP 4.x Version Supported Until Release Date 4.4 2008-08-07 2005-07-11 4.3 2005-03-31 2002-12-27 4.2 2002-09-06 2002-04-22 4.1 2002-03-12 2001-12-10 4.0 2001-06-23 2000-05-22 Legacy Versions Version Supported Until Release Date 3.0 2000-10-20 1998-06-06 2.0 1997-11-01 1.0 1995-06-08 Section 1.1: HTML output from web server PHP can be used to add content to HTML files. While HTML is processed directly by a web browser, PHP scripts are executed by a web server and the resulting HTML is sent to the browser. The following HTML markup contains a PHP statement that will add Hello World! to the output: <!DOCTYPE html> <html> <head> <title>PHP!</title> </head> <body> <p><?php echo "Hello world!"; ?></p> </body> </html> When this is saved as a PHP script and executed by a web server, the following HTML will be sent to the user's browser: <!DOCTYPE html> <html> <head>
GoalKicker.com – PHP Notes for Professionals 3 <title>PHP!</title> </head> <body> <p>Hello world!</p> </body> </html> PHP 5.x Version ≥ 5.4 echo also has a shortcut syntax, which lets you immediately print a value. Prior to PHP 5.4.0, this short syntax only works with the short_open_tag configuration setting enabled. For example, consider the following code: <p><?= "Hello world!" ?></p> Its output is identical to the output of the following: <p><?php echo "Hello world!"; ?></p> In real-world applications, all data output by PHP to an HTML page should be properly escaped to prevent XSS (Cross-site scripting) attacks or text corruption. See also: Strings and PSR-1, which describes best practices, including the proper use of short tags (<?= ... ?>). Section 1.2: Hello, World! The most widely used language construct to print output in PHP is echo: echo "Hello, World!\n"; Alternatively, you can also use print: print "Hello, World!\n"; Both statements perform the same function, with minor differences: echo has a void return, whereas print returns an int with a value of 1 echo can take multiple arguments (without parentheses only), whereas print only takes one argument echo is slightly faster than print Both echo and print are language constructs, not functions. That means they do not require parentheses around their arguments. For cosmetic consistency with functions, parentheses can be included. Extensive examples of the use of echo and print are available elsewhere. C-style printf and related functions are available as well, as in the following example: printf("%s\n", "Hello, World!"); See Outputting the value of a variable for a comprehensive introduction of outputting variables in PHP. Section 1.3: Non-HTML output from web server In some cases, when working with a web server, overriding the web server's default content type may be required. There may be cases where you need to send data as plain text, JSON, or XML, for example.
GoalKicker.com – PHP Notes for Professionals 4 The header() function can send a raw HTTP header. You can add the Content-Type header to notify the browser of the content we are sending. Consider the following code, where we set Content-Type as text/plain: header("Content-Type: text/plain"); echo "Hello World"; This will produce a plain text document with the following content: Hello World To produce JSON content, use the application/json content type instead: header("Content-Type: application/json"); // Create a PHP data array. $data = ["response" => "Hello World"]; // json_encode will convert it to a valid JSON string. echo json_encode($data); This will produce a document of type application/json with the following content: {"response":"Hello World"} Note that the header() function must be called before PHP produces any output, or the web server will have already sent headers for the response. So, consider the following code: // Error: We cannot send any output before the headers echo "Hello"; // All headers must be sent before ANY PHP output header("Content-Type: text/plain"); echo "World"; This will produce a warning: Warning: Cannot modify header information - headers already sent by (output started at /dir/example.php:2) in /dir/example.php on line 3 When using header(), its output needs to be the first byte that's sent from the server. For this reason it's important to not have empty lines or spaces in the beginning of the file before the PHP opening tag <?php. For the same reason, it is considered best practice (see PSR-2) to omit the PHP closing tag ?> from files that contain only PHP and from blocks of PHP code at the very end of a file. View the output buffering section to learn how to 'catch' your content into a variable to output later, for example, after outputting headers.
GoalKicker.com – PHP Notes for Professionals 5 Section 1.4: PHP built-in server PHP 5.4+ comes with a built-in development server. It can be used to run applications without having to install a production HTTP server such as nginx or Apache. The built-in server is only designed to be used for development and testing purposes. It can be started by using the -S flag: php -S <host/ip>:<port> Example usage Create an index.php file containing:1. <?php echo "Hello World from built-in PHP server"; Run the command php -S localhost:8080 from the command line. Do not include2. http:// . This will start a web server listening on port 8080 using the current directory that you are in as the document root. Open the browser and navigate to http://localhost:8080. You should see your "Hello World" page.3. Configuration To override the default document root (i.e. the current directory), use the -t flag: php -S <host/ip>:<port> -t <directory> E.g. if you have a public/ directory in your project you can serve your project from that directory using php -S localhost:8080 -t public/. Logs Every time a request is made from the development server, a log entry like the one below is written to the command line. [Mon Aug 15 18:20:19 2016] ::1:52455 [200]: / Section 1.5: PHP CLI PHP can also be run from command line directly using the CLI (Command Line Interface). CLI is basically the same as PHP from web servers, except some differences in terms of standard input and output. Triggering The PHP CLI allows four ways to run PHP code: Standard input. Run the php command without any arguments, but pipe PHP code into it: echo '<?php echo1. "Hello world!";' | php Filename as argument. Run the php command with the name of a PHP source file as the first argument: php2. hello_world.php
GoalKicker.com – PHP Notes for Professionals 6 Code as argument. Use the -r option in the php command, followed by the code to run. The <?php open tags3. are not required, as everything in the argument is considered as PHP code: php -r 'echo "Hello world!";' Interactive shell. Use the -a option in the php command to launch an interactive shell. Then, type (or paste)4. PHP code and hit return : $ php -a Interactive mode enabled php > echo "Hello world!"; Hello world! Output All functions or controls that produce HTML output in web server PHP can be used to produce output in the stdout stream (file descriptor 1), and all actions that produce output in error logs in web server PHP will produce output in the stderr stream (file descriptor 2). Example.php <?php echo "Stdout 1\n"; trigger_error("Stderr 2\n"); print_r("Stdout 3\n"); fwrite(STDERR, "Stderr 4\n"); throw new RuntimeException("Stderr 5\n"); ?> Stdout 6 Shell command line $ php Example.php 2>stderr.log >stdout.log;\ > echo STDOUT; cat stdout.log; echo;\ > echo STDERR; cat stderr.log\ STDOUT Stdout 1 Stdout 3 STDERR Stderr 4 PHP Notice: Stderr 2 in /Example.php on line 3 PHP Fatal error: Uncaught RuntimeException: Stderr 5 in /Example.php:6 Stack trace: #0 {main} thrown in /Example.php on line 6 Input See: Command Line Interface (CLI) Section 1.6: Instruction Separation Just like most other C-style languages, each statement is terminated with a semicolon. Also, a closing tag is used to terminate the last line of code of the PHP block. If the last line of PHP code ends with a semicolon, the closing tag is optional if there is no code following that final line of code. For example, we can leave out the closing tag after echo "No error"; in the following example: <?php echo "No error"; // no closing tag is needed as long as there is no code below However, if there is any other code following your PHP code block, the closing tag is no longer optional: <?php echo "This will cause an error if you leave out the closing tag"; ?> <html> <body>
GoalKicker.com – PHP Notes for Professionals 7 </body> </html> We can also leave out the semicolon of the last statement in a PHP code block if that code block has a closing tag: <?php echo "I hope this helps! :D"; echo "No error" ?> It is generally recommended to always use a semicolon and use a closing tag for every PHP code block except the last PHP code block, if no more code follows that PHP code block. So, your code should basically look like this: <?php echo "Here we use a semicolon!"; echo "Here as well!"; echo "Here as well!"; echo "Here we use a semicolon and a closing tag because more code follows"; ?> <p>Some HTML code goes here</p> <?php echo "Here we use a semicolon!"; echo "Here as well!"; echo "Here as well!"; echo "Here we use a semicolon and a closing tag because more code follows"; ?> <p>Some HTML code goes here</p> <?php echo "Here we use a semicolon!"; echo "Here as well!"; echo "Here as well!"; echo "Here we use a semicolon but leave out the closing tag"; Section 1.7: PHP Tags There are three kinds of tags to denote PHP blocks in a file. The PHP parser is looking for the opening and (if present) closing tags to delimit the code to interpret. Standard Tags These tags are the standard method to embed PHP code in a file. <?php echo "Hello World"; ?> PHP 5.x Version ≥ 5.4 Echo Tags These tags are available in all PHP versions, and since PHP 5.4 are always enabled. In previous versions, echo tags could only be enabled in conjunction with short tags. <?= "Hello World" ?> Short Tags You can disable or enable these tags with the option short_open_tag.
The above is a preview of the first 20 pages. Register to read the complete e-book.