PHP Language
PHP is a general-purpose scripting language geared towards web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by the PHP Group. PHP was originally an abbreviation of Personal Home Page, but it now stands for the recursive backronym PHP: Hypertext Preprocessor.
PHP Tags
When PHP parses a file, it looks for opening and closing tags, which are
Flow Control
If - Else - ElseIf
Switch
For Next
While - Do
Do - While
For - Each
break
break ends execution of the current for:
- foreach
- while
- do-while
- switch
break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.
Echo Output
Print Output
print is not actually a real function (it is a language construct) so you are not required to use parentheses with its argument list.
Printf - Formatted Output
Produces output according to format.
Sprintf - Formatted String
A type specifier that says what type the argument data should be treated as. Possible types:
| Type | Specifiers |
|---|---|
| % | a literal percent character. No argument is required. |
| b | the argument is treated as an integer, and presented as a binary number. |
| c | the argument is treated as an integer, and presented as the character with that ASCII value. |
| d | the argument is treated as an integer, and presented as a (signed) decimal number. |
| e | the argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less). |
| E | like %e but uses uppercase letter (e.g. 1.2E+2). |
| f | the argument is treated as a float, and presented as a floating-point number (locale aware). |
| F | the argument is treated as a float, and presented as a floating-point number (non-locale aware). Available since PHP 4.3.10 and PHP 5.0.3. |
| g | shorter of %e and %f. |
| G | shorter of %E and %f. |
| o | the argument is treated as an integer, and presented as an octal number. |
| s | the argument is treated as and presented as a string. |
| u | the argument is treated as an integer, and presented as an unsigned decimal number. |
| x | the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters). |
| X | the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters). |
Variables will be co-erced to a suitable type for the specifier:
| Type | Specifiers |
|---|---|
| string | s |
| integer | d, u, c, o, x, X, b |
| double | g, G, e, E, f, F |
Example #1 Argument Swapping
This will output "There are 5 monkeys in the tree". But imagine we are creating a format string in a separate file, commonly because we would like to internationalize it and we rewrite it as:
Example #2 Argument Swapping
We now have a problem. The order of the placeholders in the format string does not match the order of the arguments in the code. We would like to leave the code as is and simply indicate in the format string which arguments the placeholders refer to. We would write the format string like this instead:
Example #3 Argument Swapping
An added benefit here is that you can repeat the placeholders without adding more arguments in the code. For example:
Example #4 Argument Swapping
When using argument swapping, the n$ position specifier must come immediately after the percent sign (%), before any other specifiers, as shown in the example below.
Example #5 Specifying Padding Character
Example #6 Position Specifier With Other Specifiers
Attempting to use a position specifier greater than PHP_INT_MAX will result in sprintf() generating warnings.
print_r
Prints human-readable information about a variable
Example #1 print_r() Example
Example #2 Return Parameter Example
var_dump
Dumps information about a variable
This function displays structured information about one or more expressions that
includes its type and value. Arrays and objects are explored recursively with values
indented to show structure.
All public, private and protected properties of objects will be returned in the output unless the object implements a __debugInfo() method (implemented in PHP 5.6.0).
The above example will output:
Embedded PHP
Conditionally Embedded PHP
Embedded PHP File
- include - Adds the files contents to the code. Does not prevent the same file from being included elsewhere.
- include_once - The include_once statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again, and include_once returns true. As the name suggests, the file will be included just once.
- require - require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue.
- require_once - The require_once expression is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again.
Embedding & Inclusion
There are many options for constructing PHP applications.
Basic File Embedding
Basic file embedding is ofter used to add pieces that make for consistency between all the pages of the site. Things like headers and footers, side panels, etc...
Function Embedding
Functions used throughout the page can be grouped together into one file to be embedded at the beginning of the page. The functions will be available to any PHP sections within the page. In the structure below, within the body (Body.php), functions declared or included in any of the files above Body.php will be available in Body.php. These files include Main.php, Functions.php (The obvious location), Header.php or HeaderNavigation.php
Server Side Data Embedding Local
Data can be created in a separate file and included in the page. Possible data sources include all of the data types included in the PHP language, such as: integers, floating point numbers, strings, booleans, arrays, classes (Objects), JSON Data, XML Data, etc...
Example 1 - PHP Data Object
Example 2 - JSON Data Object
Example 3 - XML Data Object
Server Side Data Embedding Remote
Client Side Data Embedding Remote
Form - Post & Querystring (Get)
$_GET[""] - Get Query String
The below example will output something similar to: Hello Hannes!
$_POST - Get Post Variables
An associative array of variables passed to the current script via the HTTP POST method.
$HTTP_POST_VARS contains the same initial information, but is not a superglobal. (Note that $HTTP_POST_VARS and $_POST are different variables and that PHP handles them as such)
Start Page
welcome.php
PHP Predefined Functions
htmlspecialchars()
Convert special characters to HTML entities
json_decode()
Decodes a JSON string
json_encode()
Returns the JSON representation of a value
explode()
Split a string by string
implode()
Join array elements with a string
str_split()
Convert a string to an array
chunk_split()
Split a string into smaller chunks
preg_split()
Split string by a regular expression
count_chars()
Return information about characters used in a string
str_word_count()
Return information about words used in a string
file_get_contents
Reads entire file into a string
This function is similar to file(), except that file_get_contents() returns the file
in a string, starting at the specified offset up to length bytes.
On failure, file_get_contents() will return FALSE.
file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.
If you're opening a URI with special characters, such as spaces, you need to encode the URI with urlencode().
| Parameter | Description |
|---|---|
| filename | Name of the file to read. |
| use_include_path | Note: As of PHP 5 the FILE_USE_INCLUDE_PATH constant can be used to trigger include path search. |
| context | A valid context resource created with stream_context_create(). If you don't need to use a custom context, you can skip this parameter by NULL. |
| offset | The offset where the reading starts on the original stream. Seeking (offset) is not supported with remote files. Attempting to seek on non-local files may work with small offsets, but this is unpredictable because it works on the buffered stream. |
| length | Maximum length of data read. The default is to read until end of file is reached. Note that this parameter is applied to the stream processed by the filters. |
Return Values
The function returns the read data or FALSE on failure.
$argc
$argv
Language Reference
Basic syntax
PHP tags
Escaping from HTML
Instruction separation
Comments
Types
Introduction
Booleans
Integers
Floating point numbers
Strings
Arrays
Objects
Resources
NULL
Callbacks / Callables
Pseudo-types and variables used in this documentation
Type Juggling
Variables
Basics
Predefined Variables
Variable scope
Variable variables
Variables From External Sources
Constants
Syntax
Magic constants
Expressions
Operators
Operator Precedence
Arithmetic Operators
Assignment Operators
Bitwise Operators
Comparison Operators
Error Control Operators
Execution Operators
Incrementing/Decrementing Operators
Logical Operators
String Operators
Array Operators
Type Operators
Control Structures
Introduction
if
else
elseif/else if
Alternative syntax for control structures
while
do-while
for
foreach
break
continue
switch
declare
return
require
include
require_once
include_once
goto
Functions
User-defined functions
Function arguments
Returning values
Variable functions
Internal (built-in) functions
Anonymous functions
Classes and Objects
Introduction
The Basics
Properties
Class Constants
Autoloading Classes
Constructors and Destructors
Visibility
Object Inheritance
Scope Resolution Operator (::)
Static Keyword
Class Abstraction
Object Interfaces
Traits
Overloading
Object Iteration
Magic Methods
Final Keyword
Object Cloning
Comparing Objects
Type Hinting
Late Static Bindings
Objects and references
Object Serialization
OOP Changelog
Namespaces
Namespaces overview
Defining namespaces
Declaring sub-namespaces
Defining multiple namespaces in the same file
Using namespaces: Basics
Namespaces and dynamic language features
namespace keyword and __NAMESPACE__ constant
Using namespaces: Aliasing/Importing
Global space
Using namespaces: fallback to global function/constant
Name resolution rules
FAQ: things you need to know about namespaces
Exceptions
Extending Exceptions
Generators
Generators overview
Generator syntax
Comparing generators with Iterator objects
References Explained
What References Are
What References Do
What References Are Not
Passing by Reference
Returning References
Unsetting References
Spotting References
Predefined Variables
Superglobals - Superglobals are built-in variables that are always available in all scopes
$GLOBALS - References all variables available in global scope
$_SERVER - Server and execution environment information
$_GET - HTTP GET variables
$_POST - HTTP POST variables
$_FILES - HTTP File Upload variables
$_REQUEST - HTTP Request variables
$_SESSION - Session variables
$_ENV - Environment variables
$_COOKIE - HTTP Cookies
$php_errormsg - The previous error message
$HTTP_RAW_POST_DATA - Raw POST data
$http_response_header - HTTP response headers
$argc - The number of arguments passed to script
$argv - Array of arguments passed to script
Predefined Exceptions
Exception
ErrorException
Predefined Interfaces and Classes
Traversable - The Traversable interface
Iterator - The Iterator interface
IteratorAggregate - The IteratorAggregate interface
ArrayAccess - The ArrayAccess interface
Serializable - The Serializable interface
Closure - The Closure class
Generator - The Generator class
Context options and parameters
Socket context options - Socket context option listing
HTTP context options - HTTP context option listing
FTP context options - FTP context option listing
SSL context options - SSL context option listing
CURL context options - CURL context option listing
Phar context options - Phar context option listing
MongoDB context options - MongoDB context option listing
Context parameters - Context parameter listing
Supported Protocols and Wrappers
file:// - Accessing local filesystem
http:// - Accessing HTTP(s) URLs
ftp:// - Accessing FTP(s) URLs
php:// - Accessing various I/O streams
zlib:// - Compression Streams
data:// - Data (RFC 2397)
glob:// - Find pathnames matching pattern
phar:// - PHP Archive
ssh2:// - Secure Shell 2
rar:// - RAR
ogg:// - Audio streams
expect:// - Process Interaction Streams