PHP

  • HTML embedded, server side, scripting language
  • Similar syntax to C, Java, Perl
  • Can be ran from the command line!
  • Interpreted language
  • Does not need to be compiled
  • Requires PHP to be installed as a server service
  • Files end with .php to let the server know that its dealing with a PHP file, and therefore needs interpreting
  • Returns HTML

 

  • 1994 Rasmus Lerdof created Personal Home Page Tools, set of Perl scripts
  • 1995 v1 PHP/FI (Personal Home Page / Forms Interpreter). Rewrite as a set of CGI binaries developed in C
  • 1997 v2 PHP/FI 2
  • 1998 v3 PHP: Hypertext Preprocessor. Recursive acronym. Parser rewrite
  • 2000 v4 New Company Zend
  • 2004 v5 Includes OOP

Working Model

 

  1. Browser Client requests page from ISP
  2. ISP resolves DNS and sends request to target web server
  3. Target web server, running Apache, finds target page
    • Since target page has .php extension, it tells the server that it needs to process the page as a PHP file
  4. PHP interpreter processes the PHP tags and asks for any requested data from MySQL database
  5. MySQL database returns any requested data to the PHP interpreter
  6. PHP returns the interpreted data as HTML to Apache
  7. Apache returns the interpreted HTML
  8. Browser Client receives receives requested page

Running?

Save & load the following as a .php file on the target platform

If successful, the standard phpinfo page will be displayed:

Anatomy of a PHP script

The basic outline of a PHP script consists of:

  1. PHP Opening tag
  2. Comments
  3. Statements
  4. PHP Closing tag
  • File name ends .php

 

PHP tag, informs interpreter to execute PHP code

<?php     ?>

 

Short codes <? ?> (without the php) can be used but are considered bad form

 

Comments

Use # or // for a single line
Use /* for

Multiple lines
*/

 

Statements

In this case the echo() function outputs a quoted string (as its argument) within its parentheses.

NOTE: Each statement must end with a semi-colon ;

 

Forgetting the semi-colon, is one of the most common problems!!

 

Whitespace, to make code more readable

HTML embedded PHP

Although the above simple script will work, PHP is more commonly embedded within HTML code:

 

Data Types

2 Fundamentals Data Yypes:

  • Numerical
    • Integer
    • Floating Point
    • Octal start with 0
    • Hex start with 0x
  • String
    • Single quote
      • Literal text
    • Double quote
      • Interploated
      • Any variables are expanded

PHP automatically evaluates data as it is assigned depending upon the context in which it is used, and therefore does not need to be specifically declared as a particular data type.

 

However, type casting can also be applied to set the target to a specific data type.

int 

double

string

array

bool

null

object

 

Integer 

Floating point number

String

Array

Boolean

NULL

Object. Instance of a class

Resource

Whole Number. No decimal point 

Real numbers

Series of characters, usually defined within "double quotes"

Named indexed collection of key with their values

Logical TRUE or FALSE

No Value. Nothing whatsoever! Not empty. Not Zero. Nothing! NULL

Object. Instance of a class

References to external resources (functions, databases, files)

Variables

  • Begin with a $
  • Followed by name, starting with a letter or _underscore
  • Case sensitive
  • Cannot use $this, reserved for OOP
  • Don't need to be declared
  • Initialised at use
  • Assigned with a single equals sign =

 

Assigned by Value

 

$myVar = 10 ;

$yourVar = "Potato" ;

 

 

Assigned by Reference

 

Prefix & ampersand to variable being referenced

 

$potatoVar = &$yourVar ;

 

Any changes to the original or referenced variable will be seen in each other. i.e. if you change one, then you change them all

Type Casting

Explicitly converts data types

 

(target data type)identifier

 

Displays:

42

52

 

Displays:

$myInt, 123, is of data type: integer
$myFloat, 12.34, is of data type: double

 

 

To test a certain datatype:

  • is_string()
  • is_float()
  • is_int()
  • is_bool()
  • is_array()
  • is_object()
  • is_resource()
  • is_null()

isset()

Returns boolean TRUE or FALSE if the target variable is set or not.

Displays:

$myVar is set

$nothing is not set

Scope

Determines when and where a variable can be used.

 

Can also be thought of as the lifetime or validity of the variable.

 

4 scope types:

  • Global
  • Local
  • Function Parameters
  • Static

Global Scope

  • Any variable defined outside of any function
  • Can be accessed from any part of the script that is not inside a function
  • Use the global keyword to access a global variable from within a function

Displays:

42

0

42

 

 

The $GLOBALS[ ] array also stores global variables, using the name of the variable as the index:

Displays:

42

Local Scope

A locally scoped variable is only valid within the block of code in which it has been declared.

Displays:

nothing here

42

6


Function Parameters

Objects passed to a function as arguments to be used within the function

Only valid within the function

Displays:

The two variables passed in were: Excellent and 12

Static Variables

Use static keyword within a function to make the variable retains its previous value

The variable still remains local to that function and cannot be used outside of the function

Displays:

$myVar is now: 1
$myVar is now: 2
$myVar is now: 3
$myVar is now: 4
$myVar is now: 5

This example shows a bad function (salmon shaded area) without using the global keyword to use the global variable.
Which is then followed by a good function (lilac shaded area) using the global keyword to use the global variable.
Finally it shows that the local variable within a function is non-existent outside of the function:

Displays:

$myVar in global scope is: 5.

 
Function NOT using global variable:
$myVar inside function is: .
Locally scoped $newVar inside function is: 0.

 
Function USING global variable:
$myVar inside function is: 5.
Locally scoped $newVar inside function is: 25.

 

 

Global $myVar is: 5.
Previously locally scoped $newVar outside the function is: .

Variable Variables

Indirectly referring to a variable.

 

