Including PHP in a File
<?php
// place PHP code here
?>
Writing Comments
//
— Denotes comments that only span one line#
— Another way of producing single-line comments/*...*/
— Everything between/*
and*/
is not executed, also works across several lines
Outputting Data
In PHP, data is commonly output using echo
or print
. For example, the title of this blog post might be displayed on a page like this:
<?php
echo "<h2>Hello World!</h2>";
?>
The two commands echo
and print
are pretty much the same. The only difference is that the former has no return value and can take several parameters, while the latter has a return value of 1 and can only take one argument.
Note: Like all other PHP commands, functions echo
and print
are not case sensitive. That means that when you write ECHO
, EcHo
, eCHO
or any other variation, they will continue to work. As you will learn further on, that doesn’t apply to everything.
Writing PHP Functions
function NameOfTheFunction() {
// PHP code here
}
Quick explanation: the first part is the function of a name (reminder: function names are not case sensitive). After that, everything between the curly braces is what the function does when called.
Defining Variables
In PHP, you denote a variable using the $
sign and assign its value using =
. A typical example:
<?php
$title = "PHP Cheat Sheet";
?>
Note:
- Variables need to start with a letter or underscore (
_
) and can only be comprised of alpha-numeric characters - PHP variables are case sensitive, that means
$myVar
and$myvar
are not the same thing - If your variable consists of more than one word you may write it
$my_variable
or$myVariable
Types of Data
- Integers — Integers are non-decimal numbers between -2,147,483,648 and ,147,483,647. They must have at least one digit and no decimal point. It can be in decimal, hexadecimal, or octal.
- Floats — This is the name for numbers with a decimal point or in exponential form.
- Strings — This simply means text. We will talk about it in detail further below.
- Boolean values — Meaning true/false statements.
- Arrays — Arrays are variables that store several values. We will talk about them in detail further below.
- Objects — Objects store both data and information on how to process it.
- Resources — These are references to functions and resources outside of PHP.
- NULL — A variable that is NULL doesn’t have any value.
There is no need to declare PHP variables in a certain way. They automatically take on the type of data they contain.
Variable Scope
Variables can be available in different scopes, meaning the part of a script you can access them. This can be global, local and static.
Any variable declared outside of a function is available globally. That means it can be accessed outside of a function as well.
If you declare a variable inside a function, it will have a local scope. The consequence is that it can only be accessed within that function.
A way around this is to prepend a local variable with global
. That way, it becomes part of the global scope:
function myFunction() {
global $a, $b;
$b = $a - $b;
}
In both cases, the variable becomes part of the $GLOBALS
variable mentioned below.
Finally, it’s also possible to add static
in front of a local variable. That way, it won’t be deleted after its function is executed and can be reused.
Predefined Variables
Reserve PHP variables, accessible from anywhere, regardless of scope.
$GLOBALS
— Used to access global variables from anywhere inside a PHP script$_SERVER
— Contains information about the locations of headers, paths, and scripts$_GET
— Can collect data that was sent in the URL or submitted in an HTML form$_POST
— Used to gather data from an HTML form and to pass variables$_REQUEST
— Also collects data after submitting an HTML form
Variable-Handling Functions
There are a whole bunch of functions to work with variables:
boolval
— Used to retrieve the boolean value of a variabledebug_zval_dump
— Outputs a string representation of an internal zend valueempty
— Checks whether a variable is empty or notfloatval
— Get the float value of a variable (doubleval
is another possibility)get_defined_vars
— Returns an array of all defined variablesget_resource_type
— Returns the resource typegettype
— Retrieves the variable typeimport_request_variables
— Import GET/POST/Cookie variables into the global scopeintval
— Find the integer value of a variableis_array
— Checks whether a variable is an arrayis_bool
— Finds out if a variable is a booleanis_callable
— Verify whether you can call the contents of a variable as a functionis_countable
— Check whether the contents of a variable are countableis_float
— Find out if the type of a variable is float, alternatives:is_double
andis_real
is_int
— Check if the type of a variable is an integer,is_integer
andis_long
also worksis_iterable
— Verify that a variable’s content is an iterable valueis_null
— Checks whether a variable’s value is NULLis_numeric
— Find out if a variable is a number or a numeric stringis_object
— Determines whether a variable is an objectis_resource
— Check if a variable is a resourceis_scalar
— Tests if a variable is a scalaris_string
— Find out whether the type of a variable is a stringisset
— Determine if a variable has been set and is not NULLprint_r
— Provides human-readable information about a variableserialize
— Generates a representation of a value that is storablesettype
— Sets a variable’s typestrval
— Retrieves the string value of a variableunserialize
— Creates a PHP value from a stored representationunset
— Unsets a variablevar_dump
— Dumps information about a variablevar_export
— Outputs or returns a string representation of a variable that can be parsed
Constants
Aside from variables, you can also define constants which also store values. In contrast to variables their value can not be changed, it’s locked in.
In PHP you can define a constant:
define(name, value, true/false)
The first is the name, the second the constant’s value and the third parameter whether its name should be case sensitive (the default is false).
Constants are useful since they allow you to change the value for an entire script in one place instead of having to replace every instance of it. They are also global in nature, meaning they can be accessed from anywhere.
Aside from user-defined constants, there also a number of default PHP constants:
__LINE__
— Denotes the number of the current line in a file__FILE__
— Is the full path and filename of the file__DIR__
— The directory of the file__FUNCTION__
— Name of the function__CLASS__
— Class name, includes the namespace it was declared in__TRAIT__
— The trait name, also includes the namespace__METHOD__
— The class method name__NAMESPACE__
— Name of the current namespace
PHP Arrays – Grouped Values
Arrays are a way to organize several values in a single variable so that they can be used together. While functions are for blocks of code, arrays are for the values – a placeholder for larger chunks of information.
In PHP there are different types of arrays:
- Indexed arrays – Arrays that have a numeric index
- Associative arrays – Arrays where the keys are named
- Multidimensional arrays – Arrays that contain one or more other arrays
Declaring an Array in PHP
Arrays in PHP are created with the array()
<?php
$cms = array("Banna", "Apple", "Pear");
echo "What is your favorite fruit? Is it " . $cms[0] . ", " . $cms[1] . " or " . $cms[2] . "?";
?>
Array keys can either be strings or integers.
How to create an array with key value pairs in PHP?
PHP offers us a special type of array called an Associative Array that allows us to create an array with Key-Value pairs. The syntax for creating an Associative Array is as follows:
Syntax 1: Using array() constructor
$arrayVariable = array( key1 => value1, key2 => value2, key3 => value3, ... keyN => valueN, );
Syntax 2: Using shorthand notation
$arrayVariable = [ key1 => value1, key2 => value2, key3 => value3, ... keyN => valueN, ];
Array Functions
array_change_key_case
— Changes all keys in an array to uppercase or lowercasearray_chunk
— Splits an array into chunksarray_column
— Retrieves the values from a single column in an arrayarray_combine
— Merges the keys from one array and the values from another into a new arrayarray_count_values
— Counts all values in an arrayarray_diff
— Compares arrays, returns the difference (values only)array_diff_assoc
— Compares arrays, returns the difference (values and keys)array_diff_key
— Compares arrays, returns the difference (keys only)array_diff_uassoc
— Compares arrays (keys and values) through a user callback functionarray_diff_ukey
— Compares arrays (keys only) through a user callback functionarray_fill
— Fills an array with valuesarray_fill_keys
— Fills an array with values, specifying keysarray_filter
— Filters the elements of an array via a callback functionarray_flip
— Exchanges all keys in an array with their associated valuesarray_intersect
— Compare arrays and return their matches (values only)array_intersect_assoc
— Compare arrays and return their matches (keys and values)array_intersect_key
— Compare arrays and return their matches (keys only)array_intersect_uassoc
— Compare arrays via a user-defined callback function (keys and values)array_intersect_ukey
— Compare arrays via a user-defined callback function (keys only)array_key_exists
— Checks if a specified key exists in an array, alternative:key_exists
array_keys
— Returns all keys or a subset of keys in an arrayarray_map
— Applies a callback to the elements of a given arrayarray_merge
— Merge one or several arraysarray_merge_recursive
— Merge one or more arrays recursivelyarray_multisort
— Sorts of multiple or multi-dimensional arraysarray_pad
— Inserts a specified number of items (with a specified value) into an arrayarray_pop
— Deletes an element from the end of an arrayarray_product
— Calculate the product of all values in an arrayarray_push
— Push one or several elements to the end of the arrayarray_rand
— Pick one or more random entries out of an arrayarray_reduce
— Reduce the array to a single string using a user-defined functionarray_replace
— Replaces elements in the first array with values from following arraysarray_replace_recursive
— Recursively replaces elements from later arrays into the first arrayarray_reverse
— Returns an array in reverse orderarray_search
— Searches the array for a given value and returns the first key if successfularray_shift
— Shifts an element from the beginning of an arrayarray_slice
— Extracts a slice of an arrayarray_splice
— Removes a portion of the array and replaces itarray_sum
— Calculate the sum of the values in an arrayarray_udiff
— Compare arrays and return the difference using a user function (values only)array_udiff_assoc
— Compare arrays and return the difference using default and a user function (keys and values)array_udiff_uassoc
— Compare arrays and return the difference using two user functions (values and keys)array_uintersect
— Compare arrays and return the matches via user function (values only)array_uintersect_assoc
— Compare arrays and return the matches via a default user function (keys and values)array_uintersect_uassoc
— Compare arrays and return the matches via two user functions (keys and values)array_unique
— Removes duplicate values from an arrayarray_unshift
— Adds one or more elements to the beginning of an arrayarray_values
— Returns all values of an arrayarray_walk
— Applies a user function to every element in an arrayarray_walk_recursive
— Recursively applies a user function to every element of an arrayarsort
— Sorts an associative array in descending order according to the valueasort
— Sorts an associative array in ascending order according to the valuecompact
— Create an array containing variables and their valuescount
— Count all elements in an array, alternatively usesizeof
current
— Returns the current element in an array, an alternative ispos
each
— Return the current key and value pair from an arrayend
— Set the internal pointer to the last element of an arrayextract
— Import variables from an array into the current symbol tablein_array
— Checks if a value exists in an arraykey
— Fetches a key from an arraykrsort
— Sorts an associative array by key in reverse orderksort
— Sorts an associative array by keylist
— Assigns variables as if they were an arraynatcasesort
— Sorts an array using a “natural order” algorithm independent of casenatsort
— Sorts an array using a “natural order” algorithmnext
— Advance the internal pointer of an arrayprev
— Move the internal array pointer backwardrange
— Creates an array from a range of elementsreset
— Set the internal array pointer to its first elementrsort
— Sort an array in reverse ordershuffle
— Shuffle an arraysort
— Sorts an indexed array in ascending orderuasort
— Sorts an array with a user-defined comparison functionuksort
— Arrange an array by keys using a user-defined comparison functionusort
— Categorize an array by values using a comparison function defined by the user
PHP Strings
In programming, speech strings are nothing more than text. As we have settled earlier, they are also a valid value for variables.
Defining Strings
In PHP there are several ways to define strings:
- Single quotes — This is the simplest way. Just wrap your text in
'
markers and PHP will handle it as a string. - Double quotes — As an alternative you can use
"
. When you do, it’s possible to use the escape characters below to display special characters. - heredoc — Begin a string with
<<<
and an identifier, then put the string in a new line. Close it in another line by repeating the identifier.heredoc
behaves like double-quoted strings. - nowdoc — Is what
heredoc
is for double-quoted strings but for single quotes. It works the same way and eliminates the need for escape characters.
Note: Strings can contain variables, arrays, and objects.
Escape Characters
\n
— Linefeed\r
— Carriage return\t
— Horizontal tab\v
— Vertical tab\e
— Escape\f
— Form feed\\
— Backslash\$
— Dollar sign/'
— Single quote\"
— Double quote\[0-7]{1,3}
— Character in octal notation\x[0-9A-Fa-f]{1,2}
— Character in hexadecimal notation\u{[0-9A-Fa-f]+}
— String as UTF-8 representation
String Functions
addcslashes()
— Returns a string with backslashes in front of specified charactersaddslashes()
— Returns a string with backslashes in front of characters that need to be escapedbin2hex()
— Converts a string of ASCII characters to hexadecimal valueschop()
— Removes space or other characters from the right end of a stringchr()
— Returns a character from a specified ASCII valuechunk_split()
— Splits a string into a series of smaller chunksconvert_cyr_string()
— Converts a string from a Cyrillic character set to anotherconvert_uudecode()
— Decodes a uuencoded stringconvert_uuencode()
— Encodes a string using uuencodecount_chars()
— Returns information about the characters in a stringcrc32()
— Calculates a 32-bit CRC for a stringcrypt()
— Returns a hashed stringecho() or echo ''
— Outputs one or several stringsexplode()
— Breaks down a string into an arrayfprintf()
— Writes a formatted string to a specified output streamget_html_translation_table()
— Returns the translation table used byhtmlspecialchars()
andhtmlentities()
hebrev()
— Transforms Hebrew text to visual texthebrevc()
— Converts Hebrew text to visual text and implements HTML line breakshex2bin()
— Translate hexadecimal values to ASCII charactershtml_entity_decode()
— Turns HTML entities to charactershtmlentities()
— Converts characters to HTML entitieshtmlspecialchars_decode()
— Transforms special HTML entities to charactershtmlspecialchars()
— Switches predefined characters to HTML entitiesimplode()
— Retrieves a string from the elements of an array, same asjoin()
lcfirst()
— Changes a string’s first character to lowercaselevenshtein()
— Calculates the Levenshtein distance between two stringslocaleconv()
— Returns information about numeric and monetary formatting for the localeltrim()
— Removes spaces or other characters from the left side of a stringmd5()
— Calculates the MD5 hash of a string and returns itmd5_file()
— Calculates the MD5 hash of a filemetaphone()
— Provides the metaphone key of a stringmoney_format()
— Returns a string as a currency stringnl_langinfo()
— Gives specific locale informationnl2br()
— Inserts HTML line breaks for each new line in a stringnumber_format()
— Formats a number including grouped thousandsord()
— Returns the ASCII value of a string’s first characterparse_str()
— Parses a string into variablesprint()
— Outputs one or several stringsprintf()
— Outputs a formatted stringquoted_printable_decode()
— Converts a quoted-printable string to 8-bit binaryquoted_printable_encode()
— Goes from 8-bit string to a quoted-printable stringquotemeta()
— Returns a string with a backslash before metacharactersrtrim()
— Strips whitespace or other characters from the right side of a stringsetlocale()
— Sets locale informationsha1()
— Calculates a string’s SHA-1 hashsha1_file()
— Does the same for a filesimilar_text()
— Determines the similarity between two stringssoundex()
— Calculates the soundex key of a stringsprintf()
— Returns a formatted stringsscanf()
— Parses input from a string according to a specified formatstr_getcsv()
— Parses a CSV string into an arraystr_ireplace()
— Replaces specified characters in a string with specified replacements (case-insensitive)str_pad()
— Pads a string to a specified lengthstr_repeat()
— Repeats a string a preset number of timesstr_replace()
— Replaces specified characters in a string (case-sensitive)str_rot13()
— Performs ROT13 encoding on a stringstr_shuffle()
— Randomly shuffles the characters in a stringstr_split()
— Splits strings into arraysstr_word_count()
— Returns the number of words in a stringstrcasecmp()
— Case-insensitive comparison of two stringsstrcmp()
— Binary safe string comparison (case sensitive)strcoll()
— Compares two strings based on localestrcspn()
— Returns the number of characters found in a string before the occurrence of specified charactersstrip_tags()
— Removes HTML and PHP tags from a stringstripcslashes()
— Opposite ofaddcslashes()
stripslashes()
— Opposite ofaddslashes()
stripos()
— Finds the position of the first occurrence of a substring within a string (case insensitive)stristr()
— Case-insensitive version ofstrstr()
strlen()
— Returns the length of a stringstrnatcasecmp()
— Case-insensitive comparison of two strings using a “natural order” algorithmstrnatcmp()
— Same as the aforementioned but case sensitivestrncasecmp()
— String comparison of a defined number of characters (case insensitive)strncmp()
— Same as above but case-sensitivestrpbrk()
— Searches a string for any number of charactersstrpos()
— Returns the position of the first occurrence of a substring in a string (case sensitive)strrchr()
— Finds the last occurrence of a string within another stringstrrev()
— Reverses a stringstrripos()
— Finds the position of the last occurrence of a string’s substring (case insensitive)strrpos()
— Same asstrripos()
but case sensitivestrspn()
— The number of characters in a string with only characters from a specified liststrstr()
— Case-sensitive search for the first occurrence of a string inside another stringstrtok()
— Splits a string into smaller chunksstrtolower()
— Converts all characters in a string to lowercasestrtoupper()
— Same but for uppercase lettersstrtr()
— Translates certain characters in a string, alternative:strchr()
substr()
— Returns a specified part of a stringsubstr_compare()
— Compares two strings from a specified start position up to a certain length, optionally case sensitivesubstr_count()
— Counts the number of times a substring occurs within a stringsubstr_replace()
— Replaces a substring with something elsetrim()
— Removes space or other characters from both sides of a stringucfirst()
— Transforms the first character of a string to uppercaseucwords()
— Converts the first character of every word in a string to uppercasevfprintf()
— Writes a formatted string to a specified output streamvprintf()
— Outputs a formatted stringvsprintf()
— Writes a formatted string to a variablewordwrap()
— Shortens a string to a given number of characters
PHP Operators
Operators allow you to perform operations with values, arrays, and variables. There are several different types.
Arithmetic Operators
Your standard mathematic operators.
+
— Addition-
— Subtraction*
— Multiplication/
— Division%
— Modulo (the remainder of value divided by another)**
— Exponentiation
Assignment Operators
Besides the standard assignment operator (=
), you also have the following options:
+=
— a += b is the same as a = a + b-=
— a -= b is the same as a = a – b*=
— a *= b is the same as a = a * b/=
— a /= b is the same as a = a / b%=
— a %= b is the same as a = a % b
Comparison Operators
==
— Equal===
— Identical!=
— Not equal<>
— Not equal!==
— Not identical<
— Less than>
— Greater than<=
— Less than or equal to>=
— Greater than or equal to<=>
— Less than, equal to, or greater than
Logical Operators
and
— Andor
— Orxor
— Exclusive or!
— Not&&
— And||
— Or
Bitwise Operators
&
— And|
— Or (inclusive or)^
— Xor (exclusive or)~
— Not<<
— Shift left>>
— Shift right
Error Control Operator
You can use the @
sign to prevent expressions from generating error messages. This is often important for security reasons, for example, to keep confidential information safe.
Execution Operator
PHP supports one execution operator, which is ``
(backticks). These are not single-quotes! PHP will attempt to execute the contents of the backticks as a shell command.
Increment/Decrement Operators
++$i
— Increments a variable by one, then returns it$i++
— Returns a variable, then increments it by one--$i
— Decrements the variable by one, returns it afterward$i--
— Returns the variable then decrements it by one
String Operators
.
— Used to concatenate (mean combine) arguments.=
— Used to append the argument on the right to the left-side argument
Loops in PHP
Loops are very common in programming. They allow you to run through the same block of code under different circumstances. PHP has several different ones.
For Loop
This type goes through a block of code a specified number of times:
for ($i = 0; $i <= 10; $i++) {
// code to execute goes here
}
Foreach Loop
A loop using foreach
runs through each element in an array:
foreach ($InsertYourArrayName as $value) {
// code to execute goes here
}
// or
foreach ($array as $key => $value)
While Loop
Loops through a block of code as long as a specified condition is true.
while (condition that must apply) {
// code to execute goes here
}
Do…While Loop
The final PHP loop runs a code snippet once, then repeats the loop as long as the given condition is true.
do {
// code to execute goes here;
} while (condition that must apply);
Conditional Statements
If/else statements are similar to loops. They are statements for running code only under certain circumstances. You have several options:
If/elseif/else Statement
if (condition) {
// code to execute if condition is met
} elseif (condition) {
// code to execute if this condition is met
} else {
// code to execute if none of the conditions are met
}
Switch Statement
switch (n) {
case 1:
code to execute if n=1;
break;
case 'abc':
code to execute if n='abc';
break;
case z:
code to execute if n=z;
break;
// add more cases as needed
default:
code to execute if n is neither of the above;
}
Working with Forms in PHP
$_GET
and $_POST
help to collect data sent via a form.
Using GET vs POST
GET collects data via URL parameters. That means all variable names and their values are contained in the page address.
The advantage of this is that you’re able to bookmark the information. Keep in mind that it also means that the information is visible to everyone. For that reason, GET is not suitable for sensitive information such as passwords. It also limits the amount of data that can be sent in ca 2000 characters.
POST, on the other hand, uses the HTTP POST method to pass on variables. This makes the data invisible to third parties, as it is sent in the HTTP body. You are not able to bookmark it.
With POST, there are no limits to the amount of information you can send. Aside from that, it also has advanced functionality and is therefore preferred by developers.
Form Security
The most important issue when it comes to web forms is security. If not set up properly, they are vulnerable to cross-scripting attacks. The hackers add scripts to unsecured web forms to use them for their own purpose.
PHP offers following function to thwart those attacks:
htmlspecialchars()
trim()
stripslashes()
Required Fields, Error Messages and Data Validation
PHP is able to define required fields (you can’t submit the form without filling them out), display error messages if some information is missing and to validate data. We have already talked about the necessary tools to do so.
For example, you can simply define variables for your form fields and use the empty()
function to check if they have values. After that, create a simple if/else statement to either send the submitted data or output an error message.
The next step is to check the submitted data for validity. For that, PHP offers a number of filters such as FILTER_VALIDATE_EMAIL
to make sure a submitted email address has the right format.
Regular Exprressions (RegEx)
Syntax
$exp = "/w3schools/i";
RegEx Functions
preg_match()
Returns 1 if the pattern was found in the string and 0 if not
preg_match_all()
Returns the number of times the pattern was found in the string, which may also be 0
preg_replace()
Returns a new string where matched patterns have been replaced with another string
RegEx Modifiers
i
Performs a case-insensitive search
m
Performs a multiline search (patterns that search for the beginning or end of a string will match the beginning or end of each line)
u
Enables correct matching of UTF-8 encoded patterns
RegEx Patterns
[abc]
– Find one character from the options between the brackets
[^abc]
– Find any character NOT between the brackets
[0-9]
– Find one character from the range 0 to 9
Metacharacters
|
Find a match for any one of the patterns separated by | as in: cat|dog|fish
.
Find just one instance of any character
^
Finds a match as the beginning of a string as in: ^Hello
$
Finds a match at the end of the string as in: World$
\d
Find a digit
\s
Find a whitespace character
\b
Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b
\uxxxx
Find the Unicode character specified by the hexadecimal number xxxx
Quantifiers
n+
Matches any string that contains at least one n
n*
Matches any string that contains zero or more occurrences of n
n?
Matches any string that contains zero or one occurrences of n
n{x}
Matches any string that contains a sequence of X n’s
n{x,y}
Matches any string that contains a sequence of X to Y n’s
n{x,}
Matches any string that contains a sequence of at least X n’s
Grouping
Use parentheses ( ) to apply quantifiers to entire patterns. They cal also be used to select parts of the pattern to be used as a match.
<?php
$str = "Apples and bananas.";
$pattern = "/ba(na){2}/i";
echo preg_match($pattern, $str); // Outputs 1
?>
PHP Functions
- A function is a block of statements that can be used repeatedly in a program.
- A function will not execute automatically when a page loads.
- A function will be executed by a call to the function.
Default Argument Value
<?php declare(strict_types=1); // strict requirement
function setHeight(int $minheight = 100) {
echo "The height is : $minheight <br>";
}
setHeight(50);
setHeight(); // will use the default value of 100
?>
PHP Filters
Filters are used to validate and filter data that is coming from insecure sources. As mentioned, a common example is user input. PHP offers a number of filter functions and constants for that:
Filter Functions
filter_has_var()
— Checks if a variable of the specified type existsfilter_id()
— Returns the ID belonging to a named filterfilter_input()
— Retrieves a specified external variable by name and optionally filters itfilter_input_array()
— Pulls external variables and optionally filters themfilter_list()
— Returns a list of all supported filtersfilter_var_array()
— Gets multiple variables and optionally filters themfilter_var()
— Filters a variable with a specified filter
Filter Constants
FILTER_VALIDATE_BOOLEAN
— Validates a booleanFILTER_VALIDATE_EMAIL
— Certifies an e-mail addressFILTER_VALIDATE_FLOAT
— Confirms a floatFILTER_VALIDATE_INT
— Verifies an integerFILTER_VALIDATE_IP
— Validates an IP addressFILTER_VALIDATE_REGEXP
— Confirms a regular expressionFILTER_VALIDATE_URL
— Validates a URLFILTER_SANITIZE_EMAIL
— Removes all illegal characters from an e-mail addressFILTER_SANITIZE_ENCODED
— Removes/Encodes special charactersFILTER_SANITIZE_MAGIC_QUOTES
— Appliesaddslashes()
FILTER_SANITIZE_NUMBER_FLOAT
— Removes all characters, except digits, +- and .,eEFILTER_SANITIZE_NUMBER_INT
— Gets rid of all characters except digits and + –FILTER_SANITIZE_SPECIAL_CHARS
— Removes special charactersFILTER_SANITIZE_FULL_SPECIAL_CHARS
— Converts special characters to HTML entitiesFILTER_SANITIZE_STRING
— Removes tags/special characters from a string, alternative:FILTER_SANITIZE_STRIPPED
FILTER_SANITIZE_URL
— Rids all illegal characters from a URLFILTER_UNSAFE_RAW
—Do nothing, optionally strip/encode special charactersFILTER_CALLBACK
— Call a user-defined function to filter data
HTTP Functions in PHP
PHP also has the functionality to manipulate data sent to the browser from the webserver.
HTTP Functions
header()
— Sends a raw HTTP header to the browserheaders_list()
— A list of response headers ready to send (or already sent)headers_sent()
— Checks if and where the HTTP headers have been sentsetcookie()
— Defines a cookie to be sent along with the rest of the HTTP headerssetrawcookie()
— Defines a cookie (without URL encoding) to be sent along
Working with MySQL
Many platforms that are based on PHP work with a MySQL database in the background.
MySQL Functions
mysqli_affected_rows()
— The number of affected rows in the previous MySQL operationmysqli_autocommit()
— Turn auto-committing database modifications on or offmysqli_change_user()
— Changes the user of the specified database connectionmysqli_character_set_name()
— The default character set for the database connectionmysqli_close()
— Closes an open database connectionmysqli_commit()
— Commits the current transactionmysqli_connect_errno()
— The error code from the last connection errormysqli_connect_error()
— The error description from the last connection errormysqli_connect()
— Opens a new connection to the MySQL servermysqli_data_seek()
— Moves the result pointer to an arbitrary row in the result setmysqli_debug()
— Performs debugging operationsmysqli_dump_debug_info()
— Dumps debugging information into a logmysqli_errno()
— The last error code for the most recent function callmysqli_error_list()
— A list of errors for the most recent function callmysqli_error()
— The last error description for the most recent function callmysqli_fetch_all()
— Fetches all result rows as an arraymysqli_fetch_array()
— Fetches a result row as an associative, a numeric array, or bothmysqli_fetch_assoc()
— Fetches a result row as an associative arraymysqli_fetch_field_direct()
— Metadata for a single field as an objectmysqli_fetch_field()
— The next field in the result set as an objectmysqli_fetch_fields()
— An array of objects that represent the fields in a result setmysqli_fetch_lengths()
— The lengths of the columns of the current row in the result setmysqli_fetch_object()
— The current row of a result set as an objectmysqli_fetch_row()
— Fetches one row from a result set and returns it as an enumerated arraymysqli_field_count()
— The number of columns for the most recent querymysqli_field_seek()
— Sets the field cursor to the given field offsetmysqli_field_tell()
— The position of the field cursormysqli_free_result()
— Frees the memory associated with a resultmysqli_get_charset()
— A character set objectmysqli_get_client_info()
— The MySQL client library versionmysqli_get_client_stats()
— Returns client per-process statisticsmysqli_get_client_version()
— The MySQL client library version as an integermysqli_get_connection_stats()
— Statistics about the client connectionmysqli_get_host_info()
— The MySQL server hostname and the connection typemysqli_get_proto_info()
— The MySQL protocol versionmysqli_get_server_info()
— Returns the MySQL server versionmysqli_get_server_version()
— The MySQL server version as an integermysqli_info()
— Returns information about the most recently executed querymysqli_init()
— Initializes MySQLi and returns a resource for use withmysqli_real_connect()
mysqli_insert_id()
— Returns the auto-generated ID used in the last querymysqli_kill()
— Asks the server to kill a MySQL threadmysqli_more_results()
— Checks if there are more results from a multi-querymysqli_multi_query()
— Performs one or more queries on the databasemysqli_next_result()
— Prepares the next result set frommysqli_multi_query()
mysqli_num_fields()
— The number of fields in a result setmysqli_num_rows()
— The number of rows in a result setmysqli_options()
— Sets extra connect options and affect behavior for a connectionmysqli_ping()
— Pings a server connection or tries to reconnect if it has gone downmysqli_prepare()
— Prepares an SQL statement for executionmysqli_query()
— Performs a query against the databasemysqli_real_connect()
— Opens a new connection to the MySQL servermysqli_real_escape_string()
— Escapes special characters in a string for use in an SQL statementmysqli_real_query()
— Executes an SQL querymysqli_reap_async_query()
— Returns the result from async querymysqli_refresh()
— Refreshes tables or caches or resets the replication server informationmysqli_rollback()
— Rolls back the current transaction for the databasemysqli_select_db()
— Changes the default database for the connectionmysqli_set_charset()
— Sets the default client character setmysqli_set_local_infile_default()
— Unsets a user-defined handler for the LOAD LOCAL INFILE commandmysqli_set_local_infile_handler()
— Sets a callback function for the LOAD DATA LOCAL INFILE commandmysqli_sqlstate()
— Returns the SQLSTATE error code for the last MySQL operationmysqli_ssl_set()
— Establishes secure connections using SSLmysqli_stat()
— The current system statusmysqli_stmt_init()
— Initializes a statement and returns an object for use withmysqli_stmt_prepare()
mysqli_store_result()
— Transfers a result set from the last querymysqli_thread_id()
— The thread ID for the current connectionmysqli_thread_safe()
— Returns if the client library is compiled as thread-safemysqli_use_result()
— Initiates the retrieval of a result set from the last query executed using themysqli_real_query()
mysqli_warning_count()
— The number of warnings from the last query in the connection
Date/Time Functions
checkdate()
— Checks the validity of a Gregorian datedate_add()
— Adds a number of days, months, years, hours, minutes and seconds to a date objectdate_create_from_format()
— Returns a formatted DateTime objectdate_create()
— Creates a new DateTime objectdate_date_set()
— Sets a new datedate_default_timezone_get()
— Returns the default timezone used by all functionsdate_default_timezone_set()
— Sets the default timezonedate_diff()
— Calculates the difference between two datesdate_format()
— Returns a date formatted according to a specific formatdate_get_last_errors()
— Returns warnings or errors found in a date stringdate_interval_create_from_date_string()
— Sets up a DateInterval from relative parts of a stringdate_interval_format()
— Formats an intervaldate_isodate_set()
— Sets a date according to ISO 8601 standardsdate_modify()
— Modifies the timestampdate_offset_get()
— Returns the offset of the timezonedate_parse_from_format()
— Returns an array with detailed information about a specified date, according to a specified formatdate_parse()
— Returns an array with detailed information about a specified datedate_sub()
— Subtracts days, months, years, hours, minutes and seconds from a datedate_sun_info()
— Returns an array containing information about sunset/sunrise and twilight begin/end for a specified day and locationdate_sunrise()
— The sunrise time for a specified day and locationdate_sunset()
— The sunset time for a specified day and locationdate_time_set()
— Sets the timedate_timestamp_get()
— Returns the Unix timestampdate_timestamp_set()
— Sets the date and time based on a Unix timestampdate_timezone_get()
— Returns the time zone of a given DateTime objectdate_timezone_set()
— Sets the time zone for a DateTime objectdate()
— Formats a local date and timegetdate()
— Date/time information of a timestamp or the current local date/timegettimeofday()
— The current timegmdate()
— Formats a GMT/UTC date and timegmmktime()
— The Unix timestamp for a GMT dategmstrftime()
— Formats a GMT/UTC date and time according to locale settingsidate()
— Formats a local time/date as an integerlocaltime()
— The local timemicrotime()
— The current Unix timestamp with microsecondsmktime()
— The Unix timestamp for a datestrftime()
— Formats a local time and/or date according to locale settingsstrptime()
— Parses a time/date generated withstrftime()
strtotime()
— Transforms an English textual DateTime into a Unix timestamptime()
— The current time as a Unix timestamptimezone_abbreviations_list()
— Returns an array containing dst, offset, and the timezone nametimezone_identifiers_list()
— An indexed array with all timezone identifierstimezone_location_get()
— Location information for a specified timezonetimezone_name_from_abbr()
— Returns the timezone name from an abbreviationtimezone_name_get()
— The name of the timezonetimezone_offset_get()
— The timezone offset from GMTtimezone_open()
— Creates a new DateTimeZone objecttimezone_transitions_get()
— Returns all transitions for the timezonetimezone_version_get()
— Returns the version of the timezonedb
Date and Time Formatting
d
— 01 to 31j
— 1 to 31D
— Mon through Sunl
— Sunday through SaturdayN
— 1 (for Mon) through 7 (for Sat)w
— 0 (for Sun) through 6 (for Sat)m
— Months, 01 through 12n
— Months, 1 through 12F
— January through DecemberM
— Jan through DecY
— Four digits year (e.g. 2018)y
— Two digits year (e.g. 18)L
— Defines whether it’s a leap year (1 or 0)a
— am and pmA
— AM and PMg
— Hours 1 through 12h
— Hours 01 through 12G
— Hours 0 through 23H
— Hours 00 through 23i
— Minutes 00 to 59s
— Seconds 00 to 59
PHP Errors
Error Functions
debug_backtrace()
— Used to generate a backtracedebug_print_backtrace()
— Prints a backtraceerror_get_last()
— Gets the last error that occurrederror_log()
— Sends an error message to the web server’s log, a file or a mail accounterror_reporting()
— Specifies which PHP errors are reportedrestore_error_handler()
— Reverts to the previous error handler functionrestore_exception_handler()
— Goes back to the previous exception handlerset_error_handler()
— Sets a user-defined function to handle script errorsset_exception_handler()
— Sets an exception handler function defined by the usertrigger_error()
— Generates a user-level error message, you can also useuser_error()
Error Constants
E_ERROR
— Fatal run-time errors that cause the halting of the script and can’t be recovered fromE_WARNING
— Non-fatal run-time errors, execution of the script continuesE_PARSE
— Compile-time parse errors, should only be generated by the parserE_NOTICE
— Run-time notices that indicate a possible errorE_CORE_ERROR
— Fatal errors at PHP initialization, like anE_ERROR
in PHP coreE_CORE_WARNING
— Non-fatal errors at PHP startup, similar toE_WARNING
but in PHP coreE_COMPILE_ERROR
— Fatal compile-time errors generated by the Zend Scripting EngineE_COMPILE_WARNING
— Non-fatal compile-time errors by the Zend Scripting EngineE_USER_ERROR
— Fatal user-generated error, set by the programmer usingtrigger_error()
E_USER_WARNING
— Non-fatal user-generated warningE_USER_NOTICE
— User-generated notice bytrigger_error()
E_STRICT
— Suggestions by PHP to improve your code (needs to be enabled)E_RECOVERABLE_ERROR
— Catchable fatal error caught by a user-defined handle-
E_DEPRECATED
— Enable this to receive warnings about a code which is not future-proof E_USER_DEPRECATED
— User-generated warning for deprecated codeE_ALL
— All errors and warnings exceptE_STRICT