Successfully reported this slideshow.

PHP Powerpoint -- Teach PHP with this



Upcoming SlideShare
PHP7. Game Changer.
PHP7. Game Changer.
Loading in …3
1 of 354
1 of 354

More Related Content

Related Books

Free with a 14 day trial from Scribd

See all

PHP Powerpoint -- Teach PHP with this

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