1 / 55

Lecture 9 Introduction to PHP

Lecture 9 Introduction to PHP. Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU. Server-side Web-scripting is mostly about connecting web-sites to back-end servers such as databases. This enables two way communication:

Download Presentation

Lecture 9 Introduction to PHP

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lecture 9Introduction to PHP Presented By Dr. ShazzadHosain Asst. Prof. EECS, NSU

  2. Server-side Web-scripting is mostly about connecting web-sites to back-end servers such as databases. This enables two way communication: Server to client: Web-pages can be assembled from back-end server output; Client to Server: Customer-entered information can be acted upon. See next page for data flow in server-side scripting. Server-side Scripting

  3. Server-side Scripting (cont’d)

  4. What do You Need? • Where to Start? • Install an Apache server on a Windows or Linux machine. Or IIS on wndows. • Install PHP on a Windows or Linux machine • Install MySQL on a Windows or Linux machine • Or, Install XAMPP/WAMP to get all-in-one solution • PHP + MySQL • PHP combined with MySQL are Cross-platform (means that you can develop in Windows and serve on a Unix platform), Open source, Compatible with leading web servers, Faster and Truly Portable.

  5. Introduction to PHP

  6. PHP Tag Styles – The good… • XML Style: <?php print “this is XML style”; ?> • Short Style: <? print “this is ASP style”; ?> • To use Short style the PHP you are using must have “short tags” enabled in its config file… this is almost always the case.

  7. Comments • Why do we go on about comments so much? • because without them, marking would hurt our heads. <? //C style comment #perl style comment /* C++ multi line comment */ ?>

  8. PHP is for Lazy People • You know that means you! Don’t need to work with types and conversions. • Basic data types • numbers (integers and real) • strings(Double-quoted "abc“ and single-quoted 'abc') • booleans (true,false ) • Dynamic typing • Don't have to declare types • Automatic conversion done • all variables in PHP are denoted with a leading dollar sign ($); • variables have default values.

  9. Variables in action <? $x = false;         // boolean type $x = true; $x = 10;         // decimal $x = 1.45;         // Floating point $x = 0x1A;         // hexadecimal  $x = "mmm\"oo'oo\n";     // mmm"oo'oo  and a new line $x = 'mmm"oo\'oo\n';     // string = mmm"oo'oo\n $y = &$x         // Reference $x[1] = 10         // array of decimals $x["name"] = “jimbo";    // associative array $x[2]["lala"] = "xx";    // a two dimensional array ?>

  10. Assigning variables: $pi = 3 + 0.14159 // approximately Re-assigning variables: $my_num_var = “it is not a number”; $my_num_var = 5; Unassigned variables: PHP ensures that variables have default values (they can be printed unassigned). Variables (cont’d)

  11. Checking assignment with IsSet: $set_var = 0; //set_var has a value //never_set does not if (IsSet($set_var)) print(“set_var has a value. <BR>”); if (IsSet($never_set)) print(“never_set has a value. <BR>”); else print(“never_set has no value. <BR>”); If you use an unset variable, system will complain. Variables (cont’d)

  12. Switching Modes Using the arrow-question mark tag we can quickly switch modes <? if(strstr($HTTP_USER_AGENT,"MSIE")) { ?> <b>You are using Internet Explorer</b> <? } else { ?><b>You are not using Internet Explorer</b> <? } ?> Here we are in PHP-mode Here we have flicked back to HTML again

  13. Variable Scope • The 3 basic types of scope in PHP is: • Global variables declared in a script are visible throughout that script, but not inside functions • Variables used inside functions are local to the function • Variables used inside functions that are declared as global refer to the global variable of the same name

  14. Operators • Arithmetic Operators:+, -, *, / , %, ++, -- • Assignment Operators:=, +=, -=, *=, /=, %= • Comparison Operators:==, !=, >, <, >=, <= • Logical Operators:&&, ||, ! • String Operators: . , .= Example Is the same as x+=y x=x+y x-=y x=x-y x*=y x=x*y x/=y x=x/y x%=y x=x%y $a = "Hello "; $b = $a . "World!"; //now $b contains "Hello World!" $a = "Hello "; $a .= "World!";

  15. For printing to output we can use: echo - to print a string as argument. echo “This prints in the browser.”; or echo(“This prints in the browser.”); or echo “This prints”, “in the browser.”; Note that echo will also work with the string concatenation operator . as: echo “This prints” . “in the browser.”; or echo(“This prints” . “in the” . “browser.”); but echo(“This causes a”, “PARSE ERROR!”); Output- echo

  16. print - is very similar to echo, with two important differences: can accept only one argument; returns a value, which represents whether the print statement succeeded; returned value 1 means that printing was successful; returned value 0 means that printing was unsuccessful. Example: print(“3.14159”); //print a string print(3.14159); //print a number numbers are converted to strings before they are printed. Output- print (cont’d)

  17. variables and strings $animal = “Antelope”; $heads = 1; $legs = 4; print(“$animal has $heads head(s). <BR>”); print(“$animal has $legs leg(s). <BR>”); Output Antelope has 1 head(s). Antelope has 4 leg(s). Use single quotes to print directories print(‘C:\newcode\myphp.php’); Output (cont’d)

  18. HTML and line breaks C programmers be aware that the new line character “\n” is not the same as “<BR>”; \n prints a new line in the HTML code generated, while <BR> prints a new line on the browser; what is the HTML and browser output of the statement: print(“Is this only \n\n one line? <BR>”); (left as an exercise). Output (cont’d)

  19. Simple String functions chr - Return a specific character ord - Return ASCII value of character sprintf - Return a formatted string strlen - Get string length strpos - Find position of first occurrence of a string strrev - Reverse a string strtolower - Make a string lowercase strtoupper - Make a string uppercase str_replace - Replace all occurrences of the search string with the replacement string

  20. PHP Control Statements • Just for the record what’s the same as C++/Java? • For Loops • While Loops • If Statements • Break, Continue, Exit, Switch, etc. • The main concepts which differ in syntax are: • Functions • Classes

  21. If – exists • You often need to check whether a variable exists in PHP. • There are two ways to do this… if ($a){ print “\$a exists"; }else{ print “\$a exists"; } if (!empty($a)){ print “\$a exists"; }else{ print “\$a exists"; }

  22. Conditionals: if else <html><head></head> <body> <?php $d=date("D"); if ($d =="Fri") echo "Have a nice weekend! <br/>"; else echo "Have a nice day! <br/>"; $x=10; if ($x==10) { echo "Hello<br />"; echo "Good morning<br />"; } ?> </body> </html> if (condition) code to be executed if condition istrue; else code to be executed if condition isfalse; date() is a built-in function that can be called with many different parameters to return the date (and/or local time) in various formats In this case we get a three letter string for the day of the week.

  23. Conditionals: switch <html><head></head> <body> <!–- switch-cond.php --> <?php $x = rand(1,5); // random integer echo “x = $x <br/><br/>”; switch ($x){ case 1: echo "Number 1"; break; case 2: echo "Number 2"; break; case 3: echo "Number 3"; break; default: echo "No number between 1 and 3"; } ?> </body> </html> switch (expression) { case label1: code to be executed if expression = label1; break; case label2: code to be executed if expression = label2; break; default: code to be executed if expression is different from both label1 and label2; }

  24. <html><head></head> <body> <?php $i=0; do { $i++; echo "The number is $i <br />"; } while($i <= 10); ?> </body> </html> <html><head></head> <body> <?php $i=1; while($i <= 5) { echo "The number is $i <br />"; $i++; } ?> </body> </html> loops through a block of code if and as long as a specified condition is true loops through a block of code once, and then repeats the loop as long as a special condition is true Looping: while and do-while Can loop depending on a condition

  25. <?php $a_array = array(1, 2, 3, 4); foreach ($a_array as $value) { $value = $value * 2; echo “$value <br/> \n”; } ?> <?php $a_array=array("a","b","c"); foreach($a_array as $key=>$value) { echo $key." = ".$value."\n"; } ?> loops through a block of code for each element in an array Looping: for and foreach Can loop depending on a "counter" <?php for ($i=1; $i<=5; $i++) { echo "Hello World!<br />"; } ?> loops through a block of code a specified number of times

  26. PHP Functions • Functions in PHP are not case sensitive. • Be careful of this because variable naming is case sensitive function my_function() { print “My function was called”; } • Functions can be created anywhere in your PHP code • However good style demands they should always be at the top of your code

  27. Do what is neatest… <? Function my_function() { print “My function was called”; } ?> <? Function my_function() { ?> My function was called <? } ?> IS IDENTICAL TO…

  28. Passing Parameters • As normal you don’t have to specify the types of your parameters... • Be careful of this because variable naming is case sensitive function display_table($data){ print “<TABLE>”; for ($i=0; $i<sizeof($data); $i++) print “<TR><TD> $data[$i] </TD></TR>”; print “</TABLE>”; }

  29. Defaults & Passing by Reference • As with other languages you can set defaults. PHP requires that you do specify the correct number of parameters in a call. • Equally you don’t have to pass by value – an ampersand will mean the variable is passed by reference and so any changes to it are global: function increment(&$value, $amount=1) { $value = $value + $amount; }

  30. Example… function larger($x, $y) { if ($x > $y) return $x; if ($x < $y) return $y; if ($x == $y) return “x and y have the same value”; }

  31. <?php $a = 1; $b = 2; function Sum() { global $a, $b; $b = $a + $b; } Sum(); echo $b; ?> <?php function Test() { static $a = 0; echo $a; $a++; } Test(); Test(); Test(); ?> global refers to its global version. static does not lose its value. Variable Scope <?php $a = 1; /* global scope */ function Test() { echo $a; /* reference to local scope variable */ } Test(); ?> The scope of a variable is the context within which it is defined. The scope is local within functions.

  32. Arrays in PHP are associative, i.e. values of elements are stored in association with the key values, rather than a strict linear order. /* Direct assignment: create array $state_loc, and assign location with key = ‘San Mateo’ equal to ‘California’ */ $state_loc[‘San Mateo’]= ‘California’; //…later assign ‘California’ to $state $state = state_loc[‘San Mateo’]; Arrays in PHP

  33. The array() construct $fruit_basket = array(‘apple’,‘banana’); which can also be written as: $fruit_basket[1] = ‘apple’; $fruit_basket[2] = ‘banana’; or (almost) equivalent to: $fruit_basket[] = ‘apple’; //here indices start $fruit_basket[] = ‘banana’; //from 0 (not 1). Arrays (cont’d)

  34. Specifying indices using array() $fruit_basket = array(0 =>‘apple’, 1 =>‘banana’ ); We could also write: $fruit_basket = array(‘red’ =>‘apple’, ‘yellow’ =>‘banana’ ); Arrays (cont’d)

  35. Multi-dimensional arrays as arrays with elements that are arrays themselves. $basket[0][0] = ‘apple’; $basket[0][1] = ‘banana’; $basket[1][0] = ‘rose’; $basket[1][1] = ‘tulip’; Arrays (cont’d)

  36. Alternatively: $basket = array(0 => array(0 => ‘apple’, 1 => ‘banana’ ), 1 => array(0 => ‘rose’, 1 => ‘tulip’) ) ); Arrays (cont’d)

  37. Or, for a more meaningful version: $basket = array(‘fruits’ => array(‘red’ => ‘apple’, ‘yellow’ => ‘banana’ ), ‘flowers’ => array(‘red’ => ‘rose’, ‘violet’ => ‘tulip’) ) ); Arrays (cont’d)

  38. The program: $kind = ‘flower’; $colour = ‘red’; print(“You want a {$basket[$kind][$colour]}.”); Outputs: You want a rose. Arrays (cont’d)

  39. the list() construct is the inverse of array(), since array() packages its arguments into an array, and list() takes the array apart again into individual variable assignments. $fruits = array(‘apple’, ‘banana’, ‘orange’); list($red, $yellow) = $fruits; print(“The $red is red and the $yellow is yellow.<BR>”); Output: The apple is red and the banana is yellow. The list() construct

  40. Merging Arrays • array_merge() $fruits = array("apples", "oranges", "pears"); $vegetables = array("potatoes", “onions", "carrots"); $newarray = array_merge($fruits, $vegetables); $howmany = count($newarray); print "$howmany"; // will output 6 to the screen

  41. Accessing Array Elements <?php $vegetables = array("potatoes", “onions", "carrots"); for ($i=0; $i< count($vegetables); $i++) { print "$vegetables[$i]<br>\n"; } ?>

  42. each() function $vegetables = array("potatoes", “onions", "carrots"); for ($i=0; $i< count($vegetables); $i++) { $Line = each($vegetables); print "$Line[key] is $Line[value]<br>\n"; }

  43. Array Functions (the boring ones) count - Count elements in a variable sizeof - Get the number of elements in variable array_pop - Pop the element off the end of array array_push - Push one or more elements onto the end of array array_shift - Shift an element off the beginning of array array_search - Searches the array for a given value and returns the corresponding key if successful sort - Sort an array into numerical order

  44. …er.. The exciting ones? array_reverse - Return an array with elements in reverse order array_flip - Flip all the values of an array keys become values array_unique - Removes duplicate values from an array array_values - Return all the values of an array array_sum - Calculate the sum of values in an array. extract – converts arrays to scalar variables array_rand - Pick 1 or more random entries from the array shuffle – randomly reorders the elements in an array

  45. Constants • A constant is an identifier (name) for a simple value. A constant is case-sensitive by default. • By convention, constant identifiers are always uppercase. <?php // Valid constant names define("FOO", "something"); define(“MAX", 100); define(“PI", 3.14159); // Invalid constant names define("2FOO", "something"); You can access constants anywhere in your script without regard to scope.

  46. Exploding Strings • Not a new firework but rather a way of breaking a string down and putting it into an array. • And its useful, especially if you are doing anything with cookies. $email = “info@cs.nsu.edu”; $email_array = explode(“@”, $email); $domains = explode(“.”, $email_array[0]); • Implode() reverses the process. $domain[0] = “cs” $domain[1] = “nsu” $domain[2] = “edu”

  47. Changing Case • Most people who use your sites will be muppets. (although your sites for HLL will probably only be viewed by members of staff so draw your own conclusions). • Whatever you tell them to do, they won’t enter data in the format you wantand this will matter. Login names are classic examples of this. • Imagine someone types “aStOn VillA” into a field… Strtoupper() Strtolower() Ucfirst() Ucwords() Turns string to uppercase Turns string to lowercase Capitalises first character Capitalises every word ASTON VILLA aston villa Aston villa Aston Villa

  48. Problem Characters • Some characters cause you no end of problems. • Specifically ‘ and “. • For example if you have a field asking for a name and someone sends you back: Ronnie O’Sullivan, consider the following code: Print ‘Welcome to the site $name’; Print ‘Welcome to the site Ronnie O’Sullivan’; • We need a way of marking, or escaping these characters so that databases such as mysql can understand we meant a literal character.

  49. Adding Slashes • To do this escaping normally you just add a \ (backslash). This can be very painful to do manually. AddSlashes() a function to do it for you. StripSlashes() reverses the process. • So if a user typed in: You said to me that “you don’t give guarantees” • $userInput = AddSlashes($userInput) You said to me that \“you don\’t give guarantees\”.

  50. Crypt • crypt() will encrypt a string that you give it. • This is especially useful for encrypting items such as passwords. • This then cannot be reversed – but you can encrypt another string that is entered and then compare it with the stored encrypted string. • You should always encrypt your users access information if its privacy is essential.

More Related