Author:PHP Notes For Professionals
No description
Tags
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.
Page
1
PHP Notes for ProfessionalsPHP Notes for Professionals GoalKicker.com Free Programming Books Disclaimer This is an unocial free book created for educational purposes and is not aliated with ocial 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
Page
2
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: Superglobal Variables PHP 21 ........................................................................................................... Section 4.1: Suberglobals explained 21 .......................................................................................................................... Section 4.2: PHP5 SuperGlobals 28 ................................................................................................................................. Chapter 5: Outputting the Value of a Variable 32 .......................................................................................... Section 5.1: echo and print 32 .......................................................................................................................................... Section 5.2: Outputting a structured view of arrays and objects 33 .......................................................................... Section 5.3: String concatenation with echo 35 ............................................................................................................. Section 5.4: printf vs sprintf 36 ........................................................................................................................................ Section 5.5: Outputting large integers 36 ...................................................................................................................... Section 5.6: Output a Multidimensional Array with index and value and print into the table 37 ............................. Chapter 6: Constants 39 ................................................................................................................................................ Section 6.1: Defining constants 39 ................................................................................................................................... Section 6.2: Class Constants 40 ...................................................................................................................................... Section 6.3: Checking if constant is defined 40 ............................................................................................................. Section 6.4: Using constants 42 ...................................................................................................................................... Section 6.5: Constant arrays 42 ...................................................................................................................................... Chapter 7: Magic Constants 43 .................................................................................................................................. Section 7.1: Dierence between __FUNCTION__ and __METHOD__ 43 ................................................................. Section 7.2: Dierence between __CLASS__, get_class() and get_called_class() 43 ........................................... Section 7.3: File & Directory Constants 44 ..................................................................................................................... Chapter 8: Comments 45 .............................................................................................................................................. Section 8.1: Single Line Comments 45 ............................................................................................................................ Section 8.2: Multi Line Comments 45 .............................................................................................................................. Chapter 9: Types 46 ......................................................................................................................................................... Section 9.1: Type Comparison 46 .................................................................................................................................... Section 9.2: Boolean 46 .................................................................................................................................................... Section 9.3: Float 47 .........................................................................................................................................................
Page
3
Section 9.4: Strings 48 ...................................................................................................................................................... Section 9.5: Callable 50 .................................................................................................................................................... Section 9.6: Resources 50 ................................................................................................................................................ Section 9.7: Type Casting 51 ........................................................................................................................................... Section 9.8: Type Juggling 51 ......................................................................................................................................... Section 9.9: Null 52 ........................................................................................................................................................... Section 9.10: Integers 52 .................................................................................................................................................. Chapter 10: Operators 54 .............................................................................................................................................. Section 10.1: Null Coalescing Operator (??) 54 .............................................................................................................. Section 10.2: Spaceship Operator (<=>) 55 .................................................................................................................... Section 10.3: Execution Operator (``) 55 .......................................................................................................................... Section 10.4: Incrementing (++) and Decrementing Operators (--) 55 ....................................................................... Section 10.5: Ternary Operator (?:) 56 ........................................................................................................................... Section 10.6: Logical Operators (&&/AND and ||/OR) 57 ............................................................................................. Section 10.7: String Operators (. and .=) 57 .................................................................................................................... Section 10.8: Object and Class Operators 57 ................................................................................................................. Section 10.9: Combined Assignment (+= etc) 59 ........................................................................................................... Section 10.10: Altering operator precedence (with parentheses) 59 ........................................................................... Section 10.11: Basic Assignment (=) 60 ............................................................................................................................ Section 10.12: Association 60 ............................................................................................................................................ Section 10.13: Comparison Operators 60 ........................................................................................................................ Section 10.14: Bitwise Operators 62 ................................................................................................................................. Section 10.15: instanceof (type operator) 64 ................................................................................................................. Chapter 11: References 67 ............................................................................................................................................ Section 11.1: Assign by Reference 67 ............................................................................................................................... Section 11.2: Return by Reference 67 .............................................................................................................................. Section 11.3: Pass by Reference 68 ................................................................................................................................. Chapter 12: Arrays 71 ...................................................................................................................................................... Section 12.1: Initializing an Array 71 ................................................................................................................................ Section 12.2: Check if key exists 73 ................................................................................................................................. Section 12.3: Validating the array type 74 ..................................................................................................................... Section 12.4: Creating an array of variables 74 ............................................................................................................ Section 12.5: Checking if a value exists in array 74 ....................................................................................................... Section 12.6: ArrayAccess and Iterator Interfaces 75 ................................................................................................... Chapter 13: Array iteration 79 .................................................................................................................................... Section 13.1: Iterating multiple arrays together 79 ........................................................................................................ Section 13.2: Using an incremental index 80 .................................................................................................................. Section 13.3: Using internal array pointers 80 ............................................................................................................... Section 13.4: Using foreach 81 ......................................................................................................................................... Section 13.5: Using ArrayObject Iterator 83 ................................................................................................................... Chapter 14: Executing Upon an Array 84 .............................................................................................................. Section 14.1: Applying a function to each element of an array 84 .............................................................................. Section 14.2: Split array into chunks 85 .......................................................................................................................... Section 14.3: Imploding an array into string 86 ............................................................................................................. Section 14.4: "Destructuring" arrays using list() 86 ....................................................................................................... Section 14.5: array_reduce 86 ......................................................................................................................................... Section 14.6: Push a Value on an Array 87 ..................................................................................................................... Chapter 15: Manipulating an Array 89 .................................................................................................................... Section 15.1: Filtering an array 89 .................................................................................................................................... Section 15.2: Removing elements from an array 90 .....................................................................................................
Page
4
Section 15.3: Sorting an Array 91 .................................................................................................................................... Section 15.4: Whitelist only some array keys 96 ........................................................................................................... Section 15.5: Adding element to start of array 96 ......................................................................................................... Section 15.6: Exchange values with keys 97 ................................................................................................................... Section 15.7: Merge two arrays into one array 97 ........................................................................................................ Chapter 16: Processing Multiple Arrays Together 99 ..................................................................................... Section 16.1: Array intersection 99 ................................................................................................................................... Section 16.2: Merge or concatenate arrays 99 .............................................................................................................. Section 16.3: Changing a multidimensional array to associative array 100 .............................................................. Section 16.4: Combining two arrays (keys from one, values from another) 100 ...................................................... Chapter 17: Datetime Class 102 ................................................................................................................................. Section 17.1: Create Immutable version of DateTime from Mutable prior PHP 5.6 102 ............................................ Section 17.2: Add or Subtract Date Intervals 102 .......................................................................................................... Section 17.3: getTimestamp 102 ..................................................................................................................................... Section 17.4: setDate 103 ................................................................................................................................................. Section 17.5: Create DateTime from custom format 103 ............................................................................................. Section 17.6: Printing DateTimes 103 .............................................................................................................................. Chapter 18: Working with Dates and Time 105 .................................................................................................. Section 18.1: Getting the dierence between two dates / times 105 .......................................................................... Section 18.2: Convert a date into another format 105 ................................................................................................. Section 18.3: Parse English date descriptions into a Date format 107 ........................................................................ Section 18.4: Using Predefined Constants for Date Format 107 ................................................................................. Chapter 19: Control Structures 109 .......................................................................................................................... Section 19.1: if else 109 ..................................................................................................................................................... Section 19.2: Alternative syntax for control structures 109 .......................................................................................... Section 19.3: while 109 ...................................................................................................................................................... Section 19.4: do-while 110 ................................................................................................................................................ Section 19.5: goto 110 ...................................................................................................................................................... Section 19.6: declare 110 .................................................................................................................................................. Section 19.7: include & require 111 ................................................................................................................................. Section 19.8: return 112 .................................................................................................................................................... Section 19.9: for 112 ......................................................................................................................................................... Section 19.10: foreach 113 ................................................................................................................................................ Section 19.11: if elseif else 113 .......................................................................................................................................... Section 19.12: if 114 ........................................................................................................................................................... Section 19.13: switch 114 ................................................................................................................................................... Chapter 20: Loops 116 .................................................................................................................................................... Section 20.1: continue 116 ............................................................................................................................................... Section 20.2: break 117 ................................................................................................................................................... Section 20.3: foreach 118 ................................................................................................................................................ Section 20.4: do...while 118 .............................................................................................................................................. Section 20.5: for 119 ........................................................................................................................................................ Section 20.6: while 120 ..................................................................................................................................................... Chapter 21: Functions 121 ............................................................................................................................................. Section 21.1: Variable-length argument lists 121 ........................................................................................................... Section 21.2: Optional Parameters 122 .......................................................................................................................... Section 21.3: Passing Arguments by Reference 123 ..................................................................................................... Section 21.4: Basic Function Usage 124 ......................................................................................................................... Section 21.5: Function Scope 124 ....................................................................................................................................
Page
5
Chapter 22: Functional Programming 125 ............................................................................................................ Section 22.1: Closures 125 ................................................................................................................................................ Section 22.2: Assignment to variables 126 .................................................................................................................... Section 22.3: Objects as a function 126 ......................................................................................................................... Section 22.4: Using outside variables 127 ..................................................................................................................... Section 22.5: Anonymous function 127 .......................................................................................................................... Section 22.6: Pure functions 128 ..................................................................................................................................... Section 22.7: Common functional methods in PHP 128 ............................................................................................... Section 22.8: Using built-in functions as callbacks 129 ................................................................................................ Section 22.9: Scope 129 ................................................................................................................................................... Section 22.10: Passing a callback function as a parameter 129 ................................................................................. Chapter 23: Alternative Syntax for Control Structures 131 ........................................................................ Section 23.1: Alternative if/else statement 131 ............................................................................................................. Section 23.2: Alternative for statement 131 .................................................................................................................. Section 23.3: Alternative while statement 131 ............................................................................................................... Section 23.4: Alternative foreach statement 131 .......................................................................................................... Section 23.5: Alternative switch statement 132 ............................................................................................................. Chapter 24: String formatting 133 .......................................................................................................................... Section 24.1: String interpolation 133 ............................................................................................................................. Section 24.2: Extracting/replacing substrings 134 ....................................................................................................... Chapter 25: String Parsing 136 ................................................................................................................................... Section 25.1: Splitting a string by separators 136 ......................................................................................................... Section 25.2: Substring 136 ............................................................................................................................................. Section 25.3: Searching a substring with strpos 138 .................................................................................................... Section 25.4: Parsing string using regular expressions 139 ......................................................................................... Chapter 26: Classes and Objects 140 ...................................................................................................................... Section 26.1: Class Constants 140 ................................................................................................................................... Section 26.2: Abstract Classes 142 ................................................................................................................................. Section 26.3: Late static binding 144 .............................................................................................................................. Section 26.4: Namespacing and Autoloading 145 ........................................................................................................ Section 26.5: Method and Property Visibility 147 .......................................................................................................... Section 26.6: Interfaces 149 ............................................................................................................................................ Section 26.7: Final Keyword 152 ..................................................................................................................................... Section 26.8: Autoloading 153 ......................................................................................................................................... Section 26.9: Calling a parent constructor when instantiating a child 154 ................................................................ Section 26.10: Dynamic Binding 155 ............................................................................................................................... Section 26.11: $this, self and static plus the singleton 156 ............................................................................................ Section 26.12: Defining a Basic Class 159 ...................................................................................................................... Section 26.13: Anonymous Classes 160 .......................................................................................................................... Chapter 27: Namespaces 162 ..................................................................................................................................... Section 27.1: Declaring namespaces 162 ....................................................................................................................... Section 27.2: Referencing a class or function in a namespace 162 ........................................................................... Section 27.3: Declaring sub-namespaces 163 ............................................................................................................... Section 27.4: What are Namespaces? 164 .................................................................................................................... Chapter 28: Sessions 165 ............................................................................................................................................... Section 28.1: session_start() Options 165 ...................................................................................................................... Section 28.2: Session Locking 165 .................................................................................................................................. Section 28.3: Manipulating session data 166 ................................................................................................................. Section 28.4: Destroy an entire session 166 ..................................................................................................................
Page
6
Section 28.5: Safe Session Start With no Errors 167 ..................................................................................................... Section 28.6: Session name 167 ...................................................................................................................................... Chapter 29: Cookies 169 ................................................................................................................................................. Section 29.1: Modifying a Cookie 169 ............................................................................................................................. Section 29.2: Setting a Cookie 169 ................................................................................................................................. Section 29.3: Checking if a Cookie is Set 170 ................................................................................................................ Section 29.4: Removing a Cookie 170 ............................................................................................................................ Section 29.5: Retrieving a Cookie 170 ............................................................................................................................ Chapter 30: Output Buering 171 ............................................................................................................................ Section 30.1: Basic usage getting content between buers and clearing 171 .......................................................... Section 30.2: Processing the buer via a callback 171 ................................................................................................ Section 30.3: Nested output buers 172 ........................................................................................................................ Section 30.4: Running output buer before any content 173 ..................................................................................... Section 30.5: Stream output to client 174 ...................................................................................................................... Section 30.6: Using Output buer to store contents in a file, useful for reports, invoices etc 174 .......................... Section 30.7: Typical usage and reasons for using ob_start 174 ............................................................................... Section 30.8: Capturing the output buer to re-use later 175 .................................................................................... Chapter 31: JSON 177 ...................................................................................................................................................... Section 31.1: Decoding a JSON string 177 ...................................................................................................................... Section 31.2: Encoding a JSON string 180 ...................................................................................................................... Section 31.3: Debugging JSON errors 183 ..................................................................................................................... Section 31.4: Using JsonSerializable in an Object 184 .................................................................................................. Section 31.5: Header json and the returned response 185 ........................................................................................... Chapter 32: SOAP Client 187 ........................................................................................................................................ Section 32.1: WSDL Mode 187 ......................................................................................................................................... Section 32.2: Non-WSDL Mode 187 ................................................................................................................................ Section 32.3: Classmaps 187 ........................................................................................................................................... Section 32.4: Tracing SOAP request and response 188 ............................................................................................... Chapter 33: Using cURL in PHP 190 .......................................................................................................................... Section 33.1: Basic Usage (GET Requests) 190 .............................................................................................................. Section 33.2: POST Requests 190 ................................................................................................................................... Section 33.3: Using Cookies 191 ...................................................................................................................................... Section 33.4: Using multi_curl to make multiple POST requests 192 ......................................................................... Section 33.5: Sending multi-dimensional data and multiple files with CurlFile in one request 193 ......................... Section 33.6: Creating and sending a request with a custom method 196 ................................................................ Section 33.7: Get and Set custom http headers in php 196 ......................................................................................... Chapter 34: Reflection 198 ........................................................................................................................................... Section 34.1: Feature detection of classes or objects 198 ............................................................................................ Section 34.2: Testing private/protected methods 198 ................................................................................................. Section 34.3: Accessing private and protected member variables 200 ..................................................................... Chapter 35: Dependency Injection 202 .................................................................................................................. Section 35.1: Constructor Injection 202 ........................................................................................................................... Section 35.2: Setter Injection 202 .................................................................................................................................... Section 35.3: Container Injection 204 ............................................................................................................................. Chapter 36: XML 205 ........................................................................................................................................................ Section 36.1: Create a XML using DomDocument 205 .................................................................................................. Section 36.2: Read a XML document with DOMDocument 206 ................................................................................... Section 36.3: Leveraging XML with PHP's SimpleXML Library 207 .............................................................................. Section 36.4: Create an XML file using XMLWriter 209 .................................................................................................
Page
7
Section 36.5: Read a XML document with SimpleXML 210 .......................................................................................... Chapter 37: SimpleXML 212 .......................................................................................................................................... Section 37.1: Loading XML data into simplexml 212 ..................................................................................................... Chapter 38: Parsing HTML 213 ................................................................................................................................... Section 38.1: Parsing HTML from a string 213 ............................................................................................................... Section 38.2: Using XPath 213 ......................................................................................................................................... Section 38.3: SimpleXML 213 ........................................................................................................................................... Chapter 39: Regular Expressions (regexp/PCRE) 215 .................................................................................... Section 39.1: Global RegExp match 215 ......................................................................................................................... Section 39.2: String matching with regular expressions 216 ....................................................................................... Section 39.3: Split string into array by a regular expression 217 ................................................................................ Section 39.4: String replacing with regular expression 217 ......................................................................................... Section 39.5: String replace with callback 217 .............................................................................................................. Chapter 40: Traits 219 .................................................................................................................................................... Section 40.1: What is a Trait? 219 ................................................................................................................................... Section 40.2: Traits to facilitate horizontal code reuse 220 ......................................................................................... Section 40.3: Conflict Resolution 221 ............................................................................................................................. Section 40.4: Implementing a Singleton using Traits 222 ............................................................................................ Section 40.5: Traits to keep classes clean 223 .............................................................................................................. Section 40.6: Multiple Traits Usage 224 ......................................................................................................................... Section 40.7: Changing Method Visibility 224 ................................................................................................................ Chapter 41: Composer Dependency Manager 226 .......................................................................................... Section 41.1: What is Composer? 226 .............................................................................................................................. Section 41.2: Autoloading with Composer 227 .............................................................................................................. Section 41.3: Dierence between 'composer install' and 'composer update' 227 ..................................................... Section 41.4: Composer Available Commands 228 ....................................................................................................... Section 41.5: Benefits of Using Composer 229 .............................................................................................................. Section 41.6: Installation 230 ............................................................................................................................................ Chapter 42: Magic Methods 231 ................................................................................................................................ Section 42.1: __call() and __callStatic() 231 ................................................................................................................. Section 42.2: __get(), __set(), __isset() and __unset() 232 ...................................................................................... Section 42.3: __construct() and __destruct() 233 ....................................................................................................... Section 42.4: __toString() 234 ........................................................................................................................................ Section 42.5: __clone() 235 ............................................................................................................................................ Section 42.6: __invoke() 235 ........................................................................................................................................... Section 42.7: __sleep() and __wakeup() 236 ............................................................................................................... Section 42.8: __debugInfo() 236 .................................................................................................................................... Chapter 43: File handling 238 ..................................................................................................................................... Section 43.1: Convenience functions 238 ........................................................................................................................ Section 43.2: Deleting files and directories 240 ............................................................................................................. Section 43.3: Getting file information 240 ...................................................................................................................... Section 43.4: Stream-based file IO 242 .......................................................................................................................... Section 43.5: Moving and Copying files and directories 244 ....................................................................................... Section 43.6: Minimize memory usage when dealing with large files 245 ................................................................. Chapter 44: Streams 246 .............................................................................................................................................. Section 44.1: Registering a stream wrapper 246 ........................................................................................................... Chapter 45: Type hinting 248 ..................................................................................................................................... Section 45.1: Type hinting classes and interfaces 248 .................................................................................................. Section 45.2: Type hinting scalar types, arrays and callables 249 .............................................................................
Page
8
Section 45.3: Nullable type hints 250 .............................................................................................................................. Section 45.4: Type hinting generic objects 251 ............................................................................................................. Section 45.5: Type Hinting No Return(Void) 252 .......................................................................................................... Chapter 46: Filters & Filter Functions 253 ............................................................................................................ Section 46.1: Validating Boolean Values 253 ................................................................................................................. Section 46.2: Validating A Number Is A Float 253 ......................................................................................................... Section 46.3: Validate A MAC Address 254 .................................................................................................................... Section 46.4: Sanitze Email Addresses 254 .................................................................................................................... Section 46.5: Sanitize Integers 255 ................................................................................................................................. Section 46.6: Sanitize URLs 255 ...................................................................................................................................... Section 46.7: Validate Email Address 256 ...................................................................................................................... Section 46.8: Validating A Value Is An Integer 256 ....................................................................................................... Section 46.9: Validating An Integer Falls In A Range 257 ............................................................................................ Section 46.10: Validate a URL 257 .................................................................................................................................. Section 46.11: Sanitize Floats 259 .................................................................................................................................... Section 46.12: Validate IP Addresses 261 ....................................................................................................................... Section 46.13: Sanitize filters 262 ..................................................................................................................................... Chapter 47: Generators 263 ........................................................................................................................................ Section 47.1: The Yield Keyword 263 .............................................................................................................................. Section 47.2: Reading a large file with a generator 264 .............................................................................................. Section 47.3: Why use a generator? 264 ........................................................................................................................ Section 47.4: Using the send()-function to pass values to a generator 265 .............................................................. Chapter 48: UTF-8 267 ................................................................................................................................................... Section 48.1: Input 267 ...................................................................................................................................................... Section 48.2: Output 267 .................................................................................................................................................. Section 48.3: Data Storage and Access 267 .................................................................................................................. Chapter 49: Unicode Support in PHP 269 ............................................................................................................. Section 49.1: Converting Unicode characters to “\uxxxx” format using PHP 269 ...................................................... Section 49.2: Converting Unicode characters to their numeric value and/or HTML entities using PHP 269 ............................................................................................................................................................................. Section 49.3: Intl extention for Unicode support 271 .................................................................................................... Chapter 50: URLs 272 ...................................................................................................................................................... Section 50.1: Parsing a URL 272 ...................................................................................................................................... Section 50.2: Build an URL-encoded query string from an array 272 ....................................................................... Section 50.3: Redirecting to another URL 273 ............................................................................................................... Chapter 51: How to break down an URL 275 ....................................................................................................... Section 51.1: Using parse_url() 275 ................................................................................................................................. Section 51.2: Using explode() 276 ................................................................................................................................... Section 51.3: Using basename() 276 ............................................................................................................................... Chapter 52: Object Serialization 278 ....................................................................................................................... Section 52.1: Serialize / Unserialize 278 ......................................................................................................................... Section 52.2: The Serializable interface 278 .................................................................................................................. Chapter 53: Serialization 280 ...................................................................................................................................... Section 53.1: Serialization of dierent types 280 ........................................................................................................... Section 53.2: Security Issues with unserialize 281 ......................................................................................................... Chapter 54: Closure 284 ................................................................................................................................................ Section 54.1: Basic usage of a closure 284 .................................................................................................................... Section 54.2: Using external variables 284 .................................................................................................................... Section 54.3: Basic closure binding 285 .........................................................................................................................
Page
9
Section 54.4: Closure binding and scope 285 ................................................................................................................ Section 54.5: Binding a closure for one call 287 ........................................................................................................... Section 54.6: Use closures to implement observer pattern 287 .................................................................................. Chapter 55: Reading Request Data 290 ................................................................................................................ Section 55.1: Reading raw POST data 290 ..................................................................................................................... Section 55.2: Reading POST data 290 ............................................................................................................................ Section 55.3: Reading GET data 290 .............................................................................................................................. Section 55.4: Handling file upload errors 291 ............................................................................................................... Section 55.5: Passing arrays by POST 291 .................................................................................................................... Section 55.6: Uploading files with HTTP PUT 293 ......................................................................................................... Chapter 56: Type juggling and Non-Strict Comparison Issues 294 ......................................................... Section 56.1: What is Type Juggling? 294 ...................................................................................................................... Section 56.2: Reading from a file 294 ............................................................................................................................ Section 56.3: Switch surprises 295 .................................................................................................................................. Section 56.4: Strict typing 296 ......................................................................................................................................... Chapter 57: Sockets 298 ................................................................................................................................................ Section 57.1: TCP client socket 298 ................................................................................................................................. Section 57.2: TCP server socket 299 ............................................................................................................................... Section 57.3: UDP server socket 299 .............................................................................................................................. Section 57.4: Handling socket errors 300 ...................................................................................................................... Chapter 58: PDO 301 ........................................................................................................................................................ Section 58.1: Preventing SQL injection with Parameterized Queries 301 .................................................................... Section 58.2: Basic PDO Connection and Retrieval 302 ............................................................................................... Section 58.3: Database Transactions with PDO 303 ..................................................................................................... Section 58.4: PDO: connecting to MySQL/MariaDB server 305 .................................................................................. Section 58.5: PDO: Get number of aected rows by a query 306 .............................................................................. Section 58.6: PDO::lastInsertId() 306 ............................................................................................................................... Chapter 59: PHP MySQLi 308 ....................................................................................................................................... Section 59.1: Close connection 308 ................................................................................................................................. Section 59.2: MySQLi connect 308 .................................................................................................................................. Section 59.3: Loop through MySQLi results 309 ............................................................................................................ Section 59.4: Prepared statements in MySQLi 309 ....................................................................................................... Section 59.5: Escaping Strings 310 ................................................................................................................................. Section 59.6: Debugging SQL in MySQLi 311 ................................................................................................................ Section 59.7: MySQLi query 311 ...................................................................................................................................... Section 59.8: How to get data from a prepared statement 312 ................................................................................. Section 59.9: MySQLi Insert ID 314 ................................................................................................................................. Chapter 60: SQLite3 316 ................................................................................................................................................ Section 60.1: SQLite3 Quickstart Tutorial 316 ................................................................................................................ Section 60.2: Querying a database 317 ......................................................................................................................... Section 60.3: Retrieving only one result 318 .................................................................................................................. Chapter 61: Using MongoDB 319 ................................................................................................................................ Section 61.1: Connect to MongoDB 319 .......................................................................................................................... Section 61.2: Get multiple documents - find() 319 ......................................................................................................... Section 61.3: Get one document - findOne() 319 ........................................................................................................... Section 61.4: Insert document 319 .................................................................................................................................. Section 61.5: Update a document 319 ............................................................................................................................ Section 61.6: Delete a document 320 .............................................................................................................................. Chapter 62: mongo-php 321 ........................................................................................................................................
Page
10
Section 62.1: Everything in between MongoDB and Php 321 ...................................................................................... Chapter 63: Using Redis with PHP 324 .................................................................................................................... Section 63.1: Connecting to a Redis instance 324 ......................................................................................................... Section 63.2: Installing PHP Redis on Ubuntu 324 ......................................................................................................... Section 63.3: Executing Redis commands in PHP 324 .................................................................................................. Chapter 64: Sending Email 325 .................................................................................................................................. Section 64.1: Sending Email - The basics, more details, and a full example 325 ....................................................... Section 64.2: Sending HTML Email Using mail() 327 .................................................................................................... Section 64.3: Sending Email With An Attachment Using mail() 328 ............................................................................ Section 64.4: Sending Plain Text Email Using PHPMailer 329 ...................................................................................... Section 64.5: Sending HTML Email Using PHPMailer 330 ............................................................................................. Section 64.6: Sending Email With An Attachment Using PHPMailer 331 .................................................................... Section 64.7: Sending Plain Text Email Using Sendgrid 331 ........................................................................................ Section 64.8: Sending Email With An Attachment Using Sendgrid 332 ...................................................................... Chapter 65: Using SQLSRV 333 .................................................................................................................................. Section 65.1: Retrieving Error Messages 333 ................................................................................................................. Section 65.2: Fetching Query Results 333 ...................................................................................................................... Section 65.3: Creating a Connection 334 ....................................................................................................................... Section 65.4: Making a Simple Query 334 ..................................................................................................................... Section 65.5: Invoking a Stored Procedure 334 ............................................................................................................ Section 65.6: Making a Parameterised Query 335 ........................................................................................................ Chapter 66: Command Line Interface (CLI) 336 ................................................................................................. Section 66.1: Handling Program Options 336 ................................................................................................................ Section 66.2: Argument Handling 337 ............................................................................................................................ Section 66.3: Input and Output Handling 338 ................................................................................................................ Section 66.4: Return Codes 339 ...................................................................................................................................... Section 66.5: Restrict script execution to command line 339 ...................................................................................... Section 66.6: Behavioural dierences on the command line 339 ............................................................................... Section 66.7: Running your script 340 ............................................................................................................................ Section 66.8: Edge Cases of getopt() 340 ...................................................................................................................... Section 66.9: Running built-in web server 341 ............................................................................................................... Chapter 67: Localization 343 ....................................................................................................................................... Section 67.1: Localizing strings with gettext() 343 ......................................................................................................... Chapter 68: Headers Manipulation 344 ................................................................................................................. Section 68.1: Basic Setting of a Header 344 .................................................................................................................. Chapter 69: Coding Conventions 345 ...................................................................................................................... Section 69.1: PHP Tags 345 .............................................................................................................................................. Chapter 70: Asynchronous programming 346 ................................................................................................... Section 70.1: Advantages of Generators 346 ................................................................................................................. Section 70.2: Using Icicle event loop 346 ....................................................................................................................... Section 70.3: Spawning non-blocking processes with proc_open() 347 .................................................................... Section 70.4: Reading serial port with Event and DIO 348 ........................................................................................... Section 70.5: HTTP Client Based on Event Extension 350 ............................................................................................ Section 70.6: HTTP Client Based on Ev Extension 353 .................................................................................................. Section 70.7: Using Amp event loop 357 ........................................................................................................................ Chapter 71: How to Detect Client IP Address 359 ............................................................................................. Section 71.1: Proper use of HTTP_X_FORWARDED_FOR 359 ..................................................................................... Chapter 72: Create PDF files in PHP 361 ................................................................................................................ Section 72.1: Getting Started with PDFlib 361 ................................................................................................................
Page
11
Chapter 73: YAML in PHP 362 ....................................................................................................................................... Section 73.1: Installing YAML extension 362 ................................................................................................................... Section 73.2: Using YAML to store application configuration 362 ............................................................................... Chapter 74: Image Processing with GD 364 ........................................................................................................ Section 74.1: Image output 364 ....................................................................................................................................... Section 74.2: Creating an image 365 ............................................................................................................................. Section 74.3: Image Cropping and Resizing 366 ........................................................................................................... Chapter 75: Imagick 369 ................................................................................................................................................ Section 75.1: First Steps 369 ............................................................................................................................................. Section 75.2: Convert Image into base64 String 369 .................................................................................................... Chapter 76: SOAP Server 371 ...................................................................................................................................... Section 76.1: Basic SOAP Server 371 ............................................................................................................................... Chapter 77: Machine learning 372 ............................................................................................................................ Section 77.1: Classification using PHP-ML 372 ............................................................................................................... Section 77.2: Regression 373 ........................................................................................................................................... Section 77.3: Clustering 375 ............................................................................................................................................. Chapter 78: Cache 377 .................................................................................................................................................... Section 78.1: Caching using memcache 377 .................................................................................................................. Section 78.2: Cache Using APC Cache 378 .................................................................................................................... Chapter 79: Autoloading Primer 380 ....................................................................................................................... Section 79.1: Autoloading as part of a framework solution 380 .................................................................................. Section 79.2: Inline class definition, no loading required 380 ...................................................................................... Section 79.3: Manual class loading with require 381 .................................................................................................... Section 79.4: Autoloading replaces manual class definition loading 381 .................................................................. Section 79.5: Autoloading with Composer 382 .............................................................................................................. Chapter 80: SPL data structures 383 ...................................................................................................................... Section 80.1: SplFixedArray 383 ...................................................................................................................................... Chapter 81: IMAP 387 ....................................................................................................................................................... Section 81.1: Connecting to a mailbox 387 ..................................................................................................................... Section 81.2: Install IMAP extension 388 ......................................................................................................................... Section 81.3: List all folders in the mailbox 388 ............................................................................................................. Section 81.4: Finding messages in the mailbox 389 ...................................................................................................... Chapter 82: HTTP Authentication 391 ..................................................................................................................... Section 82.1: Simple authenticate 391 ............................................................................................................................ Chapter 83: WebSockets 392 ....................................................................................................................................... Section 83.1: Simple TCP/IP server 392 .......................................................................................................................... Chapter 84: BC Math (Binary Calculator) 394 .................................................................................................... Section 84.1: Using bcmath to read/write a binary long on 32-bit system 394 ........................................................ Section 84.2: Comparison between BCMath and float arithmetic operations 395 ................................................... Chapter 85: Docker deployment 397 ...................................................................................................................... Section 85.1: Get docker image for php 397 .................................................................................................................. Section 85.2: Writing dockerfile 397 ............................................................................................................................... Section 85.3: Building image 397 .................................................................................................................................... Section 85.4: Starting application container 398 .......................................................................................................... Chapter 86: APCu 399 ...................................................................................................................................................... Section 86.1: Iterating over Entries 399 .......................................................................................................................... Section 86.2: Simple storage and retrieval 399 ............................................................................................................. Section 86.3: Store information 399 ...............................................................................................................................
Page
12
Chapter 87: PHP Built in server 400 ......................................................................................................................... Section 87.1: Running the built in server 400 .................................................................................................................. Section 87.2: built in server with specific directory and router script 400 .................................................................. Chapter 88: PSR 401 ........................................................................................................................................................ Section 88.1: PSR-4: Autoloader 401 ............................................................................................................................... Section 88.2: PSR-1: Basic Coding Standard 402 ........................................................................................................... Chapter 89: PHPDoc 403 ................................................................................................................................................ Section 89.1: Describing a variable 403 .......................................................................................................................... Section 89.2: Adding metadata to functions 403 .......................................................................................................... Section 89.3: Describing parameters 404 ...................................................................................................................... Section 89.4: Collections 405 ........................................................................................................................................... Section 89.5: Adding metadata to files 406 ................................................................................................................... Section 89.6: Inheriting metadata from parent structures 406 ................................................................................... Chapter 90: Design Patterns 408 .............................................................................................................................. Section 90.1: Method Chaining in PHP 408 ..................................................................................................................... Chapter 91: Compile PHP Extensions 410 ............................................................................................................... Section 91.1: Compiling on Linux 410 ............................................................................................................................... Chapter 92: Common Errors 411 ............................................................................................................................... Section 92.1: Call fetch_assoc on boolean 411 ............................................................................................................. Section 92.2: Unexpected $end 411 ............................................................................................................................... Chapter 93: Compilation of Errors and Warnings 413 ................................................................................... Section 93.1: Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM 413 ......................................... Section 93.2: Notice: Undefined index 413 ..................................................................................................................... Section 93.3: Warning: Cannot modify header information - headers already sent 413 ......................................... Chapter 94: Exception Handling and Error Reporting 415 .......................................................................... Section 94.1: Setting error reporting and where to display them 415 ........................................................................ Section 94.2: Logging fatal errors 415 ........................................................................................................................... Chapter 95: Debugging 417 .......................................................................................................................................... Section 95.1: Dumping variables 417 .............................................................................................................................. Section 95.2: Displaying errors 417 ................................................................................................................................ Section 95.3: phpinfo() 418 .............................................................................................................................................. Section 95.4: Xdebug 418 ................................................................................................................................................ Section 95.5: Error Reporting (use them both) 419 ...................................................................................................... Section 95.6: phpversion() 419 ........................................................................................................................................ Chapter 96: Unit Testing 420 ....................................................................................................................................... Section 96.1: Testing class rules 420 ............................................................................................................................... Section 96.2: PHPUnit Data Providers 423 ..................................................................................................................... Section 96.3: Test exceptions 426 ................................................................................................................................... Chapter 97: Performance 428 ..................................................................................................................................... Section 97.1: Profiling with Xdebug 428 .......................................................................................................................... Section 97.2: Memory Usage 429 ................................................................................................................................... Section 97.3: Profiling with XHProf 430 .......................................................................................................................... Chapter 98: Multiprocessing 432 ............................................................................................................................... Section 98.1: Multiprocessing using built-in fork functions 432 .................................................................................... Section 98.2: Creating child process using fork 432 ..................................................................................................... Section 98.3: Inter-Process Communication 433 ........................................................................................................... Chapter 99: Multi Threading Extension 434 ......................................................................................................... Section 99.1: Getting Started 434 ....................................................................................................................................
Page
13
Section 99.2: Using Pools and Workers 434 .................................................................................................................. Chapter 100: Secure Remeber Me 436 ................................................................................................................... Section 100.1: “Keep Me Logged In” - the best approach 436 ..................................................................................... Chapter 101: Security 437 .............................................................................................................................................. Section 101.1: PHP Version Leakage 437 ......................................................................................................................... Section 101.2: Cross-Site Scripting (XSS) 437 ................................................................................................................. Section 101.3: Cross-Site Request Forgery 439 .............................................................................................................. Section 101.4: Command Line Injection 440 ................................................................................................................... Section 101.5: Stripping Tags 441 .................................................................................................................................... Section 101.6: File Inclusion 442 ....................................................................................................................................... Section 101.7: Error Reporting 442 .................................................................................................................................. Section 101.8: Uploading files 443 ................................................................................................................................... Chapter 102: Cryptography 446 ................................................................................................................................. Section 102.1: Symmetric Encryption and Decryption of large Files with OpenSSL 446 ........................................... Section 102.2: Symmetric Cipher 448 ............................................................................................................................. Chapter 103: Password Hashing Functions 449 .................................................................................................. Section 103.1: Creating a password hash 449 ................................................................................................................ Section 103.2: Determine if an existing password hash can be upgraded to a stronger algorithm 450 ................ Section 103.3: Verifying a password against a hash 451 ............................................................................................. Chapter 104: Contributing to the PHP Manual 452 .......................................................................................... Section 104.1: Improve the ocial documentation 452 ................................................................................................ Section 104.2: Tips for contributing to the manual 452 ................................................................................................ Chapter 105: Contributing to the PHP Core 453 ................................................................................................ Section 105.1: Setting up a basic development environment 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 ......................................................................................................................................................
Page
14
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
Page
15
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>
Page
16
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.
Page
17
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.
Page
18
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
Page
19
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>
Page
20
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.
Comments 0
Loading comments...
Reply to Comment
Edit Comment