đź”™ Quay lại trang tải sách pdf ebook PHP Notes for Professionals Ebooks NhĂłm Zalo Notes for Professionals PHP PHP Notes for Professionals 400+ pages of professional hints and tricks GoalKicker.com Free Programming Books Disclaimer This is an unocial free book created for educational purposes and is not aliated with ocial PHP group(s) or company(s). All trademarks and registered trademarks are the property of their respective owners 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: Dierence between __FUNCTION__ and __METHOD__ ................................................................. 43 Section 7.2: Dierence 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 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 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 dierence 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 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 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 Buering ............................................................................................................................ 171 Section 30.1: Basic usage getting content between buers and clearing .......................................................... 171 Section 30.2: Processing the buer via a callback ................................................................................................ 171 Section 30.3: Nested output buers ........................................................................................................................ 172 Section 30.4: Running output buer before any content ..................................................................................... 173 Section 30.5: Stream output to client ...................................................................................................................... 174 Section 30.6: Using Output buer 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 buer 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 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: Dierence 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 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 dierent 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 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 aected 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 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 dierences 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 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 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 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 ocial 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 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 [email protected] GoalKicker.com – PHP Notes for Professionals 1 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: PHP!

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: GoalKicker.com – PHP Notes for Professionals 2 PHP!

Hello world!

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:

Its output is identical to the output of the following:

In real-world applications, all data output by PHP to an HTML page should be properly escaped to prevent XSS (Cross-site scripting) attacks or text corruption. See also: Strings and PSR-1, which describes best practices, including the proper use of short tags (). Section 1.2: Hello, World! The most widely used language construct to print output in PHP is echo: echo "Hello, World!\n"; Alternatively, you can also use print: print "Hello, World!\n"; Both statements perform the same function, with minor differences: echo has a void return, whereas print returns an int with a value of 1 echo can take multiple arguments (without parentheses only), whereas print only takes one argument echo is slightly faster than print Both echo and print are language constructs, not functions. That means they do not require parentheses around their arguments. For cosmetic consistency with functions, parentheses can be included. Extensive examples of the use of echo and print are available elsewhere. C-style printf and related functions are available as well, as in the following example: printf("%s\n", "Hello, World!"); See Outputting the value of a variable for a comprehensive introduction of outputting variables in PHP. Section 1.3: Non-HTML output from web server In some cases, when working with a web server, overriding the web server's default content type may be required. There may be cases where you need to send data as plain text, JSON, or XML, for example. GoalKicker.com – PHP Notes for Professionals 3 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 from files that contain only PHP and from blocks of PHP code at the very end of a file. View the output buffering section to learn how to 'catch' your content into a variable to output later, for example, after outputting headers. GoalKicker.com – PHP Notes for Professionals 4 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 : Example usage 1. Create an index.php file containing: : -t 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: 1. Standard input. Run the php command without any arguments, but pipe PHP code into it: echo ' 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 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: GoalKicker.com – PHP Notes for Professionals 6 We can also leave out the semicolon of the last statement in a PHP code block if that code block has a closing tag: 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:

Some HTML code goes here