Uses the value of a variable and treat that as the name of a variable

 

Displays:

$foo has a value of: 42

 

Note the use of two $$ signs to reference the value in $myVar

 

PHP uses the value in $foo (which in this case is myVar) and returns the value (42) in the variable of that name ($myVar)

 

Further indirection can be used but can also get confusing. Basically use another $ for each level of indirection used:

Displays:

$myVar has a value of: Potato
$yourVar has a value of: Potato
$theirVar has a value of: Potato
$herVar has a value of: Potato
$hisVar has a value of: Potato

echo

Outputs one or more strings

Does NOT return a value

Not necessary to use ( parentheses ), but highly recommended

Displays:

This is an example of the echo command.
This example used parenthese!
Potato
A Potato makes chips!
A $myVar makes chips!

Quotes

"Double Quotes" will interpolate any variables

 

'Single quotes' will literally print the contents

 

Displays:

Jimi Hendrix played a mean guitar!
$myVar played a mean guitar!

print

Outputs one or more strings

Provides a success/fail return value

Not necessary to use ( parentheses ), but highly recommended

Displays:

I live in London
I live in $myVar

printf

Outputs one or more strings

Provides a success/fail return value

Takes a string with format component to output the arguments

 

printf($stringFormat, $arg1 .. $arg) ;

 

Format specifiers comprise of a % symbol followed by a lower case letter

Letter Description
c Argument is treated like an integer and provides ASCII character with that value
d Argument is treated like an integer and presented as a number
f Argument is treated like a float and presented as a floating point number
s Argument is treated and presented as a string

 

%s

 

To left justify, precede the string specifier with a hyphen -

 

Number of places can be set:

%10.2f means a floating point number with a:

  • width of 10 places
    • comprising of:
      • 7 integers
      • 1 decimal point
      • 2 decimals precision

Displays:

This is a string followed by an integer 17

Standard Streams

STD IO Steams are generally used for CLI applications in PHP

 

 

The standard input is usually received from the keyboard
 
Standard out and standard error are usually sent to the screen

 

Standard In Input from Keyboard stdin 0
Standard Out Output to Screen stdout 1
Standard Error Output to Screen stderr 2

Read a single line from stdin using fgets(STDIN)

 

Assuming PHP is available from the command line, you can write to STDOUT using:

php -r 'fwrite( STDOUT, "some text output\n") ; '

 

note -r means to run the command

 

Or to write to STDERR:

php -r 'fwrite( STDERR, "some text output\n") ; '

 

 

Simple way to tell if PHP is running from the command line is to check the version with:

php -v

include_path

Contained with php.ini

 

Specifies list of directories where the: require(), include(), fopen(), file(), readfile(), file_get_contents() functions look for files

 

List of directories separated by a colon : on UNIX, or a semi-colon ; on windows

 

include_path = ".:/php/includes"

Opening files

fopen() to open files or URL

 

$fileHandle = fopen( $filename, $mode ) ;

 

Creates a local file if it doesn't already exist

 

Returns a file pointer used for further reading/writing of the specified file, or FALSE upon failure to open the specified file

 

The file pointer indicates the location to read from or write to within the file.

Read or Write: file pointer at beginning

Append: file pointer at end

 

A filehandle is assigned to the specified filename:

 

File Opening Modes

r Read only. Pointer at beginning. Must exist
r+ Read & write. Pointer at beginning. Must exist
w Write only. Pointer at beginning. Truncate file to 0 length. Create if not exist
w+ Read & Write only. Pointer at beginning. Truncate file to 0 length. Create if not exist
a Write only. Pointer at end. Create if not exist
a+ Read & write. Pointer at end. Create if not exist
x Create and open for write only. Pointer at beginning. Fail if file already exists
x+ Create and open for read & write. Pointer at beginning. Fail if file already exists

 

File Mode Modifiers

t Translate to and from windows line endings: \n to or from \r\n
b Binary mode. Dont translate. Default

CLI

Check PHP is running:

 

php -v

 

Run PHP commands straight from the CLI:

 

php -r php-command

 

Run a PHP script:

 

php -r filename.php

 

PHP script, saved as file-name.php

Reading files

Open and immediately output the file

readfile(file) ;

 

Open and assign file as a string

file_get_contents(file) ;

 

Open and assign file into array

file(file) ;

 

Read single line from opened file

fgets(file, [length]) ; //note, [length] is optional

*note feof(); tests for EOF from the file handle

*If no length specified will keep reading until end of line, or \n

 

Read opened file

fread(file, length) ; //note, length is mandatory

 

Closing files

fclose() to close files or URL

 

fclose( $fileHandle ) ;

 

Good practice to close a file:

Trimming

Remove whitespace, or other specified character, from a string

 

Trim from both sides of a string

trim(string [,charlist]) ; //optional charlist

 

Trim from left side of a string

ltrim(string [,charlist]) ; //optional charlist

 

Trim from right side of a string

rtrim(string [,charlist]) ; //optional charlist

 

If charlist is not used, the following will be removed:

" " Empty space
"\t" Tab
"\n" New Line
"r" Carriage Return
"\0" NULL
"\x0B" Vertical Tab

Writing Files

Open file, write string, close file

file_put_contents(file) ;

 

Returns number of bytes written upon success, or FALSE upon failure

 

If filename does not exist, the file is created. Otherwise, the existing file is overwritten, unless the FILE_APPEND flag is set.

 

Wite opened file

fwrite(file, string) ;

 

Returns number of bytes written upon success, or FALSE upon failure

 

Move / Rename a File or Directory

used to either rename or move files or directories

rename(source, target);

*make sure permissions and path are correct

Copy a File

Used to a file

copy(source, target);

*will overwrite existing target file

Deleting files

Used to delete files

unlink(file);

 

Super Globals

Scope is valid anywhere

 

