-
Basics
-
Syntax
-
Punctuation
- Terminate code statements with a semi-colon (;)
- Use appropriate tags
-
Tags
- <?php ... ?>
- <script language="php"> ... </script>
-
Comments
- // ...
- /* ... */
-
Arithmetic Operators
- + (adding)
- - (subtracting)
- * (multiplying)
- / (dividing)
- % (modulus)
-
Bitwise Operators
- AND &
- OR |
- EITHER-OR ^
- Shift bits << x or >> x
- Negate bits ~
-
Assignment Operators
- Assign =
- Assign (arrays) =>
-
Short Forms
- $a += 1 equals to $a = $a + 1
- $a .= 'World!';
- Increase / Decrease ++ --
-
Comparison Operators
- Equality ==
- Inequality !=
- Identical ===
- Unidentical !==
- > < >= <=
-
Array Operators
- Union +
- Equal ==
- Identical ===
- Not equal !=
- Not equal <>
- Not identical !==
-
Logical Operators
- and
- or
- xor
- not (!)
- && (and)
- || (or)
-
Execution Operators
- `command`
- shell_exec();
- Operators
-
Variables
-
Naming
- start with $
- letters, numbers, and underscores
- case-sensitive
-
Referencing
- assigned by value
- assigned by reference (&)
-
Initializing
- check with isset()
-
Control Structures
-
Conditions
- if
- else
- elseif (else if)
-
if-else (ternary operator)
- (expression) ? value_if_true : value_if_false
- switch
-
Loops
- while
- do-while
- for
- foreach
- continue
- break
-
Language Constructs & Functions
-
Output Constructs
- die(), exit()
- echo(), print()
- return()
-
Evaluation Constructs
- empty()
- eval()
-
include(), include_once()
- failure in execution leads to a warning
-
require(), require_once()
- failure in execution leads to a fatal error
-
Other Constructs
-
isset()
- determine wheter a variable has been set (not null)
-
unset()
- use to unset the variable
-
list()
- use to assign a group of variables in one step
-
Constants
-
Naming
- start with a letter or underscore
- case-sensitive
- by convention use only uppercase letters
-
Access
- defined and eaccessed anywhere
- must be defined before use
- cannot be changed subsequently
-
Predefined Constants
-
"Magic" Constants
- __XXX__
- can change depending upon where used
- E_ERROR, TRUE, FALSE, ...
-
Namespaces
-
Use
- prevent accidentally re-defining functions, classes, etc.
- avoids having to use long class names
- constants, classes, and functions are affected by the use of namespaces
- sub-namespaces to sub-divide a library
-
Declaring Namespaces
- namespace at the beginning of the code file
- one namespace per code file
- unless a namespace is defined => global space
- "\" => global space
- Subtopic 5
-
Importing / Aliasing Namespaces
- "use" operator
- can create aliases
-
Extensions & AJAX
-
PECL
- added to the php.ini
-
Core Extensions
- part of the php core
- arrays, objects, ...
-
Userland Rules
- Global Namespace Constructs
-
Internal Naming
- functions use underscores between words
- classes use the cameCase rule
- double underscore prefix is reserved
-
Configuration
-
php.ini
- configuration file for php
- file run upon server starting
-
search order
- sapi
- phprc
- Registry
- Working Directory
- Directory
- Win Directory
-
user.ini
- processed by CGI/FastCGI SAPI
- PHP_INI_PERDIR or PHP_INI_USER
-
controlled by directives
- user_ini.filename
- user.cache_ttl
-
Settings
- ini_set() -> php.ini / httpd.conf
-
Performance
-
Factors Affecting Performance
- reduced memory usage
- run-time delays
- Garbage Collection
-
Data types & formats
-
XML Basics
- Extensible Markup Language
-
XML Extension
-
Create a XML parser
- xml_parser_create()
- xml_parser_create_ns()
- xml_set_element_handler()
-
Character encodings
-
Source encoding
- conducted at time of parsing
- cannot be changed during parser lifetime
- types
- UTF-8
- US-ASCII
- ISO-8859-1
-
Target encoding
- conducted at time of php passing data to xml handlers
- can be changed at any time
- Characters not capable of source encoding cause an error
- Characters not capable of target encoding are demoted to "?"
-
SimpleXML
-
Concept
- elements become object properties
- attributes can be accessed via associative arrays
-
Functions
- $xml = simplexml_load_string('<?xml ...');
- $xml = simplexml_load_file('file.xml');
- $xml = new SimpleXMLElement('<?xml..');
-
Xpath
- query language used to select nodes within an XML document
-
xpath('//');
- executes the query
- Web Services Basics
-
SOAP
- Simple Object Access Protocoll
-
REST
-
Definition
- Representational State Transfer
- uses only HTTP
- stateless
- exposes URIs
- transfers XML, JSON, or both
-
REST uses HTTP "verbs"
- GET - list
- GET - resource
- POST - create
- PUT - update
- DELETE - delete
-
JSON & AJAX
-
Definition
- JavaScript Object Notation
- data-interchange format
-
Functions
- json_decode()
- json_encode()
- json_last_error()
-
Date & Time
-
Runtime Configuration
- date.default_latitude
- date.timezone
-
DOM
- uses UTF-8 encoding
-
simplexml_import_dom()
- converts DOM node into a SimpleXML object
-
dom_import_simplexml()
- converts a SimpleXML object into a DOM
-
Strings & patterns
-
Quoting
- delimited by single or double quotes
- single quotes '
- double quotes "
-
Comparing
-
==
- sets up comparison
- including data type conversion
-
===
- sets up comparison
- data type check
- strcasecmp()
- strcmp()
-
similar_text()
- similarity of two strings
- returns the number of matching chars
-
levenshtein()
- Levenshtein distance between strings
-
Extracting
-
explode()
- converts a string into an array
-
implode()
- converts an array into a string
-
Substrings
- string substr ( string $string , int $start [, int $length ] )
- returns a substring position
-
Formatting
-
output
- printf()
- sprintf()
- vprintf()
- vsprintf()
- fprintf()
-
characters
- binary (%b)
- decimal (%d)
- float (%f)
- octal (%o)
- scientific notation (%e)
- string (%s)
- n digits (%nd)
- n decimal places (%.nf)
-
Regular expressions
- POSIX-RegEx
-
PCRE
- Perl Compatible Regular Expression
-
Delimiter
- "/", "#", "!"
- used at the beginning and end
-
Boundaries
- start of a line (^)
- end of a line ($)
- start of a string (\A)
- end of a string (\Z)
-
Character classes
- [..]
- built-in classes
- \d
- \D
-
Quantifiers
- 0 or more (*)
- 1 or more (+)
- 0 or 1 (?)
- combination of ? with * or + makes non-greedy
-
Heredoc & Nowdoc
-
Nowdoc Syntax
- <<< 'IDENTIFIER'
- IDENTIFIER;
- parsing is conducted
-
Heredoc Syntax
- no need to escape
- <<< IDENTIFIER
- IDENTIFIER;
- do not indent ending identifier or add any chars
-
Matching
-
Locating strings
- int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
-
Counting strings
- strlen()
- str_word_count()
-
Phonetic functions
- soundex()
- metaphone()
-
Arrays
-
Enumerated Arrays
- $x = array('a', 'b', 'c');
- $y = array(0 => 'a', 1 => 'b', 2 => 'c');
- indexed numerically
-
Associative Arrays
- indexed with strings
- $x = array('xml' => 'eXtensible Markup Language');
-
Array Operations
-
Filling Arrays
- range();
- default step is "1"
- $x = range(1.2, 4.1);
-
Splitting Arrays
- array array_slice ( array $array , int $offset [, int $length [, bool $preserve_keys = false ]] )
- negative offset means count from the end of the array
- negative length exlude elements x positions from the end of the array
- x = array(1, 2, 3, 4, 5);
- $y = array_slice($x, - 4, - 1); // array(2, 3, 4)
-
Adding Elements
- int array_push ( array &$array , mixed $var [, mixed $... ] )
- alternatively $n[] = 5;
- int array_unshift ( array &$array , mixed $var [, mixed $... ] )
-
Removing Elements
-
mixed array_pop ( array &$array )
- remove 1 element at the end of an array
- return value is the removed element
-
mixed array_shift ( array &$array )
- remove 1 element at the beginning of an array
- remaining elements are moved towards the front
- return value is the removed element
-
Array Iteration
-
for
- loop and indices
- for ($i = 0; $i < count($a); $i++) { print $a[$i]; }
-
foreach
- loop and value
- loop and keys and values
- array_walk();
-
Array Functions
-
Checking For Array Values
- bool array_key_exists ( mixed $key , array $search )
- bool in_array ( mixed $needle , array $haystack [, bool $strict ] )
- array array_keys ( array $input [, mixed $search_value [, bool $strict = false ]] )
- array array_values ( array $input )
-
Sorting Arrays
- bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
- rsort()
- asort()
- arsort()
- ksort()
- krsort()
- usort()
- natsort()
-
Merging Arrays
- array array_merge ( array $array1 [, array $array2 [, array $... ]] )
-
Comparing Arrays
- array_diff($x, $y)
- array_diff_assoc()
- array_diff_uassoc()
- array_diff_key()
- array_diff_ukey
-
Input/Output
-
Files
-
f*();
- work with a file resource
- fopen();
-
file*();
- functions that work with a filename
- file_get_contents();
-
Filesystem Functions
-
resource fopen ( string $filename , string $mode [, int $use_include_path [, resource $zcontext ]] )
- create a resource
-
string fread ( resource $handle , int $length )
- read from resource
-
int fwrite ( resource $handle , string $string [, int $length ] )
- write into resource
- int fputs ( resource $handle , string $str [, int $length ] )
-
int fpassthru ( resource $handle )
- ouput all data of a file handle directly to the output buffer
-
Streams
-
Parts of a data stream
- wrapper
- pipelines
- context
- meta data
-
Wrappers
- file://
- http://
- https://
- ftp://
- ftps://
- compress.bzip2://
- compress.zlib://
- php://
-
Custom wrappers
- stream_wrapper_register(protocol, classname);
-
Contexts
- additional information for a stream
- stream_context_create();
- stream_context_set_params();
- stream_context_get_options();
-
Filesystem
-
Directory
-
chdir()
- changes the directory
-
chroot()
- changes the root directory
-
readdir()
- reads an entry from the directory handle
-
rmdir()
- deletes a directory
-
File Information
-
finfo_open()
- create a new fileinfo-resource
-
finfo_file()
- returns information about a file
-
Filesystem
-
basename()
- returns filename component of a path
-
chmod()
- changes the file mode
-
copy()
- copies a file
-
delete()
- deletes a file
-
file_exists()
- checks if a file or directory exists
-
rename()
- moves/renames a file
-
unlink()
- deletes a file
-
Filters
-
can be applied to stream data
- resource stream_filter_append ( resource $stream , string $filtername [, int $read_write [, mixed $params ]] )
-
can create custom filters
- bool stream_filter_register ( string $filtername , string $classname )
-
Functions
-
Syntax
- case-insensitive
- global scope
- can be referenced before being defined
-
types
- built-in
- user-defined
- externally provided
-
declaration
- parameters and return value optional
- set param default to avoid warning
-
Arguments
-
func_num_args()
- number of parameters
-
func_get_arg(nr)
- parameter value number nr
-
func_get_args()
- all parameters as an array
- argument list is a set of comma-delimited expression
-
pass arguments
-
by value (default)
- creates copy
- argument changes extend only within function
-
by reference
- & to supply parameters by reference
-
Variable Functions
- work like variable variables
- variables followed by parentheses causes search for, and execution of, function with the same name
- used for callbacks, function tables
-
Returns
- return()
- ends function execution
- will return values that include arrays, objects, function references (using &)
-
Variable Scope
- variables declared within functions only visible in that function
- variables declared outside of functions can be made visible within a function using "global"
-
Closures
- functions without a name
- used for callback functions
- to inherit variables from parent scope (function in which closure was declared), these variables must be declared in function header
-
OOP
-
Objects
-
converting to strings
- __toString()
-
called whenever a string is expected
- print
- string interpolation
- operation with strings
- calling function that expect strings
-
copying objects
- keyword: clone
- objects are always passed by reference
- shallow cloning by default
- __clone()
-
serializing objects
-
functions
- serialize()
- unserialize()
-
__sleep() is executed with serialization
- allows you to specify which properties should be stored
- can also create/change properties
-
__wakeup() is executed with deserialization
- open a database connection for example
-
Instantiation
- keyword: new
- an object is created unless it has a constructor defined that throws an exception with an error
- assigning an existing instance of a class to a new variable => reference
-
Class Definition
- keyword: class
- defines the abstract characteristics of an object
- properties and methods are called "members"
-
structure
- class CLASSNAME { CONSTANTS, PROPERTIES & METHODS }
-
Constructors / Destructors
-
__construct()
- used with new objects as preparation for initialization
-
__destruct()
- close open handles
- called whenever an object is destroyed
-
Properties
- also called attributes
- visibility keywords: public, protected, private
-
must be with a constant value
- nowdocs can be used to initialize a property
-
Class Constants
- a special entity that remains fixed on an individual class basis
- no $ symbol
- $classname::CONSTANT
- ClassName::$varConstant
-
Methods
- set of procedural statements
- default visibility is public
- context-object -> $this
-
Static Methods & Properties
- keyword: static
-
operator: ::
- token that permits access to the static, constant, or overridden properties / methods of a class
- self:: refers to the current class
- parent:: refers to the parent of the current class
- no instantiation required
- CLASSNAME::$varMethod
-
Magic Methods
- __get() reads a property
- __set() writes a property
- __isset() check if the property is set
- __unset() unsets or destroys a property
- __call accessing non-existent methods
- __callStatic() calling of non-existent static methods
-
Late Static Binding
- used for retrieving the caller class information when static call to inherited method is made
-
Type Hinting
-
data types
- classes
- arrays
- if the data type does not match => fatal error
- class type matches exactly or extendedly
-
Reflection
-
allows for introspection of
- objects
- classes
- methods
- properties
- functions
- parameters
- exceptions
- extensions
-
Autoload
- __autoload()
- called whenever there is an attempt to use a class or interface that has not been defined
- spl_autoload() is used as an implementation for __autoload()
-
Exceptions
- keyword: throw
-
catch with try ... catch
- may also wait for specific exceptions
- type my be an exception extended from another
- custom exceptions need to extend the base Exception class
-
Interfaces
- keyword: interface, implements
- provides methods to implement
- no implementations!
- derived classes my implement more than one interface
- interfaces may inherti from other interfaces (keyword: extends)
- methods are public
-
Inheritance
- keyword: extends
- a class can inherit from only one class
- inherited methods and properties can be overridden by redeclaring them with the same name
- child classes cannot override a parent property or method using a lower visibility
- classes and methods marked with final cannot be overridden
-
Abstract Classes
- keyword: abstract
- provides a skeleton for a class
- my contain implementations
- abstract methods must be implemented in derived classes
-
Databases
-
SQL
-
Create a database table
- CREATE TABLE tblname ( ... )
-
Read data
- SELECT field1, field2 FROM tblname WHERE field3 = 'desiredValue'
- SELECT * FROM tblname ORDER BY field1 ASC
- SELECT * FROM tblname ORDER BY field1 DESC
- SELECT field1, field2 FROM tblname GROUB BY field1
-
Insert data
- INSERT INTO tblname (field1, field2, field3) VALUES ('V1', 'V2', 3);
-
Update data
- UPDATE tblname SET field1 = 'valueNew1', field2 = 'valueNew2' WHERE field3 = 'valueOld3'
-
Delete data
- DELETE FROM tblname WHERE field1 = 'value1'
- DROP TABLE tblname
- DROP DATABASE dbname
-
Joins
- Inner join
- Left join
- Right join
-
Prepared Statements
-
advantages
- query only parsed once
- multiple executions with same or different parameters
- better performance
-
Transactions
- combines individual SQL operations into one
- usually start with BEGIN or BEGIN TRANSACTION
- execute the transaction using COMMIT
- cancel the transaction using ROLLBACK
-
PDO
- PHP Data Objects Extension
- data-access abstraction layer
- must use database-specific PDO adapter to access a db server
-
operations
- create an instance of the PDO class
- PDOStatement PDO::query ( string $statement )
-
transactions
- PDO::beginTransaction()
- PDO::commit()
- PDO::rollBack()
-
PDOStatement
- only values can be bound
- PDO::prepare()
- PDOStatement::execute()
-
Keys
- Primary Key: column of unique values that describe an entry in the data table
- Foreign Key: primary key from another table; enables relational databases
-
Aggregation
- average value AVG()
- number of elements COUNT()
- number of distinct elements DISTINCT COUNT()
- minimal value MIN()
- maximal value MAX()
- sum of values SUM()
-
Security
-
Configuration
-
General settings
- register_globals set to OFF
- display_errors set to OFF
- log_errors set to ON
- allow_url_include set to OFF
- error_reporting = E_ALL & ~E_DEPRECATED
-
Filesystem security
- only allow limited permissions to the apache web user binary
- check all variables submitted
-
Sessions
-
Session hijacking
- occurs when the session id is stolen
- session id is the sole authentication token for the whole web site
-
Session fixation
- occurs when user gets a fixed session id
-
Counter-measures
- regenerate the session ID upon login
- use SSL encryption for the login or assign a hidden key
- check that the ip address remains the same
- session_regenerate_id() before "critical" operations
- use short session timeout
- provide user logout
- destroy the original session by passing TRUE (session_regenerate_id(true);)
- session.use_only_cookies ON
-
Cross-Site-Scripting
-
Description
- injection of HTML, CSS, or script code into a page
-
JavaScript is particularly dangerous
- redirect the user
- modify the page
- read out cookies
-
Counter-measures
-
escape all data before outputting it
- htmlspecialchars()
- htmlentities()
- strip_tags()
-
Cross-Site Request Forgeries
-
Description
- creates HTTP requests
- attacker employs user's browser to execute requests on the attacker's behalf
-
Counter-measures
- use unique token in the form
- re-login before sensitive operations
-
SQL injections
-
Description
- SQL code is injected into the SQL query
- allows attacker to do almost anything the database user is permitted
-
Counter-measures
- use prepared statements
- escape all data
-
Remote Code Injection
-
Description
- run the attacker's code on a user's machine
-
Include file attacks
- possible from remote servers
- includes remote code execution
-
Counter-measures
- check data against a whitelist
- remove paths using basename()
- set allow_url_fopen = Off in php.ini
- do note use system()
- escapeshell*()
-
Email injection
- make sure not to provide open relays
- open the smtp prot only if essential
-
Input filtering
- use the same charset for filtering as the target procedure
- convert charsets prior to filtering
- use filters
-
Escaping output
- 1) filter and validate all input
- 2) escape output
- 3) never rely on client side filtering
-
Encryption, hashing, algorithms
-
Password security
- do not save passwords in cleartext
-
use hash values
- md5() / 32 characters, hexadecimal
- sha1() / 40 characters, hexadecimal
-
File uploads
-
file name can be forged
- use checks and basename()
-
MIME can be forged
- ignore
-
temp file name can be forged under certain conditions
- use *_uploaded_file() functions
-
Web Features
-
Sessions
-
Definition
- way of preserving data across a series of web site accesses by the user
- session support is enabled by default
- SID(string) is a pre-defined constant for this extension
-
Session ID
- user assigned a unique identifier
- session id is stored in a cookie on the client or in the url
-
site access by user triggers session id check
- session.auto_start = 1
- session_start()
- $_SESSION (super global)
- enable session.use_only_cookies for data protection
-
Session Functions
- session_cache_expire() return current cache expire
- session_destroy() destroys all data registers to a session
- session_id() get/set current session id
- session_start() initialize session data
-
Forms
-
General
- form elements are automatically available to PHP scripts
-
form data can be made into an array
- <input name"array[]" />
- dots (.) and spaces ( ) are converted to underscores (_)
-
Superglobal Arrays
- $_POST
- $_GET
- $_REQUEST ($_POST/$_GET/$_COOKIE)
- $_FILES
-
Cookies
-
create cookies with setcookie() or setrawcookie()
- must be called before sending any output
- can delay script output using output buffering
-
access with $_COOKIE or $_REQUEST
- cookies are part of the HTTP header
- to assign all values to only one cookie, can use serialize() or explode() with first value
-
HTTP Headers and Code
-
header()
- sets an http header
-
headers_list()
- list of headers sent or to be sent; indexed array
- headers_sent()
- header_remove()
-
Header Codes
- 1XX Informational
- 2XX Successful
- 3XX Redirection
- 4XX Error (Client)
- 5XX Error (Server)
-
HTTP Authentication
- PHP_AUTH_USER User
- PHP_AUTH_PW Password
- AUTH_TYPE Authentication type