Some HTML code goes here

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. Short Tags You can disable or enable these tags with the option short_open_tag. GoalKicker.com – PHP Notes for Professionals 7 Short tags: are disallowed in all major PHP coding standards are discouraged in the official documentation are disabled by default in most distributions interfere with inline XML's processing instructions are not accepted in code submissions by most open source projects PHP 5.x Version ≤ 5.6 ASP Tags By enabling the asp_tags option, ASP-style tags can be used. <% echo "Hello World"; %> These are an historic quirk and should never be used. They were removed in PHP 7.0. GoalKicker.com – PHP Notes for Professionals 8 Chapter 2: Variables Section 2.1: Accessing A Variable Dynamically By Name (Variable variables) Variables can be accessed via dynamic variable names. The name of a variable can be stored in another variable, allowing it to be accessed dynamically. Such variables are known as variable variables. To turn a variable into a variable variable, you put an extra $ put in front of your variable. $variableName = 'foo'; $foo = 'bar'; // The following are all equivalent, and all output "bar": echo $foo; echo ${$variableName}; echo $$variableName; //similarly, $variableName = 'foo'; $$variableName = 'bar'; // The following statements will also output 'bar' echo $foo; echo $$variableName; echo ${$variableName}; Variable variables are useful for mapping function/method calls: function add($a, $b) { return $a + $b; } $funcName = 'add'; echo $funcName(1, 2); // outputs 3 This becomes particularly helpful in PHP classes: class myClass { public function __construct() { $functionName = 'doSomething'; $this->$functionName('Hello World'); } private function doSomething($string) { echo $string; // Outputs "Hello World" } } It is possible, but not required to put $variableName between {}: ${$variableName} = $value; The following examples are both equivalent and output "baz": $fooBar = 'baz'; GoalKicker.com – PHP Notes for Professionals 9 $varPrefix = 'foo'; echo $fooBar; // Outputs "baz" echo ${$varPrefix . 'Bar'}; // Also outputs "baz" Using {} is only mandatory when the name of the variable is itself an expression, like this: ${$variableNamePart1 . $variableNamePart2} = $value; It is nevertheless recommended to always use {}, because it's more readable. While it is not recommended to do so, it is possible to chain this behavior: $$$$$$$$DoNotTryThisAtHomeKids = $value; It's important to note that the excessive usage of variable variables is considered a bad practice by many developers. Since they're not well-suited for static analysis by modern IDEs, large codebases with many variable variables (or dynamic method invocations) can quickly become difficult to maintain. Differences between PHP5 and PHP7 Another reason to always use {} or (), is that PHP5 and PHP7 have a slightly different way of dealing with dynamic variables, which results in a different outcome in some cases. In PHP7, dynamic variables, properties, and methods will now be evaluated strictly in left-to-right order, as opposed to the mix of special cases in PHP5. The examples below show how the order of evaluation has changed. Case 1 : $$foo['bar']['baz'] PHP5 interpretation : ${$foo['bar']['baz']} PHP7 interpretation : ($$foo)['bar']['baz'] Case 2 : $foo->$bar['baz'] PHP5 interpretation : $foo->{$bar['baz']} PHP7 interpretation : ($foo->$bar)['baz'] Case 3 : $foo->$bar['baz']() PHP5 interpretation : $foo->{$bar['baz']}() PHP7 interpretation : ($foo->$bar)['baz']() Case 4 : Foo::$bar['baz']() PHP5 interpretation : Foo::{$bar['baz']}() PHP7 interpretation : (Foo::$bar)['baz']() Section 2.2: Data Types There are different data types for different purposes. PHP does not have explicit type definitions, but the type of a variable is determined by the type of the value that is assigned, or by the type that it is casted to. This is a brief overview about the types, for a detailed documentation and examples, see the PHP types topic. There are following data types in PHP: null, boolean, integer, float, string, object, resource and array. GoalKicker.com – PHP Notes for Professionals 10 Null Null can be assigned to any variable. It represents a variable with no value. $foo = null; This invalidates the variable and it's value would be undefined or void if called. The variable is cleared from memory and deleted by the garbage collector. Boolean This is the simplest type with only two possible values. $foo = true; $bar = false; Booleans can be used to control the flow of code. $foo = true; if ($foo) { echo "true"; } else { echo "false"; } Integer An integer is a whole number positive or negative. It can be in used with any number base. The size of an integer is platform-dependent. PHP does not support unsigned integers. $foo = -3; // negative $foo = 0; // zero (can also be null or false (as boolean) $foo = 123; // positive decimal $bar = 0123; // octal = 83 decimal $bar = 0xAB; // hexadecimal = 171 decimal $bar = 0b1010; // binary = 10 decimal var_dump(0123, 0xAB, 0b1010); // output: int(83) int(171) int(10) Float Floating point numbers, "doubles" or simply called "floats" are decimal numbers. $foo = 1.23; $foo = 10.0; $bar = -INF; $bar = NAN; Array An array is like a list of values. The simplest form of an array is indexed by integer, and ordered by the index, with the first element lying at index 0. $foo = array(1, 2, 3); // An array of integers $bar = ["A", true, 123 => 5]; // Short array syntax, PHP 5.4+ GoalKicker.com – PHP Notes for Professionals 11 echo $bar[0]; // Returns "A" echo $bar[1]; // Returns true echo $bar[123]; // Returns 5 echo $bar[1234]; // Returns null Arrays can also associate a key other than an integer index to a value. In PHP, all arrays are associative arrays behind the scenes, but when we refer to an 'associative array' distinctly, we usually mean one that contains one or more keys that aren't integers. $array = array(); $array["foo"] = "bar"; $array["baz"] = "quux"; $array[42] = "hello"; echo $array["foo"]; // Outputs "bar" echo $array["bar"]; // Outputs "quux" echo $array[42]; // Outputs "hello" String A string is like an array of characters. $foo = "bar"; Like an array, a string can be indexed to return its individual characters: $foo = "bar"; echo $foo[0]; // Prints 'b', the first character of the string in $foo. Object An object is an instance of a class. Its variables and methods can be accessed with the -> operator. $foo = new stdClass(); // create new object of class stdClass, which a predefined, empty class $foo->bar = "baz"; echo $foo->bar; // Outputs "baz" // Or we can cast an array to an object: $quux = (object) ["foo" => "bar"]; echo $quux->foo; // This outputs "bar". Resource Resource variables hold special handles to opened files, database connections, streams, image canvas areas and the like (as it is stated in the manual). $fp = fopen('file.ext', 'r'); // fopen() is the function to open a file on disk as a resource. var_dump($fp); // output: resource(2) of type (stream) To get the type of a variable as a string, use the gettype() function: echo gettype(1); // outputs "integer" echo gettype(true); // "boolean" GoalKicker.com – PHP Notes for Professionals 12 Section 2.3: Global variable best practices We can illustrate this problem with the following pseudo-code function foo() { global $bob; $bob->doSomething(); } Your first question here is an obvious one Where did $bob come from? Are you confused? Good. You've just learned why globals are confusing and considered a bad practice. If this were a real program, your next bit of fun is to go track down all instances of $bob and hope you find the right one (this gets worse if $bob is used everywhere). Worse, if someone else goes and defines $bob (or you forgot and reused that variable) your code can break (in the above code example, having the wrong object, or no object at all, would cause a fatal error). Since virtually all PHP programs make use of code like include('file.php'); your job maintaining code like this becomes exponentially harder the more files you add. Also, this makes the task of testing your applications very difficult. Suppose you use a global variable to hold your database connection: $dbConnector = new DBConnector(...); function doSomething() { global $dbConnector; $dbConnector->execute("..."); } In order to unit test this function, you have to override the global $dbConnector variable, run the tests and then reset it to its original value, which is very bug prone: /** * @test */ function testSomething() { global $dbConnector; $bkp = $dbConnector; // Make backup $dbConnector = Mock::create('DBConnector'); // Override assertTrue(foo()); $dbConnector = $bkp; // Restore } How do we avoid Globals? The best way to avoid globals is a philosophy called Dependency Injection. This is where we pass the tools we need into the function or class. GoalKicker.com – PHP Notes for Professionals 13 function foo(\Bar $bob) { $bob->doSomething(); } This is much easier to understand and maintain. There's no guessing where $bob was set up because the caller is responsible for knowing that (it's passing us what we need to know). Better still, we can use type declarations to restrict what's being passed. So we know that $bob is either an instance of the Bar class, or an instance of a child of Bar, meaning we know we can use the methods of that class. Combined with a standard autoloader (available since PHP 5.3), we can now go track down where Bar is defined. PHP 7.0 or later includes expanded type declarations, where you can also use scalar types (like int or string). Version = 4.1 Superglobal variables Super globals in PHP are predefined variables, which are always available, can be accessed from any scope throughout the script. There is no need to do global $variable; to access them within functions/methods, classes or files. These PHP superglobal variables are listed below: $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_ENV $_COOKIE $_SESSION Section 2.4: Default values of uninitialized variables Although not necessary in PHP however it is a very good practice to initialize variables. Uninitialized variables have a default value of their type depending on the context in which they are used: Unset AND unreferenced var_dump($unset_var); // outputs NULL Boolean echo($unset_bool ? "true\n" : "false\n"); // outputs 'false' String $unset_str .= 'abc'; var_dump($unset_str); // outputs 'string(3) "abc"' Integer GoalKicker.com – PHP Notes for Professionals 14 $unset_int += 25; // 0 + 25 => 25 var_dump($unset_int); // outputs 'int(25)' Float/double $unset_float += 1.25; var_dump($unset_float); // outputs 'float(1.25)' Array $unset_arr[3] = "def"; var_dump($unset_arr); // outputs array(1) { [3]=> string(3) "def" } Object $unset_obj->foo = 'bar'; var_dump($unset_obj); // Outputs: object(stdClass)#1 (1) { ["foo"]=> string(3) "bar" } Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. Section 2.5: Variable Value Truthiness and Identical Operator In PHP, variable values have an associated "truthiness" so even non-boolean values will equate to true or false. This allows any variable to be used in a conditional block, e.g. if ($var == true) { /* explicit version */ } if ($var) { /* $var == true is implicit */ } Here are some fundamental rules for different types of variable values: Strings with non-zero length equate to true including strings containing only whitepace such as ' '. Empty strings '' equate to false. $var = ''; $var_is_true = ($var == true); // false $var_is_false = ($var == false); // true $var = ' '; $var_is_true = ($var == true); // true $var_is_false = ($var == false); // false Integers equate to true if they are nonzero, while zero equates to false. $var = -1; $var_is_true = ($var == true); // true $var = 99; $var_is_true = ($var == true); // true $var = 0; $var_is_true = ($var == true); // false null equates to false $var = null; $var_is_true = ($var == true); // false $var_is_false = ($var == false); // true GoalKicker.com – PHP Notes for Professionals 15 Empty strings '' and string zero '0' equate to false. $var = ''; $var_is_true = ($var == true); // false $var_is_false = ($var == false); // true $var = '0'; $var_is_true = ($var == true); // false $var_is_false = ($var == false); // true Floating-point values equate to true if they are nonzero, while zero values equates to false. NAN (PHP's Not-a-Number) equates to true, i.e. NAN == true is true. This is because NAN is a nonzero floating-point value. Zero-values include both +0 and -0 as defined by IEEE 754. PHP does not distinguish between +0 and -0 in its double-precision floating-point, i.e. floatval('0') == floatval('-0') is true. In fact, floatval('0') === floatval('-0'). Additionally, both floatval('0') == false and floatval('-0') == false. $var = NAN; $var_is_true = ($var == true); // true $var_is_false = ($var == false); // false $var = floatval('-0'); $var_is_true = ($var == true); // false $var_is_false = ($var == false); // true $var = floatval('0') == floatval('-0'); $var_is_true = ($var == true); // false $var_is_false = ($var == false); // true IDENTICAL OPERATOR In the PHP Documentation for Comparison Operators, there is an Identical Operator ===. This operator can be used to check whether a variable is identical to a reference value: $var = null; $var_is_null = $var === null; // true $var_is_true = $var === true; // false $var_is_false = $var === false; // false It has a corresponding not identical operator !==: $var = null; $var_is_null = $var !== null; // false $var_is_true = $var !== true; // true $var_is_false = $var !== false; // true The identical operator can be used as an alternative to language functions like is_null(). USE CASE WITH strpos() The strpos($haystack, $needle) language function is used to locate the index at which $needle occurs in $haystack, or whether it occurs at all. The strpos() function is case sensitive; if case-insensitive find is what you need you can go with stripos($haystack, $needle) The strpos & stripos function also contains third parameter offset (int) which if specified, search will start this number of characters counted from the beginning of the string. Unlike strrpos and strripos, the offset cannot be GoalKicker.com – PHP Notes for Professionals 16 negative The function can return: 0 if $needle is found at the beginning of $haystack; a non-zero integer specifying the index if $needle is found somewhere other than the beginning in $haystack; and value false if $needle is not found anywhere in $haystack. Because both 0 and false have truthiness false in PHP but represent distinct situations for strpos(), it is important to distinguish between them and use the identical operator === to look exactly for false and not just a value that equates to false. $idx = substr($haystack, $needle); if ($idx === false) { // logic for when $needle not found in $haystack } else { // logic for when $needle found in $haystack } Alternatively, using the not identical operator: $idx = substr($haystack, $needle); if ($idx !== false) { // logic for when $needle found in $haystack } else { // logic for when $needle not found in $haystack } GoalKicker.com – PHP Notes for Professionals 17 Chapter 3: Variable Scope Variable scope refers to the regions of code where a variable may be accessed. This is also referred to as visibility. In PHP scope blocks are defined by functions, classes, and a global scope available throughout an application. Section 3.1: Superglobal variables Superglobal variables are defined by PHP and can always be used from anywhere without the global keyword. string 'localhost' (length=9) 'HTTP_CONNECTION' => string 'keep-alive' (length=10) 'HTTP_CACHE_CONTROL' => string 'max-age=0' (length=9) 'HTTP_UPGRADE_INSECURE_REQUESTS' => string '1' (length=1) 'HTTP_USER_AGENT' => string 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36' (length=110) 'HTTP_ACCEPT' => string 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' (length=74) 'HTTP_ACCEPT_ENCODING' => string 'gzip, deflate, sdch, br' (length=23) 'HTTP_ACCEPT_LANGUAGE' => string 'en-US,en;q=0.8,en-GB;q=0.6' (length=26) 'HTTP_COOKIE' => string 'PHPSESSID=0gslnvgsci371ete9hg7k9ivc6' (length=36) 'PATH' => string 'C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem ;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;E:\Program Files\ATI Technologies\ATI.ACE\Core Static;E:\Program Files\AMD\ATI.ACE\Core-Static;C:\Program Files (x86)\AMD\ATI.ACE\Core Static;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;C:\Program Files\Intel\Intel(R) Managemen'... (length=1169) 'SystemRoot' => string 'C:\WINDOWS' (length=10) 'COMSPEC' => string 'C:\WINDOWS\system32\cmd.exe' (length=27) 'PATHEXT' => string '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY' (length=57) 'WINDIR' => string 'C:\WINDOWS' (length=10) 'SERVER_SIGNATURE' => string '
Apache/2.4.23 (Win64) PHP/7.0.10 Server at localhost Port 80
' (length=80) 'SERVER_SOFTWARE' => string 'Apache/2.4.23 (Win64) PHP/7.0.10' (length=32) 'SERVER_NAME' => string 'localhost' (length=9) 'SERVER_ADDR' => string '::1' (length=3) 'SERVER_PORT' => string '80' (length=2) 'REMOTE_ADDR' => string '::1' (length=3) 'DOCUMENT_ROOT' => string 'C:/wamp64/www' (length=13) 'REQUEST_SCHEME' => string 'http' (length=4) 'CONTEXT_PREFIX' => string '' (length=0) 'CONTEXT_DOCUMENT_ROOT' => string 'C:/wamp64/www' (length=13) 'SERVER_ADMIN' => string '[email protected]' (length=29) 'SCRIPT_FILENAME' => string 'C:/wamp64/www/test.php' (length=26) 'REMOTE_PORT' => string '5359' (length=4) 'GATEWAY_INTERFACE' => string 'CGI/1.1' (length=7) 'SERVER_PROTOCOL' => string 'HTTP/1.1' (length=8) 'REQUEST_METHOD' => string 'GET' (length=3) 'QUERY_STRING' => string '' (length=0) 'REQUEST_URI' => string '/test.php' (length=13) 'SCRIPT_NAME' => string '/test.php' (length=13) 'PHP_SELF' => string '/test.php' (length=13) 'REQUEST_TIME_FLOAT' => float 1491068771.413 'REQUEST_TIME' => int 1491068771 There is a lot to take in there so I will pick out some important ones below. If you wish to read about them all then consult the indices section of the documentation. I might add them all below one day. Or someone can edit and add a good explanation of them below? Hint, hint;) For all explanations below, assume the URL is http://www.example.com/index.php HTTP_HOST - The host address. GoalKicker.com – PHP Notes for Professionals 23 This would return www.example.com HTTP_USER_AGENT - Contents of the user agent. This is a string which contains all the information about the client's browser, including operating system. HTTP_COOKIE - All cookies in a concatenated string, with a semi-colon delimiter. SERVER_ADDR - The IP address of the server, of which the current script is running. This would return 93.184.216.34 PHP_SELF - The file name of the currently executed script, relative to document root. This would return /index.php REQUEST_TIME_FLOAT - The timestamp of the start of the request, with microsecond precision. Available since PHP 5.4.0. REQUEST_TIME - The timestamp of the start of the request. Available since PHP 5.1.0. $_GET An associative array of variables passed to the current script via the URL parameters. $_GET is an array that contains all the URL parameters; these are the whatever is after the ? in the URL. Using http://www.example.com/index.php?myVar=myVal as an example. This information from this URL can be obtained by accessing in this format $_GET["myVar"] and the result of this will be myVal. Using some code for those that don't like reading. // URL = http://www.example.com/index.php?myVar=myVal echo $_GET["myVar"] == "myVal" ? "true" : "false"; // returns "true" The above example makes use of the ternary operator. This shows how you can access the value from the URL using the $_GET superglobal. Now another example! gasp // URL = http://www.example.com/index.php?myVar=myVal&myVar2=myVal2 echo $_GET["myVar"]; // returns "myVal" echo $_GET["myVar2"]; // returns "myVal2" It is possible to send multiple variables through the URL by separating them with an ampersand (&) character. Security risk It is very important not to send any sensitive information via the URL as it will stay in history of the computer and will be visible to anyone that can access that browser. $_POST An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request. Very similar to $_GET in that data is sent from one place to another. I'll start by going straight into an example. (I have omitted the action attribute as this will send the information to the page that the form is in). GoalKicker.com – PHP Notes for Professionals 24
Above is a basic form for which data can be sent. In an real environment the value attribute would not be set meaning the form would be blank. This would then send whatever information is entered by the user. echo $_POST["myVar"]); // returns "myVal" Security risk Sending data via POST is also not secure. Using HTTPS will ensure that data is kept more secure. $_FILES An associative array of items uploaded to the current script via the HTTP POST method. The structure of this array is outlined in the POST method uploads section. Let's start with a basic form.
Note that I omitted the action attribute (again!). Also, I added enctype="multipart/form-data", this is important to any form that will be dealing with file uploads. // ensure there isn't an error if ($_FILES["myVar"]["error"] == UPLOAD_ERR_OK) { $folderLocation = "myFiles"; // a relative path. (could be "path/to/file" for example) // if the folder doesn't exist then make it if (!file_exists($folderLocation)) mkdir($folderLocation); // move the file into the folder move_uploaded_file($_FILES["myVar"]["tmp_name"], "$folderLocation/" . basename($_FILES["myVar"]["name"])); } This is used to upload one file. Sometimes you may wish to upload more than one file. An attribute exists for that, it's called multiple. There's an attribute for just about anything. I'm sorry Below is an example of a form submitting multiple files.
Note the changes made here; there are only a few. The input name has square brackets. This is because it is now an array of files and so we are telling the form GoalKicker.com – PHP Notes for Professionals 25 to make an array of the files selected. Omitting the square brackets will result in the latter most file being set to $_FILES["myVar"]. The multiple="multiple" attribute. This just tells the browser that users can select more than one file. $total = isset($_FILES["myVar"]) ? count($_FILES["myVar"]["name"]) : 0; // count how many files were sent // iterate over each of the files for ($i = 0; $i < $total; $i++) { // there isn't an error if ($_FILES["myVar"]["error"][$i] == UPLOAD_ERR_OK) { $folderLocation = "myFiles"; // a relative path. (could be "path/to/file" for example) // if the folder doesn't exist then make it if (!file_exists($folderLocation)) mkdir($folderLocation); // move the file into the folder move_uploaded_file($_FILES["myVar"]["tmp_name"][$i], "$folderLocation/" . basename($_FILES["myVar"]["name"][$i])); } // else report the error else switch ($_FILES["myVar"]["error"][$i]) { case UPLOAD_ERR_INI_SIZE: echo "Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini."; break; case UPLOAD_ERR_FORM_SIZE: echo "Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form."; break; case UPLOAD_ERR_PARTIAL: echo "Value: 3; The uploaded file was only partially uploaded."; break; case UPLOAD_ERR_NO_FILE: echo "Value: 4; No file was uploaded."; break; case UPLOAD_ERR_NO_TMP_DIR: echo "Value: 6; Missing a temporary folder. Introduced in PHP 5.0.3."; break; case UPLOAD_ERR_CANT_WRITE: echo "Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0."; break; case UPLOAD_ERR_EXTENSION: echo "Value: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. Introduced in PHP 5.2.0."; break; default: echo "An unknown error has occurred."; break; } } This is a very simple example and doesn't handle problems such as file extensions that aren't allowed or files named with PHP code (like a PHP equivalent of an SQL injection). See the documentation. The first process is checking if there are any files, and if so, set the total number of them to $total. GoalKicker.com – PHP Notes for Professionals 26 Using the for loop allows an iteration of the $_FILES array and accessing each item one at a time. If that file doesn't encounter a problem then the if statement is true and the code from the single file upload is run. If an problem is encountered the switch block is executed and an error is presented in accordance with the error for that particular upload. $_COOKIE An associative array of variables passed to the current script via HTTP Cookies. Cookies are variables that contain data and are stored on the client's computer. Unlike the aforementioned superglobals, cookies must be created with a function (and not be assigning a value). The convention is below. setcookie("myVar", "myVal", time() + 3600); In this example a name is specified for the cookie (in this example it is "myVar"), a value is given (in this example it is "myVal", but a variable can be passed to assign its value to the cookie), and then an expiration time is given (in this example it is one hour since 3600 seconds is a minute). Despite the convention for creating a cookie being different, it is accessed in the same way as the others. echo $_COOKIE["myVar"]; // returns "myVal" To destroy a cookie, setcookie must be called again, but the expiration time is set to any time in the past. See below. setcookie("myVar", "", time() - 1); var_dump($_COOKIE["myVar"]); // returns null This will unset the cookies and remove it from the clients computer. $_SESSION An associative array containing session variables available to the current script. See the Session functions documentation for more information on how this is used. Sessions are much like cookies except they are server side. To use sessions you must include session_start() at the top of your scripts to allow sessions to be utilised. Setting a session variable is the same as setting any other variable. See example below. $_SESSION["myVar"] = "myVal"; When starting a session a random ID is set as a cookie and called "PHPSESSID" and will contain the session ID for that current session. This can be accessed by calling the session_id() function. It is possible to destroy session variables using the unset function (such that unset($_SESSION["myVar"]) would destroy that variable). The alternative is to call session_destory(). This will destroy the entire session meaning that all session variables will no longer exist. GoalKicker.com – PHP Notes for Professionals 27 $_REQUEST An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE. As the PHP documentation states, this is just a collation of $_GET, $_POST, and $_COOKIE all in one variable. Since it is possible for all three of those arrays to have an index with the same name, there is a setting in the php.ini file called request_order which can specify which of the three has precedence. For instance, if it was set to "GPC", then the value of $_COOKIE will be used, as it is read from left to right meaning the $_REQUEST will set its value to $_GET, then $_POST, and then $_COOKIE and since $_COOKIE is last that is the value that is in $_REQUEST. See this question. $_ENV An associative array of variables passed to the current script via the environment method. These variables are imported into PHP's global namespace from the environment under which the PHP parser is running. Many are provided by the shell under which PHP is running and different systems are likely running different kinds of shells, a definitive list is impossible. Please see your shell's documentation for a list of defined environment variables. Other environment variables include the CGI variables, placed there regardless of whether PHP is running as a server module or CGI processor. Anything stored within $_ENV is from the environment from which PHP is running in. $_ENV is only populated if php.ini allows it. See this answer for more information on why $_ENV is not populated. Section 4.2: PHP5 SuperGlobals Below are the PHP5 SuperGlobals $GLOBALS $_REQUEST $_GET $_POST $_FILES $_SERVER $_ENV $_COOKIE $_SESSION $GLOBALS: This SuperGlobal Variable is used for accessing globals variables. $_REQUEST: This SuperGlobal Variable is used to collect data submitted by a HTML Form. $_GET: This SuperGlobal Variable is used to collect data submitted by HTML Form with get method. $_POST: This SuperGlobal Variable is used to collect data submitted by HTML Form with post method. $_FILES: This SuperGlobal Variable holds the information of uploaded files via HTTP Post method. "; print_r($_FILES['picture']); echo ""; } /** This will print details of the File with name picture uploaded via a form with method='post and with enctype='multipart/form-data' Details includes Name of file, Type of File, temporary file location, error code(if any error occurred while uploading the file) and size of file in Bytes. Eg. Array ( [picture] => Array ( [0] => Array ( [name] => 400.png [type] => image/png [tmp_name] => /tmp/php5Wx0aJ [error] => 0 [size] => 15726 ) ) ) GoalKicker.com – PHP Notes for Professionals 29 */ ?> $_SERVER: This SuperGlobal Variable holds information about Scripts, HTTP Headers and Server Paths. "; print_r($_SERVER); echo ""; /** Will print the following details on my local XAMPP Array ( [MIBDIRS] => C:/xampp/php/extras/mibs [MYSQL_HOME] => \xampp\mysql\bin [OPENSSL_CONF] => C:/xampp/apache/bin/openssl.cnf [PHP_PEAR_SYSCONF_DIR] => \xampp\php [PHPRC] => \xampp\php [TMP] => \xampp\tmp [HTTP_HOST] => localhost [HTTP_CONNECTION] => keep-alive [HTTP_CACHE_CONTROL] => max-age=0 [HTTP_UPGRADE_INSECURE_REQUESTS] => 1 [HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*;q=0.8 [HTTP_ACCEPT_ENCODING] => gzip, deflate, sdch [HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.8 [PATH] => C:\xampp\php;C:\ProgramData\ComposerSetup\bin; [SystemRoot] => C:\Windows [COMSPEC] => C:\Windows\system32\cmd.exe [PATHEXT] => .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC [WINDIR] => C:\Windows [SERVER_SIGNATURE] => Apache/2.4.16 (Win32) OpenSSL/1.0.1p PHP/5.6.12 Server at localhost Port 80 [SERVER_SOFTWARE] => Apache/2.4.16 (Win32) OpenSSL/1.0.1p PHP/5.6.12 [SERVER_NAME] => localhost [SERVER_ADDR] => ::1 [SERVER_PORT] => 80 [REMOTE_ADDR] => ::1 [DOCUMENT_ROOT] => C:/xampp/htdocs [REQUEST_SCHEME] => http [CONTEXT_PREFIX] => [CONTEXT_DOCUMENT_ROOT] => C:/xampp/htdocs [SERVER_ADMIN] => postmaster@localhost [SCRIPT_FILENAME] => C:/xampp/htdocs/abcd.php [REMOTE_PORT] => 63822 [GATEWAY_INTERFACE] => CGI/1.1 [SERVER_PROTOCOL] => HTTP/1.1 [REQUEST_METHOD] => GET [QUERY_STRING] => [REQUEST_URI] => /abcd.php [SCRIPT_NAME] => /abcd.php [PHP_SELF] => /abcd.php [REQUEST_TIME_FLOAT] => 1469374173.88 [REQUEST_TIME] => 1469374173 ) */ ?> $_ENV: This SuperGlobal Variable Shell Environment Variable details under which the PHP is running. GoalKicker.com – PHP Notes for Professionals 30 $_COOKIE: This SuperGlobal Variable is used to retrieve Cookie value with given Key. "; echo "Value is: " . $_COOKIE[$cookie_name]; } /** Output Cookie 'data' is set! Value is: Foo Bar */ ?> $_SESSION: This SuperGlobal Variable is used to Set and Retrieve Session Value which is stored on Server. GoalKicker.com – PHP Notes for Professionals 31 Chapter 5: Outputting the Value of a Variable To build a dynamic and interactive PHP program, it is useful to output variables and their values. The PHP language allows for multiple methods of value output. This topic covers the standard methods of printing a value in PHP and where these methods can be used. Section 5.1: echo and print echo and print are language constructs, not functions. This means that they don't require parentheses around the argument like a function does (although one can always add parentheses around almost any PHP expression and thus echo("test") won't do any harm either). They output the string representation of a variable, constant, or expression. They can't be used to print arrays or objects. Assign the string Joel to the variable $name $name = "Joel"; Output the value of $name using echo & print echo $name; #> Joel print $name; #> Joel Parentheses are not required, but can be used echo($name); #> Joel print($name); #> Joel Using multiple parameters (only echo) echo $name, "Smith"; #> JoelSmith echo($name, " ", "Smith"); #> Joel Smith print, unlike echo, is an expression (it returns 1), and thus can be used in more places: print("hey") && print(" ") && print("you"); #> you11 The above is equivalent to: print ("hey" && (print (" " && print "you"))); #> you11 Shorthand notation for echo When outside of PHP tags, a shorthand notation for echo is available by default, using to end it. For example:

Note that there is no terminating ;. This works because the closing PHP tag acts as the terminator for the single GoalKicker.com – PHP Notes for Professionals 32 statement. So, it is conventional to omit the semicolon in this shorthand notation. Priority of print Although the print is language construction it has priority like operator. It places between = += -= *= **= /= .= %= &= and and operators and has left association. Example: echo '1' . print '2' + 3; //output 511 Same example with brackets: echo '1' . print ('2' + 3); //output 511 Differences between echo and print In short, there are two main differences: print only takes one parameter, while echo can have multiple parameters. print returns a value, so can be used as an expression. Section 5.2: Outputting a structured view of arrays and objects print_r() - Outputting Arrays and Objects for debugging print_r will output a human readable format of an array or object. You may have a variable that is an array or object. Trying to output it with an echo will throw the error: Notice: Array to string conversion. You can instead use the print_r function to dump a human readable format of this variable. You can pass true as the second parameter to return the content as a string. $myobject = new stdClass(); $myobject->myvalue = 'Hello World'; $myarray = [ "Hello", "World" ]; $mystring = "Hello World"; $myint = 42; // Using print_r we can view the data the array holds. print_r($myobject); print_r($myarray); print_r($mystring); print_r($myint); This outputs the following: stdClass Object ( [myvalue] => Hello World ) Array ( [0] => Hello [1] => World ) GoalKicker.com – PHP Notes for Professionals 33 Hello World 42 Further, the output from print_r can be captured as a string, rather than simply echoed. For instance, the following code will dump the formatted version of $myarray into a new variable: $formatted_array = print_r($myarray, true); Note that if you are viewing the output of PHP in a browser, and it is interpreted as HTML, then the line breaks will not be shown and the output will be much less legible unless you do something like echo '
' . print_r($myarray, true) . '
'; Opening the source code of a page will also format your variable in the same way without the use of the
 tag. 