$GLOBALS

Associative array containing all global variables currently available within the global scope of the script, including ALL other super globals.

 

The Super Global variables are recognisable by their $_ prefix followed by the rest of their name in UPPERCASE

 

$_SERVER

Associative array containing all variables set by the web server, or other sources that directly related to the execution of the script.

 

 

$_GET

Contains all variables sent by HTTP GET request to the script via URL query string

 

IMPORTANT: Data sent with the GET method is limited and visible to everyone (i.e. displayed in the browser's address bar)

The top half of the above code asks the user to enter their name

Upon submit, the data is sent using the GET method to the file specified in the form action: "get.php"

The lower half of the above code (get.php) displays the data sent, which can be seen in it's URL

e.g. https://php.tech-academy.co.uk/get.php?yourName=Derrick *(unsafe for sensitive data!)

The names of the form fields are used as the keys in the $_GET array

 

 

$_POST

Contains all variables sent via a HTTP POST request.

 

IMPORTANT: Data sent with the POST method is invisible and has no limits on the amount of data to send (default is 8MB, can be changed by post_max_size in php.ini)

The top half of the above code asks the user to enter their name

Upon submit, the data is sent using the POST method to the file specified in the form action: "post.php"

The lower half of the above code (post.php) displays the data sent, but cannot be seen in it's URL

e.g. https://php.tech-academy.co.uk/post.php

The names of the form fields are used as the keys in the $_POST array

 

 

$_COOKIE

Associative array containing all variables sent via HTTP cookies

 

 

$_FILES

Associative array containing all variables sent via HTTP POST file upload

The top half of the above code provides user with choose file form, followed by Submit button

Upon submit, the data is sent using the POST method to the file specified in the form action: "post.php"

The lower half of the above code (fileUpload.php) displays the contents of the $_FILES array

Just for completeness, the last two lines copy the file from its temp location for permanent storage

 

 

$_ENV

Associative array containing all environment variables set by your system or shell for the script

*Probably quite dangerous to have this as a live script, since it shows a little too much information!

 

 

$_REQUEST

Associative array containing the contents of $_GET, $_POST and $_COOKIE

Beware: contains all variables from untrusted sources (e.g., site visitors), best to avoid unless really necessary

The top half of the above code asks the user to enter their name

Upon submit, the data is sent using the POST method (GET could alternatively have been used) to the file specified in the form action: "request.php"

The lower half of the above code (request.php) displays the data sent

The names of the form fields are used as the keys in the $_REQUEST array

 

 

$_SESSION

Contains all variables stored in a user's session

Constants

Created using the define(); function

 

Classically UPPERCASE

 

  • Do NOT have $ sign before them
  • Can be used anywhere, regardless of scoping rules
  • Cannot be redefined or undefined once set

Operators

Assignment

$a = $b Assign
$a += $b $a = $a + $b Addition
$a -= $b $a = $a - $b Subtraction
$a *= $b $a = $a * $b Multiplication
$a /= $b $a = $a / $b Division
$a %= $b $a = $a % $b Modulus

 

Increment / Decrement

++$a Pre-Increment Increments $a by one, then returns $a
$a++ Post-Increment Returns $a, then Increments $a by one
--$a Pre-Decrement Decrements $a by one, then returns $a
$a-- Post-Decrement Returns $a, then Decrements $a by one

 

Arithmetic

$a + $b Addition Sum of $a and $b
$a - $b Subtraction Difference of $a and $b
$a * $b Multiplication Product of $a and $b
$a / $b Division Quotient of $a and $b
$a % $b Modulus Remainder of $a divided by $b

 

String

$a . $b Concatenate Produce single string, with contents of $a, followed by contents of $b
$a .= "string" Concatenating Assignment Concatenate "string" with $a and reassign to $a

 

Comparison

$a == $b Equal TRUE if $a is equal to $b
$a === $b Identical TRUE is $a is equal to $b, and they are of the same type
$a != $b Not Equal TRUE if $a is not equal to $b
$a <> $b Not Equal TRUE if $a is not equal to $b
$a !== $b Not Identical TRUE if $a is not equal to $b, or they are not of the same type
$a < $b Less Than TRUE if $a is strictly less than $b
$a > $b Greater Than TRUE if $a is strictly greater than $b
$a <= $b Less Than or Equal To TRUE if $a is less than or equal to $b
$a >= $b Less Than or Equal To TRUE if $a is greater than or equal to $b

 

Logical

$a and $b And TRUE if both $a and $b are TRUE
$a && $b And TRUE if both $a and $b are TRUE
$a or $b Or TRUE if either $a or $b is TRUE
$a || $b Or TRUE if either $a or $b is TRUE
$a xor $b Xor TRUE if either $a or $b is TRUE, but not both
! $a Not TRUE if $a is not TRUE

Arrays

Data structure that stores one or more similar data type values in a single variable

 

Data is stored in elements as key / value pairs. The key is also known as the index

 

3 different types of arrays:

  • Numeric array - Utilises a numeric index. Values are stored and accessed in linear fashion
  • Associative array - Utilises strings as index. Values stored in association with key (string) values
  • Multidimensional array - An array containing one or more arrays. Values accessed using multiple indices

Use the array() construct to create an array. Values are automatically assigned to a numerical index, if not specifically defined:

 

array("model", "price", "speed") ;

 

Alternatively, the Big Arrow => notation can be used:

 

array("0" => "model", "1" => "price", "2" => "speed") ;

 

*note: it is possible to assign alternative key values, as long as they are unique, otherwise their values will be overwritten

 

 

Numeric Array

 

Keys start from 0

 

akin to a spreadsheet that has just one column

 

Assigned using the array(); function:

 

or individually assigning specific elements, using the [ ] (aka Array Operator) notation:

 

 

Associative Array

 

Keys must be unique strings

 

akin to a spreadsheet that has just one column and uses named cells for reference (instead of a cell number)

 

or individually assigning specific elements, using the [ ] notation:

 

Multidimensional Arrays

 

An array of arrays

Each element in the array can be an array, and each element in that sub-array can be an array, etc.

Displays:

array(3) {
    ["England"]=>
    array(3) {
        ["Capital"]=>
        string(6) "London"
        ["Population"]=>
        int(40000000)
        ["NationalSport"]=>
        string(7) "Cricket"
    }
    ["Wales"]=>
    array(3) {
        ["Capital"]=>
        string(7) "Cardiff"
        ["Population"]=>
        int(5000000)
        ["NationalSport"]=>
        string(5) "Rugby"
    }
    ["Scotland"]=>
    array(3) {
        ["Capital"]=>
        string(9) "Edinburgh"
        ["Population"]=>
        int(8000000)
        ["NationalSport"]=>
        string(8) "Football"
    }
}

References

Use =& to reference the target variable

 

$myVar = "Hello, World!" ;

 

$yourVar =& $myVar ;

 

The two variables are now pointing to the same data and a change to one is reflected in the other

Ternary

Tests if a condition is true or false

 

condition ? true : false ;

 

Execution Operator

Use of `back ticks` to execute commands directly

 

Array Functions

count($myArray) ; //gives the number of indexes

 

unset($myArray[index]) ; //removes the element at index

 

unset($yourArray) ; //deletes the whole array

 

foreach () ; //iterates values in an array

 

foreach($myArray as $value) {

echo “The values are $value: \n”;

}

 

each($myArray) ; //returns a key/vale pair for each element in the array

 

array_push($myArray, $value) ; //pushes $value onto end of $myArray

 

*equivalent to: $myArray[] = $value ;

 

array_pop($myArray) ; //returns end value from the array, and removes the index, thus reducing the index length

 

array_unshift($myArray, $value) ; //inserts $value into index 0 and shifts all other indexes +1

 

array_shift($myArray) ; //removes index 0 and shifts all other indexes -1

 

print_r($myArray) ; //prints human-readable information about a variable

 

var_dump($myArray) ; //displays structured information about a variable including its type and value

*Arrays and objects are explored recursively with values indented to show structure.

 

sort($myArray) ; //sorts an array by its values. Assigns new keys!

 

Escape Sequences

Specific characters need escaping, by prefixing a backslash before the desired character:

Escape sequence Meaning
\$ $ dollar
\\ \ backslash
\' ' single quote
\" ” double quote
\? ? question mark
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab

Code Blocks

The use of { } to separate multiple lines of related statements from the rest of script.

 

Heredoc

Assigning a user defined text label to a variable to hold a string of text, using <<<DELIMITER at the beginning of the assignment and (the same) LABEL followed by a semi-colon ; to identify the end of the string.

 

  • <<< informs PHP that you want to enter heredoc mode
  • DELIMITER can be anything you like, TEXT or anything else could be used
  • Single and Double quotes do not need escaping
  • Variables will be interpolated, i.e. The value of $myVar will be substituted within the string
  • $ should be escaped if you want it displayed, i.e. \$myVar
  • Delimiter DELIMITER; identifies the end of the string. MUST be in the the first column of a new line, with NO spaces around it.

*Note: The Delimiter MUST be in the the first column of a new line, with NO spaces around it.

 

 

 

Can also be used without assigning to a var, say if you just wanted to echo it as content:

*Note: The Delimiter MUST be in the the first column of a new line, with NO spaces around it.

if, else, elseif

Consists of a boolean expression (evaluating to true or false), followed by one or more statements

 

if(test condition) {

//execute this code block if TRUE

}


Can be followed by an (optional) else statement.

 

elseif allows for an additional test condition statements

 

while

While loops through the statements enclosed within the { code block } until the test condition is false:

 

while (test condition {

statements ;

statements ;

}

Displays:

$myVar is currently
$myVar is currently 1
$myVar is currently 2
$myVar is currently 3
$myVar is currently 4

do

Do loops through the statements enclosed within the { code block } until the following while test condition is false:

 

do {

statements ;

statements ;

} while (test expression;

 

*note ending semi-colon ; after the while test expression!

for

The for loop starts from an initial condition and iterates through the statements enclosed within the { code block } until the test is false.

 

The initial condition, test and iterator are separated by a semi-colon ;

 

for (initialiser ; test ; iterator) {

statements ;

statements ;

}

switch

Tests a condition against any number of case conditions, defined within "double quotes"

 

Break must be used to terminate the switch, or the next statement will be executed.

 

A default case is utilised for when no condition is met.

*note that there's no case keyword before default

break

Used to exit out of a loop code block

 

Next statement following the loop will then be executed

Displays:

$myVar is currently 0
$myVar is currently 1
$myVar is currently 2
$myVar is currently 3
$myVar is currently 4
$myVar is currently 5
$myVar is currently 6
The if condition executed the break when $myVar evaluated to 7

continue

Passes control to the next iteration of the loop code block in which it appears, bypassing any remaining statements within that iteration of the code block

Displays:

$myVar is currently 0
$myVar is currently 1
$myVar is currently 2
$myVar is currently 3
$myVar is currently 4
$myVar is currently 5
$myVar is currently 6
$myVar is currently 8
$myVar is currently 9 

 

When the if condition for $myVar evaluated to 7,the loop continued through the other iterations, bypassing 7

foreach

Iterates through each value in an array

 

This version simply returns the values

 

This version returns the keys and values

Mixed mode

Process of turning the PHP parser on / off as required.

 

Simply close the PHP code with a ?> then carry on in normal HTML as required, then when ready go back in to PHP mode with a new <?php starting tag

 

Allows HTML code to be output based on conditional code within the PHP

Alternative Syntax

Use colon : and endif; instead of using curly braces { and }

 

Use corresponding endXXX ; for opening control structure, replacing XXX as follows:

endif ;

endwhile ;

endfor ;

endforeach ;

endswitch ;

 

Also applies to else : and elseif :

 

 

Another simple example that only displays the the HTML if the test condition is TRUE

 

A variation of the Mixed mode example:

Include and Require

Used to insert the contents of the target PHP file at the place from where it was called in the calling PHP file.

 

Four variations:

  • include()  upon failure will generate a warning, but the script will continue executing the remaining code.
  • include_once() identical to above, but will check if the file has already been included, and therefore not include it again
  • require()  upon failure will generate a fatal error and halt execution
  • require_once()  identical to above, but will check if the file has already been included, and therefore not require it again

 

Displays:

My has a top speed of mph
My Ducati has a top speed of 188 mph

Strings

Sequence of characters, usually assigned to a variable

Displays:

I live in London
I live in $myLocation

 

 

Concatenation

Joining of strings by use of the dot . operator

Displays:

I live in London

 

 

A few String Functions

 

strlen($myVar) ; //returns the number of characters in the string

 

strpos("I live in London", "London") ; //crude example, strings could be replaced by variables

 

explode($myVar) ; //breaks a string into an array

 

implode(" ", $myArray) ; //returns a string from the elements of an array. Note use of optional separator

 

md5($myVar) ; //calculates the MD5 hash of a string

 

md5_file($fileHandle) ; //calculates the MD5 hash of a file

 

strtolower($myString) ; //converts string to lowercase letters

 

strtoupper($myString) ; //converts string to uppercase letters

 

Functions

PHP requires the keyword: "function" before the function definition.

 

This is followed by the function name and parentheses to accept (zero or more) arguments being sent in to the function.

 

The code block for the function then follows within curly braces { }

 

function myFunction( argument, list ) {

echo "Hello, World!" ;

}

 

A function is called by stating the name of the function and including (zero or more) arguments to be sent to the function within parentheses, followed by a semi-colon ;

 

myFunction( argument, list ) ;

 

Displays:

Hello, World!

 

 

Apart from having the ability to create your own functions, PHP also has a few built-in functions of its own: https://www.php.net/quickref.php

Pass by Value

Passing a parameter to a function

Displays:

Hello, World!

 

 

A default value can be set by argument assignment in the function interface

 

Multiple parameters are received in to the function in the order they are sent by the function call

In the above, $myVar is the first parameter being sent in the function call, corresponding to $argTwo as the first argument in the function interface, and so on for subsequent parameters.

Pass by Reference

When parameters are passed in to a function by value, PHP takes a copy of the value and uses the copy within the function, leaving the original unchanged  outside the function.

 

In order to change the original value, it must be passed in by reference (as per assigning a variable by reference) so that the actual variable is passed in to the function.

 

function functionName( &$argument){

statements ;

}

 

Therefore any changes to that variable within the function will be reflected outside the function.

Displays:

Hello, World!
$myVar was re-assigned in the function to: Good to see you!

Function return values

To return a value from a function, the return keyword is used before the varaible being returned

 

Displays:

The sum of $myVar 17 and $yourVar 42 is 59

Variable Functions

By appending parentheses () to the end of a variable, PHP looks for a function with the same name and executes it.

 

Displays:

This is example One 

This is example Two

This is example Three with a passed in value of: Potato

This is example One

Anonymous Functions

aka Closures or Lambdas

 

Requires PHP 5.3

 

Allows functions with no name

 

An unnamed function (closure) is assigned to a variable as follows:

 

$myVar = function($myArg) {

echo "$myARG";

} ;

 

*notice the variable assignment still closes with a semi-colon ;

 

So far we have assigned an anonymous function to $myVar, which expects an argument $myArg to be passed to it

 

We can now use that variable as though it were a function:

 

Forms, GET and POST

 

A form consists of the form definition, identifying what it should do (action) and how it should do it (method)

 

<form action="submittedPage.php" method="POST">

 

Will send any collected data to the specified page, in this case: submittedPage.php, using the POST method

 

$_GET and $_POST are the two METHODS used to retrieve user entered information input to a form upon Submit.

 

  • $_GET insecure, data can be seen in the URL
  • $_POST data cannot be seen in the URL

The above HTML code for a simple form provides three text boxes and a submit button

 

Each element within the form has a specific name. This name is used for the collected data:

 

Name: <input type="text" name="formName"><br>
Age: <input type="text" name="formAge"><br>
Location: <input type="text" name="formLoc">

 

Once the user has entered their data and clicked upon submit, the "submittedPage.php" page will be loaded.

 

We then use the $_POST super global variable to present the collected information.

 

The element names of the form fields will automatically be the keys in the $_POST array

 

Notice that the element name is specified within "double quotes" within [square brackets]

Displays:

The information submitted was: 

 

Julia
21
Camden

 

*note, the URL will simply display the submittedPage.php

 

 

Alternatively, we can use the GET method

Now we collect the information using the $_GET super global variable

 

The element names of the form fields will automatically be the keys in the $_GET array

Displays:

The information submitted was: 

 

Jimmy
25
Camden

 

However, this time the URL displays all of the collected data !

 

.../submittedPage.php?formName=Jimmy&formAge=25&formLocation=Camden

 

Notice the URL contains the name of the page specified in the action, followed by a ? and each of the element names and their submitted data, separated by an &

File Upload

Uses the $_FILES super global

 

A simple form requesting file name to upload:

*note:

  • the form has an enctype="multipart/form-data"
  • the first element in the above form is of type="file", and has a name "myUploadFile" (just for this example)

 

Upon submit, the data is sent using the POST method to the file specified in the form action: "fileUpload.php"

The uploaded file is then copied from its temp location for permanent storage

 

Ensure the script has the correct permissions in order to save the file to the desired location

 

And that the desired location exists!

 

Reading Directories

Method 1: Using opendir(), readdir() and closedir()

 

  1. Assign the required directory to a handler variable: $dirHandle = opendir('path/to/target') ;
  2. Read the contents of the directory using readdir()
  3. Close the directory variable handler using closedir()

readdir() returns the file name of the next file in the directory in the order stored by the file system. This will remain TRUE until the end of the directory is reached, at which point it will turn FALSE and the while loop will end

 

 

Method 2: using scandir()

 

scandir() returns an array of the contents of the specified directory

 

Date and Time

time();

 

Works on the number of seconds since the UNIX epoch 1 January 1970 00:00:00 GMT

 

date();

 

  • converts a timestamp to a more human readable form
  • requires a format parameter
  • optional timestamp - defaults to current date/time

 

Format paramaters (case sensitive!):

a Lowercase am/pm am or pm
A Uppercase am/pm AM or PM
B Swatch Internet Time 000 to 999
c ISO 8601 date, time, and time zone 2012-11-26T14:26:55+01:00
d 2-digit day of month, leading zeros 01 to 31
D Day string, three letters Mon, Thu, Sat
F Month string, full January, April
g 12-hour clock hour, no leading zeros 1 to 12
G 24-hour clock hour, no leading zeros 0 to 23
h 12-hour clock hour, leading zeros 01 to 12
H 24-hour clock hour, leading zeros 00 to 23
i Minutes with leading zeros 00 to 59
I Is daylight savings time active? 1 if yes, 0 if no
j Day of month, no leading zeros 1 to 31
l Day string, full Sunday, Tuesday
L Is it a leap year? 1 if yes, 0 if no
m Numeric month, leading zeros 01 to 12
M Short month string Jan, Mar
n Numeric month, no leading zeros 1 to 12
O Difference from GMT 100
r RFC-822 formatted date Sun, 17 May 2007 21:30 +0000
s Seconds, with leading zeros 00 to 59
S English ordinal suffix for day number st, nd, rd, or th
t Number of days in month 28 to 31
T Time zone for server GMT, CET, EST
U Unix Timestamp 1353936090
w Numeric day of week 0 (Sunday), 6 (Saturday)
W ISO-8601 week number of year 30 (30th week of the year)
y Two-digit representation of year 75, 12
Y Four-digit representation of year 1975, 2012
z Day of year 0 to 366
Z Time zone offset in seconds -43200 to 43200

 

 

mktime();

 

Returns the UNIX timestamp for the specified date

 

mktime(hour, minute, second, month, day, year, is_dst) ;

 

 

Useful for calculations involving date/time

 

Use leading zeroes for values less than 10

All parameters optional

Order must be separated with comma ,

Cookies

Small text file held on local machine

 

Stores user information

 

setcookie(name, value, expire, path, domain, secure) ;

//last 3 parameters offer more control, but aren't used that often

 

*note: setcookie(); must be before the opening <html> tag, due to HTTP headers (e.g. cookies) being sent before body (HTML code)

 

Displays a welcome message depending upon the status of the cookie

 

 

To delete a cookie, simply set its expiry date in the past

Sessions

Allows the storage/retrieval of data across various site pages, using the $_SESSION super global

 

Server creates a UID (unique ID) consisting of a long system generated string, to store user information against.

 

UID stored in cookie or sent in URL

 

Session_start() ;  //required on every page where session processing is used

*note: session_start(); must be before the opening <html> tag, due to HTTP headers (e.g. sessions) being sent before body (HTML code)

 

The required session variables are defined within the super global $_SESSION associative array, as follows:

Displays:

London
Yamaha SG2000S
Ducati
2

 

 

Removing session data is carried out by use of the unset()

Displays:

London
Yamaha SG2000S
Ducati

 

 

Or completely destroy all session data, using or session_destroy()

Displays:

 

*note: the above is intentionally blank as the above code destroys all the session data

Regular Expressions

  • Perl Compatible Regular Expressions. preg_match(); preg_match_all();
  • POSIX Regular Expressions. ereg(); eregi(); split();  Deprecated

Regular expressions are enclosed within delimiters, usually the forward slash /

 

preg_match( "/RegEx/", "Target String", $storageArray ) ;

or

preg_match( "/$regEx/", $targetString, $storageArray ) ;

 

Where:

  • 1st argument is the regular expression to search for
  • 2nd Argument is the target string to search in
  • 3rd (optional) argument is resultant match
  • Match will return 1
  • No match returns 0

The use of any other alternative delimiter symbol can be used as long as it's the same at both ends. For instance if the vertical bar | were used, it avoids having to escape forward slashes, e.g. "/https:\/\//"

 

echo preg_match( "|http://|", "https://www.tech-academy.co.uk") ; // returns 1

 

adding a lower case i after the closing delimiter, makes the search case insensitive:

 

echo preg_match( "/HtTp/i", "http://www.tech-academy.co.uk") ; // returns 1

 

 

Meta-Characters 

^ Match at Beginning of Line
$ Match at End of line
. Match Any single character
? Match zero or one of the preceding items. Preceding character is optional
( ) Groups literal characters
[ ] Set of optional characters
[!] Set of Non-matching optional characters
- All characters between two characters
+ Match One or more of the preceding items
* Match Zero or more of the preceding items
{ , } Start and end numbers of a range of repartitions, or exactly if just one number
\ following character is literal
( | ) Match Set of alternate strings, logical OR'ing either side of the |
e.g.
ab*c will match ac or abbbc
colou?r will match the US spelling of color or the UK spelling colour

 

 

 

Character types

\d Any decimal digit
\D Any character not a decimal digit
\h Any horizontal whitespace character
\H Any character not a horizontal whitespace
\s Any whitespace character
\S Any character not a whitespace character
\v Any vertical whitespace character
\V Any character not a vertical whitespace
\w Any word (underscore or alphanumeric) character
\W Any non-word character
e.g.
\S*[Ff]red\S* will match Fred or fred within a word
^\s*$ 0 or more whitespace

 

 

 

[ Square brackets ]are used to find a range of characters, within a character class

[ Denotes start of character class
] Denotes end of character class
^ Negate, only if first character
- Indicates character range
[a-z ] Matches Any lowercase character from a to z
[A-Z] Matches Any UPPERCASE character from A to Z
[a-Z] Matches any character from lowercase a to UPPERCASE Z
[0-9] Matches decimal digit from 0 to 9
[abc] a, b, or c
[a-z] Any lowercase letter
[^A-Z] Any character that is not a uppercase letter
(gif|jpg) Matches either "gif" or "jpg"
[a-z]+ One or more lowercase letters
[0-9.-] Any number, dot, or minus sign
^[a-zA-Z0-9_]{1,}$ Any word of at least one letter, number or _
([wx])([yz]) Sub-patterns: wy, wz, xy, or xz
[^A-Za-z0-9] Any symbol (not a number or a letter)
([A-Z]{3}|[0-9]{4}) Matches three letters or four numbers

 

 

Multipliers

r+ At least one r
r* Zero or more r's
r? Alternative to r*
r{N} Match exactly N r's
r{N,M} Match at least N r's, but no more than M
r{N, } Match N or more r's
e.g.
ab{3,7}c will match an a followed by a min of 3 and a max of 7 b's followed by a c

 

 

Functions

preg_match() The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise.
preg_match_all() The preg_match_all() function matches all occurrences of pattern in string.
preg_replace() The preg_replace() function operates just like ereg_replace(), except that regular expressions can be used in the pattern and replacement input parameters.
preg_split() The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern.
preg_grep() The preg_grep() function searches all elements of input_array, returning all elements matching the regexp pattern.
preg_ quote() Quote regular expression characters

 

 

https://webcheatsheet.com/php/regular_expressions.php

https://www.tutorialspoint.com/php/php_regular_expression.htm

 

Password checker example:

In this example, the regular expression has been assigned to a string $regEx as follows

 

$regEx = /^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/ ;

 

Breaking this down, we have four groups:

 

  1. ^.*(?=.{8,}) checks there are at least 8 characters
  2. (?=.*\d) any alphanumeric zero or more times, then any digit (therefore checks there is at least one number, anywhere)
  3. (?=.*[a-z]) checks for lower case
  4. (?=.*[A-Z]).*$ checks for uppercase

The caret ^ means match at the start of the string

The . means any alphanumeric character and the * means zero or more, therefore together .* means any alphanumeric character zero or more times

The ?= means the following text must be like this

 

So in applying the above (?=.{8,}) means the next, any alphanumeric character must occur 8 or more times

 

And then (?=.*\d) means the next text must be any alphanumeric character that is a digit, zero or more times

 

 

 

 

Subpattern Capturing

( (red|white) (King|Queen) )
$1 $2 $3
  1. Outer brackets values are captured to $1
  2. First inner brackets are assigned to $2
  3. Second inner brackets are assigned to $3

Should be assigned to another variable, since they are destroyed after the match

RegEx Matching, Replacing, Splitting

Matching using the preg_match() function. Requires the pattern to be enclosed with delimiters, usually /, followed by the target string and an optional 3rd parameter for storing found matches.

 

preg_match("/pattern/", target, match) ;

Displays:

Found: simply

 

 

Replacing using the preg_replace() ; function. Requires the pattern to be enclosed with delimiters, usually /, followed by the replacement string, then the target string and an optional 4th parameter specifying how many replacements

 

preg_replace("/pattern/", replace, target, limit) ;

Displays:

If you can't explain it in plain English, you don't understand it well enough.

 

 

Splitting using the preg_split() ; function. Requires the pattern to be enclosed with delimiters (usually / ), followed by the replacement string, then the target string and an optional 4th parameter specifying how many replacements.

 

Returns an array of items that did NOT match the regex pattern

 

preg_split("/pattern/", replace, target, limit) ;

 

This example uses a regex to split the string by any number of commas or space characters:

Displays:

Array
(
    [0] => If
    [1] => you
    [2] => can't
    [3] => explain
    [4] => it
    [5] => simply
    [6] => you
    [7] => don't
    [8] => understand
    [9] => it
    [10] => well
    [11] => enough.
)

 

 

Similar to the above, the preg_grep() function returns an array of items, but this time those that matched the regex pattern:

Displays:

Array
(
    [1] => Yamaha
    [3] => Suzuki
)

External Commands / Programs

Used to execute external programs (e.g. system commands)

Take at least one parameter: the command /program to be executed

 

exec() runs the command/program and sends back the last line output from that program as its return value.

 

exec( "command", $output, $return ) ;

 

Optional parameters:

2nd parameter will contain the output of the command as an array with one line per element

3rd parameter contains the return value of the command

 

 

passthru() runs the command/program and displays all of the raw output directly to the screen

 

passthru( "command", $return ) ;

 

Optional parameters:

2nd parameter contains the return value of the command

 

 

 

system() runs the command/program and displays the raw output directly to the screen

 

system( "command", $return ) ;

 

mysql_connect()

To connect to a database, a connection handle (common name for the array containing the connection variables) must be assigned from the mysql_connect() function:

 

$connectionHandle = mysql_connect( $server, $user, $passwd ) ;

 

$server, $user, $passwd can be set in php.ini, though more common to include from separate file, e.g.:

 

This can now be called from the connecting script:

mysql_error()

Returns a text error message upon failure of the previous MySQL operation.

 

In this example, a wrong value is used to provide the error message:

Displays:

Error connecting to the database!
Access denied for user 'root'@'localhost' (using password: YES)

 

 

*Note: the die() function prints an error message (required) and exits the script. Synonym of the exit() function.

mysql_select_db()

Once a connection to the database server has been established, a specific database must be selected by passing the database name as the first parameter into the mysql_select_db() function:

 

mysql_select_db( 'databaseName', connectio) ;

 

*Note: If the (optional) second parameter, connection, is omitted, the last opened connection by mysql_connect will be used.

 

 

The database is now ready to be acted upon.

mysql_query()

Queries upon the database can be made once a connection to the database server has been established and a specific database has been selected.

 

This is performed by sending a query as a parameter into the mysql_query() function, that returns a result set which is assigned to an array variable:

 

$query = 'SELECT * FROM customers' ;  //where customers is the table being queried

 

$resultSetmysql_query( $query, $connection ) ;

 

 

In this example, the result set is now ready to be viewed / acted upon.

 

Alternative queries to INSERT, UPDATE or DELETE data are also carried with the mysql_query() function.

mysql_fetch_array()

Once a query has been made and the result set has been assigned to an array variable, we are now able to view the results.

 

Since the result set is returned as an array, we need to traverse through the array by passing this array variable as a parameter in to the mysql_fetch_array() function.

 

mysql_fetch_array( $resultSet, MYSQL_ASSOC ) ;

 

*Note: An optional second parameter of MYSQL_ASSOC or MYSQL_NUM specifies either an associative or numerical indexed array. Or, by NOT including the optional second parameter the default MYSQL_BOTH parameter is used to work upon either associative or numerical indexes in subsequent array traversals.

* alternatively, the mysql_fetch_assoc() function provides an associative array.

 

The advantage of using associative arrays, is that the field names can be used whilst looping through the array

Displays:

CustID: 1, First: Pam, Surname: Frost, Age: 21
CustID: 2, First: James, Surname: Cross, Age: 20
CustID: 3, First: Andy, Surname: Jones, Age: 34

 

MySQL Insert, Update, Delete data

Insert, Update, Delete all use the mysql_query() to act upon the connected database.

 

The difference is in the construction of the MySQL query that is being sent to the database.

 

Just as if the query was run from the command line, a new query (even a view / select) must be run for each operation:

 

Displays:

Here's the initial data:
CustID: 1, First: Pam, Surname: Frost, Age: 21
CustID: 2, First: James, Surname: Cross, Age: 20
CustID: 3, First: Andy, Surname: Jones, Age: 34 

 

Insert data
CustID: 1, First: Pam, Surname: Frost, Age: 21
CustID: 2, First: James, Surname: Cross, Age: 20
CustID: 3, First: Andy, Surname: Jones, Age: 34
CustID: 41, First: Vanessa, Surname: Loopy, Age: 44

 

Update data
CustID: 1, First: Pam, Surname: Frost, Age: 21
CustID: 2, First: James, Surname: Cross, Age: 20
CustID: 3, First: Andy, Surname: Jones, Age: 34
CustID: 41, First: Vanessa, Surname: Strange, Age: 44

 

Delete data
CustID: 1, First: Pam, Surname: Frost, Age: 21
CustID: 2, First: James, Surname: Cross, Age: 20
CustID: 3, First: Andy, Surname: Jones, Age: 34

Output Buffering

Stores the output of the page into a buffer, before being instructed to flush it's content to screen.

 

HTML is generally output directly as the page is processed in the order data appears on the page. However, this can be slow due to many smaller chunks of data having to be processed and their order being dictated within the page.

 

Output buffering overcomes these issues by processing the whole page, storing it in a buffer and then sending it when instructed.

 

 

To begin an output buffering use the ob_start() function, preferably as early as possible.

 

The page is then processed and all data is sent to an output buffer in memory.

 

At the end of the script use the ob_end_flush() function to send the data accumulated in the output buffer to the browser (this is also automatically carried out if not otherwise stated).

 

The ob_end_clean() function can be used to clean the output buffer without sending the data.

 

Both ob_end_flush and ob_end_clean turn off output buffering when called.

 

Using ob_start() to store the data into the output buffer and ob_end_flush() to deliver its content:

Simply ending the script has the same effect:

 

Using the ob_end_clean() function loses the data in the output buffer:

Authentication

Using the $_SERVER superglobals array PHP_AUTH_USER and PHP_AUTH_PW values and the header() function to provide a Username/Password popup window.

 

The header() function sends a header request to the browser, requesting an authentication dialog on the client's browser.

 

Upon submission of the credentials, the URL containing the PHP script will be called again with the predefined variables from the $_SERVER array:

  • PHP_AUTH_USER
  • PHP_AUTH_PW
  • AUTH_TYPE

 

Authentication must come before any other HTML output

MySQLi / MySQL Improved

MySQLi provides an updated version of the MySQL functions, designed to take advantage of newer PHP features.

 

The following focuses upon procedural techniques. Object Oriented database concepts are covered in Object Oriented PHP.

 

The MySQLi functions are more or less the same as the MySQL functions, with some subtle differences.

 

The main MySQLi functions are:

  • mysqli_connect(server, user, pass, database) //note new 4th parameter defining the database
  • mysqli_select_db($handle, database) //first parameter $handle required!
  • mysqli_connect_error() //just for connection errors
  • mysqli_error($handle) //for query errors
  • mysqli_query($handle, $query) //first parameter $handle required!
  • mysqli_fetch_array($resultSet) //pass through while loop
  • mysqli_num_rows($resultSet)
  • mysqli_free_result($resultSet)
  • mysqli_close($handle)

This example follows on from the previous MySQL example, but uses the MySQLi functions: