PHP

2,110 views

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
2,110
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
40
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

PHP

  1. 1. PHP & MySQL Christos Efstratiou
  2. 2. Architecture Web Browser Web Server Request Page Page with PHP code Read File PHP Interpreter Pass PHP page and server variables (GET attributes, Server settings, etc.) Generate HTML page Send HTML page MySQL Interact with Database
  3. 3. PHP Syntax <ul><li>In general PHP code is embedded into web pages </li></ul><ul><li>In most cases you will have pages that contain only PHP code </li></ul><ul><li>Pages with PHP code should have the extension: .php, .php3, .php4 </li></ul><ul><li>Examples: </li></ul><? $name = “World” ; ?> <html> <body> <h1>Hello, <? echo $name ; ?> </h1> </body> </html> <? include ( “header.html” ); if ( strpos ( $_SERVER[ “HTTP_USER_AGENT” ] , “MSIE” ) !== FALSE ) { echo “You are using Internet explorer!”; } include ( “footer.html” ); ?>
  4. 4. PHP Syntax - Variables <ul><li>PHP does not support explicit type definition. </li></ul>$foo  =   &quot;0&quot; ;     // $foo is string (ASCII 48) $foo  +=  2 ;     // $foo is now an integer (2) $foo  =  $foo  +  1.3 ;    // $foo is now a float (3.3) <ul><li>You can enforce a variable type by using type casting. </li></ul>$foo  =   1 0 ;     // $foo is  an integer $ bar   =   (boolean) $foo ;     //  $bar is boolean (true) <ul><li>Comparing values. </li></ul>$ x   =  0 ;     $ y   =   false ; if ( $ x == $ y ) //  this is true <ul><li>Comparing values and types. </li></ul>$ x   =  0 ;     $ y   =   false ; if ( $ x = = = $ y ) //  this is not true, different types
  5. 5. PHP Syntax - Strings <ul><li>There are two main ways of specifying strings </li></ul><ul><li>Using single quotes: text represented exactly as typed </li></ul>$ str   =   ‘This is an example’ ;     //  is not expanded to new line <ul><li>Using double quotes: expands variables and supports special characters </li></ul>$ val   =   5 ;   $ str   =   “The value is: $var ” ;   //  The string is: “The value is: 5” with a new line at the end   <ul><li>Concatenation with a “dot” </li></ul>$ val   =   5 ;   $ str   =   ‘The ’ . ‘value is: ’ . $var . “ ” ;   <ul><li>Single characters in a string </li></ul>$ str{2} = ‘T’ ;   //  The third character of string
  6. 6. PHP Syntax - Arrays <ul><li>PHP arrays are dynamic. Their size expands as needed. </li></ul><ul><li>PHP supports associative arrays: Array indices can be of any type not just integers. Key types can be mixed in the same array. </li></ul>$arr[1] = ‘Test’ ;   // Using integers as keys $arr [ ‘first’ ] = ‘Test’ ; // Using strings as keys $arr = array( &quot;foo&quot;   =>   &quot;bar&quot; ,   12   =>   true ); $arr[5] = 10 ; // The array is now: (“foo”=> “bar”, 12=>true, 5=>10) <ul><li>Defining arrays </li></ul><ul><li>Multidimensional arrays </li></ul>$arr = array( “first&quot;   =>   array( &quot;bar&quot; ,   ‘Test’ ), “ second&quot;   =>   array( 1   =>   true ,   2   =>   false ) ) ;
  7. 7. PHP Syntax - Control Structures <ul><li>All the control structures you would find in C </li></ul><ul><ul><li>If (…) {…} elseif (…) {…} else {…} </li></ul></ul><ul><ul><li>while(…) {…} </li></ul></ul><ul><ul><li>for (…;…;…) {…} </li></ul></ul><ul><ul><li>do {…} while (…) </li></ul></ul><ul><ul><li>switch (...) { case …: …; case …: …; default: …; } </li></ul></ul><ul><li>foreach : used for traversing associative arrays </li></ul>$foo  =  array( “Nigel” => “nigel@comp.lancs.ac.uk” , “ Chris” => “efstrati@comp.lancs.ac.uk” , “ Rob” => “r.hooper@lancaster.ac.uk” , “ Oliver” => “stortz@comp.lancs.ac.uk” ); foreach ( $foo as $name => $email ) { echo “<p>Name: $name <br/>” ; echo “Email: $email </p>” ; }
  8. 8. PHP Syntax - Functions <ul><li>Function definition </li></ul><? function  foo ( $arg_1 ,  $arg_2 ,  /* ..., */  $arg_n ) {     echo  &quot;Example function. &quot; ;     return  $retval ; } ?> <ul><li>Global variables are only accessible if declared in a function </li></ul><? $ g val = 5 ; // Global variable function  foo () { global $ g val ; // The function has now access to the global var (by reference)      echo  “ Gval: $ g val . &quot; ; } ?>
  9. 9. Pointers & pass by reference <ul><li>All value assignments in PHP are “by copy”, even when working with arrays or objects. </li></ul><ul><li>There are no explicit pointer variables but you can assign variables by reference. </li></ul>$foo  =  'Bob' ;               // Assign the value 'Bob' to $foo $bar  = & $foo ;               // Reference $foo via $bar. $bar  =  &quot;My name is $bar&quot; ;   // Alter $bar... echo  $foo ;                  // $foo is altered too. <ul><li>Passing function parameters by reference and returning references </li></ul>function & add_some_extra (& $string ) { $string .= “ some more &quot; ;  return $string ; } $foo =& add_some_extra ( $str );
  10. 10. Classes <ul><li>Support for object orientation in PHP has improved with version 4 and is much more substantial in version 5. </li></ul>class  Cart  {     var  $items ;   // Items in our shopping cart     // Add $num articles of $artnr to the cart     function  add_item ( $artnr ,  $num ) {          $this -> items [ $artnr ] +=  $num ;     } } $ myC art  = new  Cart ;  $ myCart -> myVar = “ test &quot; ;   //  This object has a new attribute not defined by the class <ul><li>Inheritance with the “extends” keyword </li></ul>class  Named_Cart  extends  Cart  { ………     }
  11. 11. Serialization <ul><li>Serialization is supported through functions “serialize” and “unserialize” </li></ul>   include( &quot;classa.inc&quot; );       $a  = new  A ;    $s  =  serialize ( $a );    // store $s somewhere    $fp  =  fopen ( &quot;store&quot; ,  &quot;w&quot; );    fwrite ( $fp ,  $s );    fclose ( $fp ); include( &quot;classa.inc&quot; );    $s  =  implode ( &quot;&quot; ,  file ( &quot;store&quot; ));    $a  =  unserialize ( $s );    // now use the object.      $a -> show_one ();
  12. 12. OO support in Version 5 <ul><li>PHP v5 has an extended support for OO. </li></ul><ul><li>Supports variable and function scopes using “ public ”, “ protected ”, “ private ” keywords. </li></ul><ul><li>Supports static (class based) methods and variables. </li></ul><ul><li>Supports abstract classes, similar to virtual classes in C++. </li></ul><ul><li>Supports the definition of interfaces. </li></ul><ul><li>Includes a complete Reflection API </li></ul><ul><li>Includes an exception handling mechanism </li></ul><ul><li>From more info check the online manual: http://www.php.net/manual/en/ </li></ul>
  13. 13. Programming techniques Separate code from GUI <ul><li>The idea is to have separate HTML/CSS files to handle the user interface and php files to handle the application’s operation. </li></ul><ul><li>Use of templates (template support is provided by PhpLib). </li></ul><ul><li>Nested templates can be used to break the UI into blocks. E.g. one template for the main page, a nested template for a content block within the main page. </li></ul>
  14. 14. Programming techniques Template example <html> <head><title> {PAGETITLE} </title></head> <body> <table> <tr><td colspan=“2”> <h1> {PAGETITLE} </h1></td></tr> <tr> <td> {OUT} </td> <td>Content</td> </tr> </table> </body> </html> include(“template.inc”) $tpl = new Template(“mytemplates/”); // Create template object $tpl->set_file(“MainPage”, “mainPage.html”); // Load the template file $tpl->set_var(“PAGETITLE”, “My Page”); // Assign values to variables $tpl->set_var(“OUT”, “Test content”); $tpl->parse(“Output”, “MainPage”); // Parse page into variable Output $tpl->p(“Output”); // Print the Output var mainPage.html index.php
  15. 15. Programming techniques Template example <html> <head><title> My Page </title></head> <body> <table> <tr><td colspan=“2”> <h1> My Page </h1></td></tr> <tr> <td> Test content </td> <td>Content</td> </tr> </table> </body> </html> include(“template.inc”) $tpl = new Template(“mytemplates/”); // Create template object $tpl->set_file(“MainPage”, “mainPage.html”); // Load the template file $tpl->set_var(“PAGETITLE”, “My Page”); // Assign values to variables $tpl->set_var(“OUT”, “Test content”); $tpl->parse(“Output”, “MainPage”); // Parse page into variable Output $tpl->p(“Output”); // Print the Output var mainPage.html index.php
  16. 16. Programming techniques Template example 2 <html> <head><title> {PAGETITLE} </title></head> <body> <table> <tr><td colspan=“2”> <h1> {PAGETITLE} </h1></td></tr> <tr> <td> {OUT} </td> <td>Content</td> </tr> </table> </body> </html> <!– start box --> <table> <tr> <td colspan=“2”><b> {TITLE} </b></td> </tr> <!– BEGIN row --> <tr> <td> {NUM} </td> <td> {BIGNUM} </td> </tr> <!– END row --> </table> <!– end box --> include(&quot;./template.inc&quot;); $t = new Template(&quot;/page/to/webserver/template&quot;, &quot;keep&quot;); // define variables named page and box, referencing files $t->set_file(array( &quot;page&quot; => &quot;page.ihtml&quot;, &quot;box&quot; => &quot;box.ihtml&quot;)); // define variable TITLE and PAGETITLE $t->set_var(array(&quot;TITLE&quot; => &quot;Testpage&quot;, &quot;PAGETITLE&quot; => “ test &quot;)); # extract the block &quot;row&quot; from &quot;box&quot;, creat e a reference to {rows}&quot;. $t->set_block(&quot;box&quot;, &quot;row&quot;, &quot;rows&quot;); # define NUM and BIGNUM, then append &quot;row&quot; to &quot;rows&quot;... for ($i=1; $i<=3; $i++) { $n = $i; $nn = $i*10; $t->set_var(array(&quot;NUM&quot; => $n, &quot;BIGNUM&quot; => $nn)); $t->parse(&quot;rows&quot;, &quot;row&quot;, true); } # build out from box, then build out put from page... $t->parse(&quot;OUT&quot;, &quot;box“ ); $t->parse(“Output” , &quot;page&quot;)); # finish out and print it. $t->p(&quot;OUT&quot;); ?>
  17. 17. Programming techniques Template example 2 <html> <head><title> test </title></head> <body> <table> <tr><td colspan=“2”> <h1> test </h1></td></tr> <tr> <td> {OUT} </td> <td>Content</td> </tr> </table> </body> </html> <!– start box --> <table> <tr> <td colspan=“2”><b> Testpage </b></td> </tr> <!– BEGIN row --> <tr> <td> {NUM} </td> <td> {BIGNUM} </td> </tr> <!– END row --> </table> <!– end box --> include(&quot;./template.inc&quot;); $t = new Template(&quot;/page/to/webserver/template&quot;, &quot;keep&quot;); // define variables named page and box, referencing files $t->set_file(array( &quot;page&quot; => &quot;page.ihtml&quot;, &quot;box&quot; => &quot;box.ihtml&quot;)); // define variable TITLE and PAGETITLE $t->set_var(array(&quot;TITLE&quot; => &quot;Testpage&quot;, &quot;PAGETITLE&quot; => “ test &quot;)); # extract the block &quot;row&quot; from &quot;box&quot;, creat e a reference to {rows}&quot;. $t->set_block(&quot;box&quot;, &quot;row&quot;, &quot;rows&quot;); # define NUM and BIGNUM, then append &quot;row&quot; to &quot;rows&quot;... for ($i=1; $i<=3; $i++) { $n = $i; $nn = $i*10; $t->set_var(array(&quot;NUM&quot; => $n, &quot;BIGNUM&quot; => $nn)); $t->parse(&quot;rows&quot;, &quot;row&quot;, true); } # build out from box, then build out put from page... $t->parse(&quot;OUT&quot;, &quot;box“ ); $t->parse(“Output” , &quot;page&quot;)); # finish out and print it. $t->p(&quot;OUT&quot;); ?>
  18. 18. Programming techniques Template example 2 <html> <head><title> test </title></head> <body> <table> <tr><td colspan=“2”> <h1> test </h1></td></tr> <tr> <td> {OUT} </td> <td>Content</td> </tr> </table> </body> </html> <!– start box --> <table> <tr> <td colspan=“2”><b> Testpage </b></td> </tr> {rows} </table> <!– end box --> include(&quot;./template.inc&quot;); $t = new Template(&quot;/page/to/webserver/template&quot;, &quot;keep&quot;); // define variables named page and box, referencing files $t->set_file(array( &quot;page&quot; => &quot;page.ihtml&quot;, &quot;box&quot; => &quot;box.ihtml&quot;)); // define variable TITLE and PAGETITLE $t->set_var(array(&quot;TITLE&quot; => &quot;Testpage&quot;, &quot;PAGETITLE&quot; => “ test &quot;)); # extract the block &quot;row&quot; from &quot;box&quot;, creat e a reference to {rows}&quot;. $t->set_block(&quot;box&quot;, &quot;row&quot;, &quot;rows&quot;); # define NUM and BIGNUM, then append &quot;row&quot; to &quot;rows&quot;... for ($i=1; $i<=3; $i++) { $n = $i; $nn = $i*10; $t->set_var(array(&quot;NUM&quot; => $n, &quot;BIGNUM&quot; => $nn)); $t->parse(&quot;rows&quot;, &quot;row&quot;, true); } # build out from box, then build out put from page... $t->parse(&quot;OUT&quot;, &quot;box“ ); $t->parse(“Output” , &quot;page&quot;)); # finish out and print it. $t->p(&quot;OUT&quot;); ?> <!– Box row --> <tr> <td> {NUM} </td> <td> {BIGNUM} </td> </tr>
  19. 19. Programming techniques Template example 2 <html> <head><title> test </title></head> <body> <table> <tr><td colspan=“2”> <h1> test </h1></td></tr> <tr> <td> {OUT} </td> <td>Content</td> </tr> </table> </body> </html> <!– start box --> <table> <tr> <td colspan=“2”><b> Testpage </b></td> </tr> {rows} </table> <!– end box --> include(&quot;./template.inc&quot;); $t = new Template(&quot;/page/to/webserver/template&quot;, &quot;keep&quot;); // define variables named page and box, referencing files $t->set_file(array( &quot;page&quot; => &quot;page.ihtml&quot;, &quot;box&quot; => &quot;box.ihtml&quot;)); // define variable TITLE and PAGETITLE $t->set_var(array(&quot;TITLE&quot; => &quot;Testpage&quot;, &quot;PAGETITLE&quot; => “ test &quot;)); # extract the block &quot;row&quot; from &quot;box&quot;, creat e a reference to {rows}&quot;. $t->set_block(&quot;box&quot;, &quot;row&quot;, &quot;rows&quot;); # define NUM and BIGNUM, then append &quot;row&quot; to &quot;rows&quot;... for ($i=1; $i<=3; $i++) { $n = $i; $nn = $i*10; $t->set_var(array(&quot;NUM&quot; => $n, &quot;BIGNUM&quot; => $nn)); $t->parse(&quot;rows&quot;, &quot;row&quot;, true); } # build out from box, then build out put from page... $t->parse(&quot;OUT&quot;, &quot;box“ ); $t->parse(“Output” , &quot;page&quot;)); # finish out and print it. $t->p(&quot;OUT&quot;); ?> <tr> <td> 1 </td> <td> 10 </td> </tr>
  20. 20. Programming techniques Template example 2 <html> <head><title> test </title></head> <body> <table> <tr><td colspan=“2”> <h1> test </h1></td></tr> <tr> <td> {OUT} </td> <td>Content</td> </tr> </table> </body> </html> <!– start box --> <table> <tr> <td colspan=“2”><b> Testpage </b></td> </tr> {rows} </table> <!– end box --> include(&quot;./template.inc&quot;); $t = new Template(&quot;/page/to/webserver/template&quot;, &quot;keep&quot;); // define variables named page and box, referencing files $t->set_file(array( &quot;page&quot; => &quot;page.ihtml&quot;, &quot;box&quot; => &quot;box.ihtml&quot;)); // define variable TITLE and PAGETITLE $t->set_var(array(&quot;TITLE&quot; => &quot;Testpage&quot;, &quot;PAGETITLE&quot; => “ test &quot;)); # extract the block &quot;row&quot; from &quot;box&quot;, creat e a reference to {rows}&quot;. $t->set_block(&quot;box&quot;, &quot;row&quot;, &quot;rows&quot;); # define NUM and BIGNUM, then append &quot;row&quot; to &quot;rows&quot;... for ($i=1; $i<=3; $i++) { $n = $i; $nn = $i*10; $t->set_var(array(&quot;NUM&quot; => $n, &quot;BIGNUM&quot; => $nn)); $t->parse(&quot;rows&quot;, &quot;row&quot;, true); } # build out from box, then build out put from page... $t->parse(&quot;OUT&quot;, &quot;box“ ); $t->parse(“Output” , &quot;page&quot;)); # finish out and print it. $t->p(&quot;OUT&quot;); ?> <tr> <td> 1 </td> <td> 10 </td> </tr> <tr> <td> 2 </td> <td> 20 </td> </tr>
  21. 21. Programming techniques Template example 2 <html> <head><title> test </title></head> <body> <table> <tr><td colspan=“2”> <h1> test </h1></td></tr> <tr> <td> {OUT} </td> <td>Content</td> </tr> </table> </body> </html> <!– start box --> <table> <tr> <td colspan=“2”><b> Testpage </b></td> </tr> <tr> <td> 1 </td> <td> 10 </td> </tr> <tr> <td> 2 </td> <td> 20 </td> </tr> </table> <!– end box --> include(&quot;./template.inc&quot;); $t = new Template(&quot;/page/to/webserver/template&quot;, &quot;keep&quot;); // define variables named page and box, referencing files $t->set_file(array( &quot;page&quot; => &quot;page.ihtml&quot;, &quot;box&quot; => &quot;box.ihtml&quot;)); // define variable TITLE and PAGETITLE $t->set_var(array(&quot;TITLE&quot; => &quot;Testpage&quot;, &quot;PAGETITLE&quot; => “ test &quot;)); # extract the block &quot;row&quot; from &quot;box&quot;, creat e a reference to {rows}&quot;. $t->set_block(&quot;box&quot;, &quot;row&quot;, &quot;rows&quot;); # define NUM and BIGNUM, then append &quot;row&quot; to &quot;rows&quot;... for ($i=1; $i<=3; $i++) { $n = $i; $nn = $i*10; $t->set_var(array(&quot;NUM&quot; => $n, &quot;BIGNUM&quot; => $nn)); $t->parse(&quot;rows&quot;, &quot;row&quot;, true); } # build out from box, then build out put from page... $t->parse(&quot;OUT&quot;, &quot;box“ ); $t->parse(“Output” , &quot;page&quot;)); # finish out and print it. $t->p(&quot;O utput &quot;); ?>
  22. 22. Programming techniques Template example 2 <html> <head><title> test </title></head> <body> <table> <tr><td colspan=“2”> <h1> test </h1></td></tr> <tr> <td> <table> <tr> <td colspan=“2”><b>Testpage</b></td> </tr> <tr> <td>1</td> <td>10</td> </tr> <tr> <td>2</td> <td>20</td> </tr> </table> </td> <td>Content</td> </tr> </table> </body> </html> include(&quot;./template.inc&quot;); $t = new Template(&quot;/page/to/webserver/template&quot;, &quot;keep&quot;); // define variables named page and box, referencing files $t->set_file(array( &quot;page&quot; => &quot;page.ihtml&quot;, &quot;box&quot; => &quot;box.ihtml&quot;)); // define variable TITLE and PAGETITLE $t->set_var(array(&quot;TITLE&quot; => &quot;Testpage&quot;, &quot;PAGETITLE&quot; => “ test &quot;)); # extract the block &quot;row&quot; from &quot;box&quot;, creat e a reference to {rows}&quot;. $t->set_block(&quot;box&quot;, &quot;row&quot;, &quot;rows&quot;); # define NUM and BIGNUM, then append &quot;row&quot; to &quot;rows&quot;... for ($i=1; $i<=3; $i++) { $n = $i; $nn = $i*10; $t->set_var(array(&quot;NUM&quot; => $n, &quot;BIGNUM&quot; => $nn)); $t->parse(&quot;rows&quot;, &quot;row&quot;, true); } # build out from box, then build out put from page... $t->parse(&quot;OUT&quot;, &quot;box“ ); $t->parse(“Output” , &quot;page&quot;)); # finish out and print it. $t->p(&quot;OUT&quot;); ?>
  23. 23. Programming techniques Template example 2 <html> <head><title> test </title></head> <body> <table> <tr><td colspan=“2”> <h1> test </h1></td></tr> <tr> <td> <table> <tr> <td colspan=“2”><b> Testpage </b></td> </tr> <tr> <td> 1 </td> <td> 10 </td> </tr> <tr> <td> 2 </td> <td> 20 </td> </tr> </table> </td> <td>Content</td> </tr> </table> </body> </html> Content test 30 3 20 2 10 1 Testpage
  24. 24. Interacting with the user <ul><li>Calling a web page (simple  ) </li></ul><ul><li>URL parameters e.g. http://www.com/mypage.php?a=alpha&b=beta </li></ul><ul><li>Forms, either through GET or POST methods </li></ul><ul><li>A php script can gain access to parameters passed by user through two built in variables: </li></ul><ul><ul><li>$_GET </li></ul></ul><ul><ul><li>$_POST </li></ul></ul><ul><li>URL parameters example. The values are specified in the $_GET variable as: </li></ul>$_GET = array(“a”=>”alpha”, “b”=>”beta”);
  25. 25. Handling Forms
  26. 26. Handling Forms <form method=“ post ” action=“index.php”> <input type=“hidden” name=“ id ” value=“100” /> <table> <tr> <td>User</td> <td><input type=“text” name=“ user ” /></td> </tr> <tr> <td>Password</td> <td><input type=“password” name=“ passwd ” /> </td> </tr> <tr> <td colspan=“2”> <input type=“submit” name=“ Login ” value=“Login” /> </td> </tr> </table> </form>
  27. 27. Handling Forms <form method=“ post ” action=“index.php”> <input type=“hidden” name=“ id ” value=“100” /> <table> <tr> <td>User</td> <td><input type=“text” name=“ user ” /></td> </tr> <tr> <td>Password</td> <td><input type=“password” name=“ passwd ” /> </td> </tr> <tr> <td colspan=“2”> <input type=“submit” name=“ Login ” value=“Login” /> </td> </tr> </table> </form> $ok = false; if (array_key_exists(“submit”, $_POST ) && ( $_POST [“submit”] == “Login”) ) { $ok = CheckLogin( $_POST [“id”], $_POST [“user”], $_POST [“passwd”]); } if ($ok) { include(“restrictedArea.html”); } else { include(“loginForm.html”); }
  28. 28. Handling Forms <form method=“ get ” action=“index.php”> <input type=“hidden” name=“ id ” value=“100” /> <table> <tr> <td>User</td> <td><input type=“text” name=“ user ” /></td> </tr> <tr> <td>Password</td> <td><input type=“password” name=“ passwd ” /> </td> </tr> <tr> <td colspan=“2”> <input type=“submit” name=“ Login ” value=“Login” /> </td> </tr> </table> </form> $ok = false; if (array_key_exists(“submit”, $_ GET ) && ( $_ GET [“submit”] == “Login”) ) { $ok = CheckLogin( $_GET [“id”], $_GET [“user”], $_GET [“passwd”]); } if ($ok) { include(“restrictedArea.html”); } else { include(“loginForm.html”); }
  29. 29. Handling Forms <ul><li>Protection from user input. Data received by a form should not be trusted. </li></ul><ul><li>Functions that remove html code from source data </li></ul><ul><ul><li>htmlspecials ( $str ) : convert HTML special characters to HTML entities (e.g. &quot;). </li></ul></ul><ul><ul><li>html_entity_decode ( $str ) : reverse, convert entities to HTML characters. </li></ul></ul><ul><ul><li>striptags ( $str ) : remove HTML and PHP tags from a string. </li></ul></ul><ul><li>Validate input using regular expressions </li></ul><ul><ul><li>example: validate an e-mail address </li></ul></ul>$ret = ereg ( ‘^([a-z0-9_]||)+@(([a-z0-9_]|)+)+[a-z]{2,4}$’ , $string );
  30. 30. Sessions <ul><li>HTTP communication is inherently stateless </li></ul><ul><li>The way to handle state information is through cookies. </li></ul><ul><li>PHP offers a built in mechanism for maintaining session information (hiding the cookie handling from the developer) </li></ul>
  31. 31. Sessions <ul><li>session_start() creates a session or resumes the current one being passed via a cookie. </li></ul><ul><li>$_SESSION this array is used for assigning session variables or retrieving existing ones </li></ul><ul><li>session_destroy() ends an existing session (e.g. when you logout). </li></ul>
  32. 32. Sessions <? // Login page session_start(); // Process the login form …………………… // Login is completed $_SESSION[‘user’] = $_POST[‘user’]; $_SESSION[‘passwd’] = $_POST[‘passwd’]; // Redirect to the private page header(&quot;Location:  ”. ” http:// www.server.com/nextpage.php” ); ?> <? // next page session_start(); // Check login user if (!array_key_exists(“user”, $_SESSION)) { // No user logged in echo “You need to login first”; exit(); } echo “Hello “. $_SESSION[“user”] .”!<br/>”; ?>
  33. 33. Sessions <ul><li>With sessions you can assign an arbitrary number of data to the $_SESSION variable. </li></ul><ul><li>The data is stored on the server side and only a session id is passed through cookies to the web client. </li></ul><ul><li>You can manage the timeout of sessions as you would with any cookie. </li></ul>
  34. 34. Authentication <ul><li>It is simple to implement authentication through sessions. </li></ul><ul><li>The main advantage compared to HTTP authentication is that username and password are transmitted only once (login) and not in every request. </li></ul><ul><li>Permissions are handled by your code and do not rely on directories. </li></ul><ul><li>The general approach is to save the username and password in the session and check on every page that they are the correct ones. If not redirect to the login page. </li></ul>
  35. 35. MySQL <ul><li>Limittations of MySQL </li></ul><ul><ul><li>Does not support transactions. Cancelling groups of actions should be implemented by the developer. </li></ul></ul><ul><ul><li>Does not support referential integrity. Needs to be done programmatically </li></ul></ul><ul><ul><li>Does not support nested selections. There are ways to overcome this but they are not very efficient. </li></ul></ul><ul><li>But in general it’s a reliable database.  </li></ul>
  36. 36. MySQL management <ul><li>The tool that you would mostly use is MySQLAdmin. A Web frond end for database management. </li></ul><ul><li>You would use it for setting up databases, creating database users. </li></ul><ul><li>During development, you would use it for testing queries before importing them into your code. </li></ul><ul><li>You would use it for debugging the results of your application (did the insert command work alright?) </li></ul>
  37. 37. MySQL Interaction <ul><li>The interaction with MySQL server consists of the following steps: </li></ul><ul><ul><li>Connect to MySQL server. This requires a username and a password. </li></ul></ul><ul><ul><li>Select the active database. </li></ul></ul><ul><ul><li>Perform SQL queries and retrieve results. </li></ul></ul>
  38. 38. PHP Support for MySQL <ul><li>Connection </li></ul>$link = mysql_connect(“localhost”, “dbuser”, “dbpass”); If ($link == false) die(“Could not connect: “. mysql_error()); <ul><li>Database selection </li></ul>$link = mysql_select_db(“myDatabase”, $link); If ($link == false) die(“Could not select database: “. mysql_error()); <ul><li>Perform a query </li></ul>$query = “INSERT INTO contacts (name, email) VALUES (‘Chris’, ‘efstrati@comp.lancs.ac.uk’)”; $res = mysql_query($query, $link); If ($res == false) echo “Could not perform insert: “. mysql_error(); else { $userID = mysql_insert_id($link); echo “New user id: $userID”; }
  39. 39. MySQL retrieving results $query = “SELECT * FROM contacts”; $res = mysql_query($query, $link); while ($record = mysql_fetch_assoc($res)) { echo “Name: “.$record[‘name’].”, email: “.$record[‘email’].”<br/>”; } mysql_free_results($res); <ul><li>There are a number of ways for retrieving the results of a query. The most commonly used are </li></ul><ul><ul><li>mysql_fetch_assoc(): returns an associative array where the keys are the record field names. </li></ul></ul><ul><ul><li>mysql_fetch_object(): returns a record as an object. There are object attributes for each record field. </li></ul></ul>
  40. 40. MySQL & PHP: Things to remember <ul><li>Usually you would get the data that you put in your database from the user. Make sure that the data will not break your SQL queries. </li></ul><ul><ul><li>mysql_real_escape_string(): a useful function for escaping characters before using a string in an SQL query. </li></ul></ul>
  41. 41. Suggested reading <ul><li>Online Php Manual http://www.php.net/manual/en/index.php </li></ul><ul><li>Online MySQL Manual http://dev.mysql.com/doc/ </li></ul><ul><li>Web Application Development with PHP Tobias Ratschiller, Till Gerken New Riders Publishing </li></ul>

×