Alternatively you can tell the browser that what you're outputting is plain text, and not HTML: 
header('Content-Type: text/plain; charset=utf-8'); 
print_r($myarray); 
var_dump() - Output human-readable debugging information about content of the argument(s) including its type and value 
The output is more detailed as compared to print_r because it also outputs the type of the variable along with its value and other information like object IDs, array sizes, string lengths, reference markers, etc. 
You can use var_dump to output a more detailed version for debugging. 
var_dump($myobject, $myarray, $mystring, $myint); 
Output is more detailed: 
object(stdClass)#12 (1) { 
["myvalue"]=> 
 string(11) "Hello World" 
} 
array(2) { 
 [0]=> 
 string(5) "Hello" 
 [1]=> 
 string(5) "World" 
} 
string(11) "Hello World" 
int(42) 
Note: If you are using xDebug in your development environment, the output of var_dump is limited / truncated by default. See the official documentation for more info about the options to change this. 
var_export() - Output valid PHP Code 
var_export() dumps a PHP parseable representation of the item.
GoalKicker.com – PHP Notes for Professionals 34 
You can pass true as the second parameter to return the contents into a variable. 
var_export($myarray); 
var_export($mystring); 
var_export($myint); 
Output is valid PHP code: 
array ( 
 0 => 'Hello', 
 1 => 'World', 
) 
'Hello World' 
42 
To put the content into a variable, you can do this: 
$array_export = var_export($myarray, true); 
$string_export = var_export($mystring, true); 
$int_export = var_export($myint, 1); // any `Truthy` value 
After that, you can output it like this: 
printf('$myarray = %s; %s', $array_export, PHP_EOL); 
printf('$mystring = %s; %s', $string_export, PHP_EOL); 
printf('$myint = %s; %s', $int_export, PHP_EOL); 
This will produce the following output: 
$myarray = array ( 
 0 => 'Hello', 
 1 => 'World', 
); 
$mystring = 'Hello World'; 
$myint = 42; 
Section 5.3: String concatenation with echo 
You can use concatenation to join strings "end to end" while outputting them (with echo or print for example). You can concatenate variables using a . (period/dot). 
// String variable 
$name = 'Joel'; 
// Concatenate multiple strings (3 in this example) into one and echo it once done. // 1. ↓ 2. ↓ 3. ↓ - Three Individual string items echo '

Hello ' . $name . ', Nice to see you.

'; // ↑ ↑ - Concatenation Operators #> "

Hello Joel, Nice to see you.

" Similar to concatenation, echo (when used without parentheses) can be used to combine strings and variables together (along with other arbitrary expressions) using a comma (,). $itemCount = 1; GoalKicker.com – PHP Notes for Professionals 35 echo 'You have ordered ', $itemCount, ' item', $itemCount === 1 ? '' : 's'; // ↑ ↑ ↑ - Note the commas #> "You have ordered 1 item" String concatenation vs passing multiple arguments to echo Passing multiple arguments to the echo command is more advantageous than string concatenation in some circumstances. The arguments are written to the output in the same order as they are passed in. echo "The total is: ", $x + $y; The problem with the concatenation is that the period . takes precedence in the expression. If concatenated, the above expression needs extra parentheses for the correct behavior. The precedence of the period affects ternary operators too. echo "The total is: " . ($x + $y); Section 5.4: printf vs sprintf printf will output a formatted string using placeholders sprintf will return the formatted string $name = 'Jeff'; // The `%s` tells PHP to expect a string // ↓ `%s` is replaced by ↓ printf("Hello %s, How's it going?", $name); #> Hello Jeff, How's it going? // Instead of outputting it directly, place it into a variable ($greeting) $greeting = sprintf("Hello %s, How's it going?", $name); echo $greeting; #> Hello Jeff, How's it going? It is also possible to format a number with these 2 functions. This can be used to format a decimal value used to represent money so that it always has 2 decimal digits. $money = 25.2; printf('%01.2f', $money); #> 25.20 The two functions vprintf and vsprintf operate as printf and sprintf, but accept a format string and an array of values, instead of individual variables. Section 5.5: Outputting large integers On 32-bits systems, integers larger than PHP_INT_MAX are automatically converted to float. Outputting these as integer values (i.e. non-scientific notation) can be done with printf, using the float representation, as illustrated below: foreach ([1, 2, 3, 4, 5, 6, 9, 12] as $p) { $i = pow(1024, $p); printf("pow(1024, %d) > (%7s) %20s %38.0F", $p, gettype($i), $i, $i); GoalKicker.com – PHP Notes for Professionals 36 echo " ", $i, "\n"; } // outputs: pow(1024, 1) integer 1024 1024 1024 pow(1024, 2) integer 1048576 1048576 1048576 pow(1024, 3) integer 1073741824 1073741824 1073741824 pow(1024, 4) double 1099511627776 1099511627776 1099511627776 pow(1024, 5) double 1.1258999068426E+15 1125899906842624 1.1258999068426E+15 pow(1024, 6) double 1.1529215046068E+18 1152921504606846976 1.1529215046068E+18 pow(1024, 9) double 1.2379400392854E+27 1237940039285380274899124224 1.2379400392854E+27 pow(1024, 12) double 1.3292279957849E+36 1329227995784915872903807060280344576 1.3292279957849E+36 Note: watch out for float precision, which is not infinite! While this looks nice, in this contrived example the numbers can all be represented as a binary number since they are all powers of 1024 (and thus 2). See for example: $n = pow(10, 27); printf("%s %.0F\n", $n, $n); // 1.0E+27 1000000000000000013287555072 Section 5.6: Output a Multidimensional Array with index and value and print into the table Array ( [0] => Array ( [id] => 13 [category_id] => 7 [name] => Leaving Of Liverpool [description] => Leaving Of Liverpool [price] => 1.00 [virtual] => 1 [active] => 1 [sort_order] => 13 [created] => 2007-06-24 14:08:03 [modified] => 2007-06-24 14:08:03 [image] => NONE ) [1] => Array ( [id] => 16 [category_id] => 7 [name] => Yellow Submarine [description] => Yellow Submarine [price] => 1.00 [virtual] => 1 [active] => 1 [sort_order] => 16 [created] => 2007-06-24 14:10:02 [modified] => 2007-06-24 14:10:02 GoalKicker.com – PHP Notes for Professionals 37 [image] => NONE ) ) Output Multidimensional Array with index and value in table $value) { foreach ($value as $k => $v) { echo ""; echo ""; // Get index. echo ""; // Get value. echo ""; } } ?>
$k$v
GoalKicker.com – PHP Notes for Professionals 38 Chapter 6: Constants Section 6.1: Defining constants Constants are created using the const statement or the define function. The convention is to use UPPERCASE letters for constant names. Define constant using explicit values const PI = 3.14; // float define("EARTH_IS_FLAT", false); // boolean const "UNKNOWN" = null; // null define("APP_ENV", "dev"); // string const MAX_SESSION_TIME = 60 * 60; // integer, using (scalar) expressions is ok const APP_LANGUAGES = ["de", "en"]; // arrays define("BETTER_APP_LANGUAGES", ["lu", "de"]); // arrays Define constant using another constant if you have one constant you can define another one based on it: const TAU = PI * 2; define("EARTH_IS_ROUND", !EARTH_IS_FLAT); define("MORE_UNKNOWN", UNKNOWN); define("APP_ENV_UPPERCASE", strtoupper(APP_ENV)); // string manipulation is ok too // the above example (a function call) does not work with const: // const TIME = time(); # fails with a fatal error! Not a constant scalar expression define("MAX_SESSION_TIME_IN_MINUTES", MAX_SESSION_TIME / 60); const APP_FUTURE_LANGUAGES = [-1 => "es"] + APP_LANGUAGES; // array manipulations define("APP_BETTER_FUTURE_LANGUAGES", array_merge(["fr"], APP_BETTER_LANGUAGES)); Reserved constants Some constant names are reserved by PHP and cannot be redefined. All these examples will fail: define("true", false); // internal constant define("false", true); // internal constant define("CURLOPT_AUTOREFERER", "something"); // will fail if curl extension is loaded And a Notice will be issued: Constant ... already defined in ... Conditional defines If you have several files where you may define the same variable (for example, your main config then your local config) then following syntax may help avoiding conflicts: defined("PI") || define("PI", 3.1415); // "define PI if it's not yet defined" const vs define define is a runtime expression while const a compile time one. GoalKicker.com – PHP Notes for Professionals 39 Thus define allows for dynamic values (i.e. function calls, variables etc.) and even dynamic names and conditional definition. It however is always defining relative to the root namespace. const is static (as in allows only operations with other constants, scalars or arrays, and only a restricted set of them, the so called constant scalar expressions, i.e. arithmetic, logical and comparison operators as well as array dereferencing), but are automatically namespace prefixed with the currently active namespace. const only supports other constants and scalars as values, and no operations. Section 6.2: Class Constants Constants can be defined inside classes using a const keyword. class Foo { const BAR_TYPE = "bar"; // reference from inside the class using self:: public function myMethod() { return self::BAR_TYPE; } } // reference from outside the class using :: echo Foo::BAR_TYPE; This is useful to store types of items. log("Info"); // Using default value $logger->log("Warning", $logger::LEVEL_WARNING); // Using var $logger->log("Error", Logger::LEVEL_ERROR); // using class Section 6.3: Checking if constant is defined Simple check To check if constant is defined use the defined function. Note that this function doesn't care about constant's value, it only cares if the constant exists or not. Even if the value of the constant is null or false the function will still return true. 'hello', 'WORLD' => 'world', ) */ It's sometimes useful for debugging GoalKicker.com – PHP Notes for Professionals 41 Section 6.4: Using constants To use the constant simply use its name: if (EARTH_IS_FLAT) { print "Earth is flat"; } print APP_ENV_UPPERCASE; or if you don't know the name of the constant in advance, use the constant function: // this code is equivalent to the above code $const1 = "EARTH_IS_FLAT"; $const2 = "APP_ENV_UPPERCASE"; if (constant($const1)) { print "Earth is flat"; } print constant($const2); Section 6.5: Constant arrays Arrays can be used as plain constants and class constants from version PHP 5.6 onwards: Class constant example class Answer { const C = [2,4]; } print Answer::C[1] . Answer::C[0]; // 42 Plain constant example const ANSWER = [2,4]; print ANSWER[1] . ANSWER[0]; // 42 Also from version PHP 7.0 this functionality was ported to the define function for plain constants. define('VALUES', [2, 3]); define('MY_ARRAY', [ 1, VALUES, ]); print MY_ARRAY[1][1]; // 3 GoalKicker.com – PHP Notes for Professionals 42 Chapter 7: Magic Constants Section 7.1: Dierence between __FUNCTION__ and __METHOD__ __FUNCTION__ returns only the name of the function whereas __METHOD__ returns the name of the class along with the name of the function: doit(); // Outputs: doit $obj->doitagain(); // Outputs: trick::doitagain Section 7.2: Dierence between __CLASS__, get_class() and get_called_class() __CLASS__ magic constant returns the same result as get_class() function called without parameters and they both return the name of the class where it was defined (i.e. where you wrote the function call/constant name ). In contrast, get_class($this) and get_called_class() functions call, will both return the name of the actual class which was instantiated: say(); // Output: // __CLASS__ value: Definition_Class // get_called_class() value: Actual_Class // get_class($this) value: Actual_Class GoalKicker.com – PHP Notes for Professionals 43 // get_class() value: Definition_Class Section 7.3: File & Directory Constants Current file You can get the name of the current PHP file (with the absolute path) using the __FILE__ magic constant. This is most often used as a logging/debugging technique. echo "We are in the file:" , __FILE__ , "\n"; Current directory To get the absolute path to the directory where the current file is located use the __DIR__ magic constant. echo "Our script is located in the:" , __DIR__ , "\n"; To get the absolute path to the directory where the current file is located, use dirname(__FILE__). echo "Our script is located in the:" , dirname(__FILE__) , "\n"; Getting current directory is often used by PHP frameworks to set a base directory: // index.php of the framework define(BASEDIR, __DIR__); // using magic constant to define normal constant // somefile.php looks for views: $view = 'page'; $viewFile = BASEDIR . '/views/' . $view; Separators Windows system perfectly understands the / in paths so the DIRECTORY_SEPARATOR is used mainly when parsing paths. Besides magic constants PHP also adds some fixed constants for working with paths: DIRECTORY_SEPARATOR constant for separating directories in a path. Takes value / on *nix, and \ on Windows. The example with views can be rewritten with: $view = 'page'; $viewFile = BASEDIR . DIRECTORY_SEPARATOR .'views' . DIRECTORY_SEPARATOR . $view; Rarely used PATH_SEPARATOR constant for separating paths in the $PATH environment variable. It is ; on Windows, : otherwise GoalKicker.com – PHP Notes for Professionals 44 Chapter 8: Comments Section 8.1: Single Line Comments The single line comment begins with "//" or "#". When encountered, all text to the right will be ignored by the PHP interpreter. // This is a comment # This is also a comment echo "Hello World!"; // This is also a comment, beginning where we see "//" Section 8.2: Multi Line Comments The multi-line comment can be used to comment out large blocks of code. It begins with /* and ends with */. /* This is a multi-line comment. It spans multiple lines. This is still part of the comment. */ GoalKicker.com – PHP Notes for Professionals 45 Chapter 9: Types Section 9.1: Type Comparison There are two types of comparison: loose comparison with == and strict comparison with ===. Strict comparison ensures both the type and value of both sides of the operator are the same. // Loose comparisons var_dump(1 == 1); // true var_dump(1 == "1"); // true var_dump(1 == true); // true var_dump(0 == false); // true // Strict comparisons var_dump(1 === 1); // true var_dump(1 === "1"); // false var_dump(1 === true); // false var_dump(0 === false); // false // Notable exception: NAN — it never is equal to anything var_dump(NAN == NAN); // false var_dump(NAN === NAN); // false You can also use strong comparison to check if type and value don't match using !==. A typical example where the == operator is not enough, are functions that can return different types, like strpos, which returns false if the searchword is not found, and the match position (int) otherwise: if(strpos('text', 'searchword') == false) // strpos returns false, so == comparison works as expected here, BUT: if(strpos('text bla', 'text') == false) // strpos returns 0 (found match at position 0) and 0==false is true. // This is probably not what you expect! if(strpos('text','text') === false) // strpos returns 0, and 0===false is false, so this works as expected. Section 9.2: Boolean Boolean is a type, having two values, denoted as true or false. This code sets the value of $foo as true and $bar as false: $foo = true; $bar = false; true and false are not case sensitive, so TRUE and FALSE can be used as well, even FaLsE is possible. Using lower case is most common and recommended in most code style guides, e.g. PSR-2. Booleans can be used in if statements like this: if ($foo) { //same as evaluating if($foo == true) echo "true"; } Due to the fact that PHP is weakly typed, if $foo above is other than true or false, it's automatically coerced to a boolean value. GoalKicker.com – PHP Notes for Professionals 46 The following values result in false: a zero value: 0 (integer), 0.0 (float), or '0' (string) an empty string '' or array [] null (the content of an unset variable, or assigned to a variable) Any other value results in true. To avoid this loose comparison, you can enforce strong comparison using ===, which compares value and type. See Type Comparison for details. To convert a type into boolean, you can use the (bool) or (boolean) cast before the type. var_dump((bool) "1"); //evaluates to true or call the boolval function: var_dump( boolval("1") ); //evaluates to true Boolean conversion to a string (note that false yields an empty string): var_dump( (string) true ); // string(1) "1" var_dump( (string) false ); // string(0) "" Boolean conversion to an integer: var_dump( (int) true ); // int(1) var_dump( (int) false ); // int(0) Note that the opposite is also possible: var_dump((bool) ""); // bool(false) var_dump((bool) 1); // bool(true) Also all non-zero will return true: var_dump((bool) -2); // bool(true) var_dump((bool) "foo"); // bool(true) var_dump((bool) 2.3e5); // bool(true) var_dump((bool) array(12)); // bool(true) var_dump((bool) array()); // bool(false) var_dump((bool) "false"); // bool(true) Section 9.3: Float $float = 0.123; For historical reasons "double" is returned by gettype() in case of a float, and not simply "float" Floats are floating point numbers, which allow more output precision than plain integers. Floats and integers can be used together due to PHP's loose casting of variable types: GoalKicker.com – PHP Notes for Professionals 47 $sum = 3 + 0.14; echo $sum; // 3.14 php does not show float as float number like other languages, for example: $var = 1; echo ((float) $var); //returns 1 not 1.0 Warning Floating point precision (From the PHP manual page) Floating point numbers have limited precision. Although it depends on the system, PHP typically give a maximum relative error due to rounding in the order of 1.11e-16. Non elementary arithmetic operations may give larger errors, and error propagation must be considered when several operations are compounded. Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2 (binary), which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118.... So never trust floating number results to the last digit, and do not compare floating point numbers directly for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available. Section 9.4: Strings A string in PHP is a series of single-byte characters (i.e. there is no native Unicode support) that can be specified in four ways: Single Quoted Displays things almost completely "as is". Variables and most escape sequences will not be interpreted. The exception is that to display a literal single quote, one can escape it with a back slash ', and to display a back slash, one can escape it with another backslash \ $my_string = 'Nothing is parsed, except an escap\'d apostrophe or backslash. $foo\n'; var_dump($my_string); /* string(68) "Nothing is parsed, except an escap'd apostrophe or backslash. $foo\n" */ Double Quoted GoalKicker.com – PHP Notes for Professionals 48 Unlike a single-quoted string, simple variable names and escape sequences in the strings will be evaluated. Curly braces (as in the last example) can be used to isolate complex variable names. $variable1 = "Testing!"; $variable2 = [ "Testing?", [ "Failure", "Success" ] ]; $my_string = "Variables and escape characters are parsed:\n\n"; $my_string .= "$variable1\n\n$variable2[0]\n\n"; $my_string .= "There are limits: $variable2[1][0]"; $my_string .= "But we can get around them by wrapping the whole variable in braces: {$variable2[1][1]}"; var_dump($my_string); /* string(98) "Variables and escape characters are parsed: Testing! Testing? There are limits: Array[0]" But we can get around them by wrapping the whole variable in braces: Success */ Heredoc In a heredoc string, variable names and escape sequences are parsed in a similar manner to double-quoted strings, though braces are not available for complex variable names. The start of the string is delimited by << 'y']; var_dump((object) $array); // object(stdClass)#1 (1) { ["x"]=> string(1) "y" } $object = new stdClass(); $object->x = 'y'; var_dump((array) $object); // array(1) { ["x"]=> string(1) "y" } $string = "asdf"; var_dump((unset)$string); // NULL But be careful: not all type casts work as one might expect: // below 3 statements hold for 32-bits systems (PHP_INT_MAX=2147483647) // an integer value bigger than PHP_INT_MAX is automatically converted to float: var_dump( 999888777666 ); // float(999888777666) // forcing to (int) gives overflow: var_dump((int) 999888777666 ); // int(-838602302) // but in a string it just returns PHP_INT_MAX var_dump((int) "999888777666"); // int(2147483647) var_dump((bool) []); // bool(false) (empty array) var_dump((bool) [false]); // bool(true) (non-empty array) Section 9.8: Type Juggling PHP is a weakly-typed language. It does not require explicit declaration of data types. The context in which the variable is used determines its data type; conversion is done automatically: $a = "2"; // string GoalKicker.com – PHP Notes for Professionals 51 $a = $a + 2; // integer (4) $a = $a + 0.5; // float (4.5) $a = 1 + "2 oranges"; // integer (3) Section 9.9: Null PHP represents "no value" with the null keyword. It's somewhat similar to the null pointer in C-language and to the NULL value in SQL. Setting the variable to null: $nullvar = null; // directly function doSomething() {} // this function does not return anything $nullvar = doSomething(); // so the null is assigned to $nullvar Checking if the variable was set to null: if (is_null($nullvar)) { /* variable is null */ } if ($nullvar === null) { /* variable is null */ } Null vs undefined variable If the variable was not defined or was unset then any tests against the null will be successful but they will also generate a Notice: Undefined variable: nullvar: $nullvar = null; unset($nullvar); if ($nullvar === null) { /* true but also a Notice is printed */ } if (is_null($nullvar)) { /* true but also a Notice is printed */ } Therefore undefined values must be checked with isset: if (!isset($nullvar)) { /* variable is null or is not even defined */ } Section 9.10: Integers Integers in PHP can be natively specified in base 2 (binary), base 8 (octal), base 10 (decimal), or base 16 (hexadecimal.) $my_decimal = 42; $my_binary = 0b101010; $my_octal = 052; $my_hexadecimal = 0x2a; echo ($my_binary + $my_octal) / 2; // Output is always in decimal: 42 Integers are 32 or 64 bits long, depending on the platform. The constant PHP_INT_SIZE holds integer size in bytes. PHP_INT_MAX and (since PHP 7.0) PHP_INT_MIN are also available. printf("Integers are %d bits long" . PHP_EOL, PHP_INT_SIZE * 8); printf("They go up to %d" . PHP_EOL, PHP_INT_MAX); Integer values are automatically created as needed from floats, booleans, and strings. If an explicit typecast is GoalKicker.com – PHP Notes for Professionals 52 needed, it can be done with the (int) or (integer) cast: $my_numeric_string = "123"; var_dump($my_numeric_string); // Output: string(3) "123" $my_integer = (int)$my_numeric_string; var_dump($my_integer); // Output: int(123) Integer overflow will be handled by conversion to a float: $too_big_integer = PHP_INT_MAX + 7; var_dump($too_big_integer); // Output: float(9.2233720368548E+18) There is no integer division operator in PHP, but it can be simulated using an implicit cast, which always 'rounds' by just discarding the float-part. As of PHP version 7, an integer division function was added. $not_an_integer = 25 / 4; var_dump($not_an_integer); // Output: float(6.25) var_dump((int) (25 / 4)); // (see note below) // Output: int(6) var_dump(intdiv(25 / 4)); // as of PHP7 // Output: int(6) (Note that the extra parentheses around (25 / 4) are needed because the (int) cast has higher precedence than the division) GoalKicker.com – PHP Notes for Professionals 53 Chapter 10: Operators An operator is something that takes one or more values (or expressions, in programming jargon) and yields another value (so that the construction itself becomes an expression). Operators can be grouped according to the number of values they take. Section 10.1: Null Coalescing Operator (??) Null coalescing is a new operator introduced in PHP 7. This operator returns its first operand if it is set and not NULL. Otherwise it will return its second operand. The following example: $name = $_POST['name'] ?? 'nobody'; is equivalent to both: if (isset($_POST['name'])) { $name = $_POST['name']; } else { $name = 'nobody'; } and: $name = isset($_POST['name']) ? $_POST['name'] : 'nobody'; This operator can also be chained (with right-associative semantics): $name = $_GET['name'] ?? $_POST['name'] ?? 'nobody'; which is an equivalent to: if (isset($_GET['name'])) { $name = $_GET['name']; } elseif (isset($_POST['name'])) { $name = $_POST['name']; } else { $name = 'nobody'; } Note: When using coalescing operator on string concatenation don't forget to use parentheses () $firstName = "John"; $lastName = "Doe"; echo $firstName ?? "Unknown" . " " . $lastName ?? ""; This will output John only, and if its $firstName is null and $lastName is Doe it will output Unknown Doe. In order to output John Doe, we must use parentheses like this. $firstName = "John"; $lastName = "Doe"; GoalKicker.com – PHP Notes for Professionals 54 echo ($firstName ?? "Unknown") . " " . ($lastName ?? ""); This will output John Doe instead of John only. Section 10.2: Spaceship Operator (<=>) PHP 7 introduces a new kind of operator, which can be used to compare expressions. This operator will return -1, 0 or 1 if the first expression is less than, equal to, or greater than the second expression. // Integers print (1 <=> 1); // 0 print (1 <=> 2); // -1 print (2 <=> 1); // 1 // Floats print (1.5 <=> 1.5); // 0 print (1.5 <=> 2.5); // -1 print (2.5 <=> 1.5); // 1 // Strings print ("a" <=> "a"); // 0 print ("a" <=> "b"); // -1 print ("b" <=> "a"); // 1 Objects are not comparable, and so doing so will result in undefined behaviour. This operator is particularly useful when writing a user-defined comparison function using usort, uasort, or uksort. Given an array of objects to be sorted by their weight property, for example, an anonymous function can use <=> to return the value expected by the sorting functions. usort($list, function($a, $b) { return $a->weight <=> $b->weight; }); In PHP 5 this would have required a rather more elaborate expression. usort($list, function($a, $b) { return $a->weight < $b->weight ? -1 : ($a->weight == $b->weight ? 0 : 1); }); Section 10.3: Execution Operator (``) The PHP execution operator consists of backticks (``) and is used to run shell commands. The output of the command will be returned, and may, therefore, be stored in a variable. // List files $output = `ls`; echo "
$output
"; Note that the execute operator and shell_exec() will give the same result. Section 10.4: Incrementing (++) and Decrementing Operators (--) Variables can be incremented or decremented by 1 with ++ or --, respectively. They can either precede or succeed variables and slightly vary semantically, as shown below. GoalKicker.com – PHP Notes for Professionals 55 $i = 1; echo $i; // Prints 1 // Pre-increment operator increments $i by one, then returns $i echo ++$i; // Prints 2 // Pre-decrement operator decrements $i by one, then returns $i echo --$i; // Prints 1 // Post-increment operator returns $i, then increments $i by one echo $i++; // Prints 1 (but $i value is now 2) // Post-decrement operator returns $i, then decrements $i by one echo $i--; // Prints 2 (but $i value is now 1) More information about incrementing and decrementing operators can be found in the official documentation. Section 10.5: Ternary Operator (?:) The ternary operator can be thought of as an inline if statement. It consists of three parts. The operator, and two outcomes. The syntax is as follows: $value = ? : If the operator is evaluated as true, the value in the first block will be returned (), else the value in the second block will be returned (). Since we are setting $value to the result of our ternary operator it will store the returned value. Example: $action = empty($_POST['action']) ? 'default' : $_POST['action']; $action would contain the string 'default' if empty($_POST['action']) evaluates to true. Otherwise it would contain the value of $_POST['action']. The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1evaluates to true, and expr3 if expr1 evaluates to false. It is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise. ?: is often referred to as Elvis operator. This behaves like the Null Coalescing operator ??, except that ?? requires the left operand to be exactly null while ?: tries to resolve the left operand into a boolean and check if it resolves to boolean false. Example: function setWidth(int $width = 0){ $_SESSION["width"] = $width ?: getDefaultWidth(); } In this example, setWidth accepts a width parameter, or default 0, to change the width session value. If $width is 0 (if $width is not provided), which will resolve to boolean false, the value of getDefaultWidth() is used instead. The getDefaultWidth() function will not be called if $width did not resolve to boolean false. Refer to Types for more information about conversion of variables to boolean. GoalKicker.com – PHP Notes for Professionals 56 Section 10.6: Logical Operators (&&/AND and ||/OR) In PHP, there are two versions of logical AND and OR operators. Operator True if $a and $b Both $a and $b are true $a && $b Both $a and $b are true $a or $b Either $a or $b is true $a || $b Either $a or $b is true Note that the && and || opererators have higher precedence than and and or. See table below: Evaluation Result of $e Evaluated as $e = false || true True $e = (false || true) $e = false or true False ($e = false) or true Because of this it's safer to use && and || instead of and and or. Section 10.7: String Operators (. and .=) There are only two string operators: Concatenation of two strings (dot): $a = "a"; $b = "b"; $c = $a . $b; // $c => "ab" Concatenating assignment (dot=): $a = "a"; $a .= "b"; // $a => "ab" Section 10.8: Object and Class Operators Members of objects or classes can be accessed using the object operator (->) and the class operator (::). class MyClass { public $a = 1; public static $b = 2; const C = 3; public function d() { return 4; } public static function e() { return 5; } } $object = new MyClass(); var_dump($object->a); // int(1) var_dump($object::$b); // int(2) var_dump($object::C); // int(3) var_dump(MyClass::$b); // int(2) var_dump(MyClass::C); // int(3) var_dump($object->d()); // int(4) var_dump($object::d()); // int(4) var_dump(MyClass::e()); // int(5) $classname = "MyClass"; GoalKicker.com – PHP Notes for Professionals 57 var_dump($classname::e()); // also works! int(5) Note that after the object operator, the $ should not be written ($object->a instead of $object->$a). For the class operator, this is not the case and the $ is necessary. For a constant defined in the class, the $ is never used. Also note that var_dump(MyClass::d()); is only allowed if the function d() does not reference the object: class MyClass { private $a = 1; public function d() { return $this->a; } } $object = new MyClass(); var_dump(MyClass::d()); // Error! This causes a 'PHP Fatal error: Uncaught Error: Using $this when not in object context' These operators have left associativity, which can be used for 'chaining': class MyClass { private $a = 1; public function add(int $a) { $this->a += $a; return $this; } public function get() { return $this->a; } } $object = new MyClass(); var_dump($object->add(4)->get()); // int(5) These operators have the highest precedence (they are not even mentioned in the manual), even higher that clone. Thus: class MyClass { private $a = 0; public function add(int $a) { $this->a += $a; return $this; } public function get() { return $this->a; } } $o1 = new MyClass(); $o2 = clone $o1->add(2); var_dump($o1->get()); // int(2) var_dump($o2->get()); // int(2) The value of $o1 is added to before the object is cloned! Note that using parentheses to influence precedence did not work in PHP version 5 and older (it does in PHP 7): GoalKicker.com – PHP Notes for Professionals 58 // using the class MyClass from the previous code $o1 = new MyClass(); $o2 = (clone $o1)->add(2); // Error in PHP 5 and before, fine in PHP 7 var_dump($o1->get()); // int(0) in PHP 7 var_dump($o2->get()); // int(2) in PHP 7 Section 10.9: Combined Assignment (+= etc) The combined assignment operators are a shortcut for an operation on some variable and subsequently assigning this new value to that variable. Arithmetic: $a = 1; // basic assignment $a += 2; // read as '$a = $a + 2'; $a now is (1 + 2) => 3 $a -= 1; // $a now is (3 - 1) => 2 $a *= 2; // $a now is (2 * 2) => 4 $a /= 2; // $a now is (16 / 2) => 8 $a %= 5; // $a now is (8 % 5) => 3 (modulus or remainder) // array + $arrOne = array(1); $arrTwo = array(2); $arrOne += $arrTwo; Processing Multiple Arrays Together $a **= 2; // $a now is (4 ** 2) => 16 (4 raised to the power of 2) Combined concatenation and assignment of a string: $a = "a"; $a .= "b"; // $a => "ab" Combined binary bitwise assignment operators: $a = 0b00101010; // $a now is 42 $a &= 0b00001111; // $a now is (00101010 & 00001111) => 00001010 (bitwise and) $a |= 0b00100010; // $a now is (00001010 | 00100010) => 00101010 (bitwise or) $a ^= 0b10000010; // $a now is (00101010 ^ 10000010) => 10101000 (bitwise xor) $a >>= 3; // $a now is (10101000 >> 3) => 00010101 (shift right by 3) $a <<= 1; // $a now is (00010101 << 1) => 00101010 (shift left by 1) Section 10.10: Altering operator precedence (with parentheses) The order in which operators are evaluated is determined by the operator precedence (see also the Remarks section). In $a = 2 * 3 + 4; $a gets a value of 10 because 2 * 3 is evaluated first (multiplication has a higher precedence than addition) yielding a sub-result of 6 + 4, which equals to 10. GoalKicker.com – PHP Notes for Professionals 59 The precedence can be altered using parentheses: in $a = 2 * (3 + 4); $a gets a value of 14 because (3 + 4) is evaluated first. Section 10.11: Basic Assignment (=) $a = "some string"; results in $a having the value some string. The result of an assignment expression is the value being assigned. Note that a single equal sign = is NOT for comparison! $a = 3; $b = ($a = 5); does the following: 1. Line 1 assigns 3 to $a. 2. Line 2 assigns 5 to $a. This expression yields value 5 as well. 3. Line 2 then assigns the result of the expression in parentheses (5) to $b. Thus: both $a and $b now have value 5. Section 10.12: Association Left association If the preceedence of two operators is equal, the associativity determines the grouping (see also the Remarks section): $a = 5 * 3 % 2; // $a now is (5 * 3) % 2 => (15 % 2) => 1 * and % have equal precedence and left associativity. Because the multiplication occurs first (left), it is grouped. $a = 5 % 3 * 2; // $a now is (5 % 3) * 2 => (2 * 2) => 4 Now, the modulus operator occurs first (left) and is thus grouped. Right association $a = 1; $b = 1; $a = $b += 1; Both $a and $b now have value 2 because $b += 1 is grouped and then the result ($b is 2) is assigned to $a. Section 10.13: Comparison Operators Equality For basic equality testing, the equal operator == is used. For more comprehensive checks, use the identical operator ===. GoalKicker.com – PHP Notes for Professionals 60 The identical operator works the same as the equal operator, requiring its operands have the same value, but also requires them to have the same data type. For example, the sample below will display 'a and b are equal', but not 'a and b are identical'. $a = 4; $b = '4'; if ($a == $b) { echo 'a and b are equal'; // this will be printed } if ($a === $b) { echo 'a and b are identical'; // this won't be printed } When using the equal operator, numeric strings are cast to integers. Comparison of objects === compares two objects by checking if they are exactly the same instance. This means that new stdClass() === new stdClass() resolves to false, even if they are created in the same way (and have the exactly same values). == compares two objects by recursively checking if they are equal (deep equals). That means, for $a == $b, if $a and $b are: 1. of the same class 2. have the same properties set, including dynamic properties 3. for each property $property set, $a->property == $b->property is true (hence recursively checked). Other commonly used operators They include: 1. Greater Than (>) 2. Lesser Than (<) 3. Greater Than Or Equal To (>=) 4. Lesser Than Or Equal To (<=) 5. Not Equal To (!=) 6. Not Identically Equal To (!==) 1. Greater Than: $a > $b, returns true if $a's value is greater than of $b, otherwise returns false. Example: var_dump(5 > 2); // prints bool(true) var_dump(2 > 7); // prints bool(false) 2. Lesser Than: $a < $b, returns true if $a's value is smaller that of $b, otherwise returns false. Example: var_dump(5 < 2); // prints bool(false) var_dump(1 < 10); // prints bool(true) 3. Greater Than Or Equal To: $a >= $b, returns true if $a's value is either greater than of $b or equal to $b, otherwise returns false. Example: GoalKicker.com – PHP Notes for Professionals 61 var_dump(2 >= 2); // prints bool(true) var_dump(6 >= 1); // prints bool(true) var_dump(1 >= 7); // prints bool(false) 4. Smaller Than Or Equal To: $a <= $b, returns true if $a's value is either smaller than of $b or equal to $b, otherwise returns false. Example: var_dump(5 <= 5); // prints bool(true) var_dump(5 <= 8); // prints bool(true) var_dump(9 <= 1); // prints bool(false) 5/6. Not Equal/Identical To: To rehash the earlier example on equality, the sample below will display 'a and b are not identical', but not 'a and b are not equal'. $a = 4; $b = '4'; if ($a != $b) { echo 'a and b are not equal'; // this won't be printed } if ($a !== $b) { echo 'a and b are not identical'; // this will be printed } Section 10.14: Bitwise Operators Prefix bitwise operators Bitwise operators are like logical operators but executed per bit rather than per boolean value. // bitwise NOT ~: sets all unset bits and unsets all set bits printf("%'06b", ~0b110110); // 001001 Bitmask-bitmask operators Bitwise AND &: a bit is set only if it is set in both operands printf("%'06b", 0b110101 & 0b011001); // 010001 Bitwise OR |: a bit is set if it is set in either or both operands printf("%'06b", 0b110101 | 0b011001); // 111101 Bitwise XOR ^: a bit is set if it is set in one operand and not set in another operand, i.e. only if that bit is in different state in the two operands printf("%'06b", 0b110101 ^ 0b011001); // 101100 Example uses of bitmasks These operators can be used to manipulate bitmasks. For example: file_put_contents("file.log", LOCK_EX | FILE_APPEND); Here, the | operator is used to combine the two bitmasks. Although + has the same effect, | emphasizes that you GoalKicker.com – PHP Notes for Professionals 62 are combining bitmasks, not adding two normal scalar integers. class Foo{ const OPTION_A = 1; const OPTION_B = 2; const OPTION_C = 4; const OPTION_A = 8; private $options = self::OPTION_A | self::OPTION_C; public function toggleOption(int $option){ $this->options ^= $option; } public function enable(int $option){ $this->options |= $option; // enable $option regardless of its original state } public function disable(int $option){ $this->options &= ~$option; // disable $option regardless of its original state, // without affecting other bits } /** returns whether at least one of the options is enabled */ public function isOneEnabled(int $options) : bool{ return $this->options & $option !== 0; // Use !== rather than >, because // if $options is about a high bit, we may be handling a negative integer } /** returns whether all of the options are enabled */ public function areAllEnabled(int $options) : bool{ return ($this->options & $options) === $options; // note the parentheses; beware the operator precedence } } This example (assuming $option always only contain one bit) uses: the ^ operator to conveniently toggle bitmasks. the | operator to set a bit neglecting its original state or other bits the ~ operator to convert an integer with only one bit set into an integer with only one bit not set the & operator to unset a bit, using these properties of &: Since &= with a set bit will not do anything ((1 & 1) === 1, (0 & 1) === 0), doing &= with an integer with only one bit not set will only unset that bit, not affecting other bits. &= with an unset bit will unset that bit ((1 & 0) === 0, (0 & 0) === 0) Using the & operator with another bitmask will filter away all other bits not set in that bitmask. If the output has any bits set, it means that any one of the options are enabled. If the output has all bits of the bitmask set, it means that all of the options in the bitmask are enabled. Bear in mind that these comparison operators: (< > <= >= == === != !== <> <=>) have higher precedence than these bitmask-bitmask operators: (| ^ &). As bitwise results are often compared using these comparison operators, this is a common pitfall to be aware of. Bit-shifting operators Bitwise left shift <<: shift all bits to the left (more significant) by the given number of steps and discard the bits exceeding the int size GoalKicker.com – PHP Notes for Professionals 63 << $x is equivalent to unsetting the highest $x bits and multiplying by the $xth power of 2 printf("%'08b", 0b00001011<< 2); // 00101100 assert(PHP_INT_SIZE === 4); // a 32-bit system printf("%x, %x", 0x5FFFFFFF << 2, 0x1FFFFFFF << 4); // 7FFFFFFC, FFFFFFFF Bitwise right shift >>: discard the lowest shift and shift the remaining bits to the right (less significant) >> $x is equivalent to dividing by the $xth power of 2 and discard the non-integer part printf("%x", 0xFFFFFFFF >> 3); // 1FFFFFFF Example uses of bit shifting: Fast division by 16 (better performance than /= 16) $x >>= 4; On 32-bit systems, this discards all bits in the integer, setting the value to 0. On 64-bit systems, this unsets the most significant 32 bits and keep the least $x = $x << 32 >> 32; significant 32 bits, equivalent to $x & 0xFFFFFFFF Note: In this example, printf("%'06b") is used. It outputs the value in 6 binary digits. Section 10.15: instanceof (type operator) For checking whether some object is of a certain class, the (binary) instanceof operator can be used since PHP version 5. The first (left) parameter is the object to test. If this variable is not an object, instanceof always returns false. If a constant expression is used, an error is thrown. The second (right) parameter is the class to compare with. The class can be provided as the class name itself, a string variable containing the class name (not a string constant!) or an object of that class. class MyClass { } $o1 = new MyClass(); $o2 = new MyClass(); $name = 'MyClass'; // in the cases below, $a gets boolean value true $a = $o1 instanceof MyClass; $a = $o1 instanceof $name; $a = $o1 instanceof $o2; // counter examples: $b = 'b'; $a = $o1 instanceof 'MyClass'; // parse error: constant not allowed $a = false instanceof MyClass; // fatal error: constant not allowed $a = $b instanceof MyClass; // false ($b is not an object) GoalKicker.com – PHP Notes for Professionals 64 instanceof can also be used to check whether an object is of some class which extends another class or implements some interface: interface MyInterface { } class MySuperClass implements MyInterface { } class MySubClass extends MySuperClass { } $o = new MySubClass(); // in the cases below, $a gets boolean value true $a = $o instanceof MySubClass; $a = $o instanceof MySuperClass; $a = $o instanceof MyInterface; To check whether an object is not of some class, the not operator (!) can be used: class MyClass { } class OtherClass { } $o = new MyClass(); $a = !$o instanceof OtherClass; // true Note that parentheses around $o instanceof MyClass are not needed because instanceof has higher precedence than !, although it may make the code better readable with parentheses. Caveats If a class does not exist, the registered autoload functions are called to try to define the class (this is a topic outside the scope of this part of the Documentation!). In PHP versions before 5.1.0, the instanceof operator would also trigger these calls, thus actually defining the class (and if the class could not be defined, a fatal error would occur). To avoid this, use a string: // only PHP versions before 5.1.0! class MyClass { } $o = new MyClass(); $a = $o instanceof OtherClass; // OtherClass is not defined! // if OtherClass can be defined in a registered autoloader, it is actually // loaded and $a gets boolean value false ($o is not a OtherClass) // if OtherClass can not be defined in a registered autoloader, a fatal // error occurs. $name = 'YetAnotherClass'; $a = $o instanceof $name; // YetAnotherClass is not defined! // $a simply gets boolean value false, YetAnotherClass remains undefined. As of PHP version 5.1.0, the registered autoloaders are not called anymore in these situations. Older versions of PHP (before 5.0) GoalKicker.com – PHP Notes for Professionals 65 In older versions of PHP (before 5.0), the is_a function can be used to determine wether an object is of some class. This function was deprecated in PHP version 5 and undeprecated in PHP version 5.3.0. GoalKicker.com – PHP Notes for Professionals 66 Chapter 11: References Section 11.1: Assign by Reference This is the first phase of referencing. Essentially when you assign by reference, you're allowing two variables to share the same value as such. $foo = &$bar; $foo and $bar are equal here. They do not point to one another. They point to the same place (the "value"). You can also assign by reference within the array() language construct. While not strictly being an assignment by reference. $foo = 'hi'; $bar = array(1, 2); $array = array(&$foo, &$bar[0]); Note, however, that references inside arrays are potentially dangerous. Doing a normal (not by reference) assignment with a reference on the right side does not turn the left side into a reference, but references inside arrays are preserved in these normal assignments. This also applies to function calls where the array is passed by value. Assigning by reference is not only limited to variables and arrays, they are also present for functions and all "pass by-reference" associations. function incrementArray(&$arr) { foreach ($arr as &$val) { $val++; } } function &getArray() { static $arr = [1, 2, 3]; return $arr; } incrementArray(getArray()); var_dump(getArray()); // prints an array [2, 3, 4] Assignment is key within the function definition as above. You can not pass an expression by reference, only a value/variable. Hence the instantiation of $a in bar(). Section 11.2: Return by Reference Occasionally there comes time for you to implicitly return-by-reference. Returning by reference is useful when you want to use a function to find to which variable a reference should be bound. Do not use return-by-reference to increase performance. The engine will automatically optimize this on its own. Only return references when you have a valid technical reason to do so. GoalKicker.com – PHP Notes for Professionals 67