Introduction to PHP Part 2 1 Simple PHP

  • Slides: 62
Download presentation
Introduction to PHP Part #2 1

Introduction to PHP Part #2 1

Simple PHP Script • Consider the following HTML file, example. html: <html> <head> <title>My

Simple PHP Script • Consider the following HTML file, example. html: <html> <head> <title>My Page</title> </head> <body> Hello world!<p> </body> </html> 2

Simple PHP Script • Here is an equivalent PHP script. PHP files have the

Simple PHP Script • Here is an equivalent PHP script. PHP files have the extension “. php” and may contain both HTML and PHP code, which is enclosed inside <? code ? > tags, or alternately <? php code ? > <html> <head> <title>My Page</title> </head> <body> <? print(“hello world!<p>”); ? > </body> </html> 3

Simple PHP Script • More interesting version, displays the date as known by the

Simple PHP Script • More interesting version, displays the date as known by the server: <html> <head> <title>My Page</title> </head> <body> <? print(“hello world! Timestamp: “. time(). “<p>”); ? > </body> </html> 4

PHP Time Stamp • The “. ” is used to concatenate strings • The

PHP Time Stamp • The “. ” is used to concatenate strings • The server parses the document and interprets code within the <? ? > tags instead of sending it directly to the client – i. e. you can write code to output the HTML you desire • Output of previous: Refresh two Seconds later: hello world! Timestamp: 1050289182 hello world! Timestamp: 1050289184 5

PHP Script • Often everything is placed inside the PHP tags. The following is

PHP Script • Often everything is placed inside the PHP tags. The following is equivalent; the header function specifies the MIME Type; i. e. that the document is HTML (as opposed to graphics, etc. ): <? header("Content-Type: text/html"); print("<HTML><HEAD><TITLE>My Page</TITLE>"); print("</HEAD>"); print("<BODY>"); print("hello world! Timestamp: ". time(). "<p>"); print("</BODY></HTML>"); ? > 6

Identifiers and Data Types • Identifiers – Case-sensitive – Same rules as Java •

Identifiers and Data Types • Identifiers – Case-sensitive – Same rules as Java • Data Types – integer – double – string, surrounded by “ “ or by ‘ ‘ – Weak typing; you do not declare variables, just use them and the value assigned is the type of the variable; any old value is gone – Can typecast just like Java • (int), (double), (string), etc. 7

Variables • A variable is an identifier prefaced by $ • Example: $x =

Variables • A variable is an identifier prefaced by $ • Example: $x = 1; $y = 3. 4; $z = $x + $y; $a = true; $s = "hello!"; print ($z. " ". $a. " ". $s); Output: 4. 4 1 hello! Note: true = non zero or not empty. False = 0 or the empty string “” Common novice mistake: Forgetting the $ 8

Variables • Interpreted; consider the following: $x = 1; $y = “x”; print($y); Output:

Variables • Interpreted; consider the following: $x = 1; $y = “x”; print($y); Output: 1 • Often {} are used to denote variable boundaries: $x = 1; $y = “x”; print({$y}); 9

Form Variables • If an HTML form invokes a PHP script, the PHP script

Form Variables • If an HTML form invokes a PHP script, the PHP script can access all of the form variables by name • Invoking FORM: <form method=post action=“scr. php”> <input type=text name=“foo” value=“bar”> <input type=submit value=“Submit”> </form> • Inside scr. php: print($_REQUEST['foo']); // Outputs “bar” 10

Sample PHP Form <? header("Content-Type: text/html"); print("<HTML><HEAD><TITLE>My Page</TITLE>"); print("</HEAD>"); print("<BODY>"); print("foo = ". $_REQUEST[‘foo’].

Sample PHP Form <? header("Content-Type: text/html"); print("<HTML><HEAD><TITLE>My Page</TITLE>"); print("</HEAD>"); print("<BODY>"); print("foo = ". $_REQUEST[‘foo’]. ", bar = ". $_REQUEST[‘bar’]. "<P>"); print("<form method=post action="example. php">"); print("<input type=text name="foo" value="zot">"); print("<input type=hidden name="bar" value=3>"); print("<input type=submit>"); Note: ” escape character print("</form>"); Could also use ‘ instead print("</BODY></HTML>"); ? > 11

Sample PHP Form • First load: • Upon submit: 12

Sample PHP Form • First load: • Upon submit: 12

Web browser • What the web browser receives after the first load. Note that

Web browser • What the web browser receives after the first load. Note that we see no PHP code: <HTML> <HEAD><TITLE>My Page</TITLE> </HEAD> <BODY>foo = , bar = <P> <form method=post action="example. php"> <input type=text name="foo" value="zot"> <input type=hidden name="bar" value=3> <input type=submit></form></BODY></HTML> 13

GET and POST • One way to hide the printing of variables when the

GET and POST • One way to hide the printing of variables when the code is first loaded is to detect if the program is invoked via GET or POST <? header("Content-Type: text/html"); print("<HTML><HEAD><TITLE>My Page</TITLE>"); print("</HEAD>"); print("<BODY>"); if ($_SERVER['REQUEST_METHOD'] == ‘POST') { print("foo = ". $_REQUEST[‘foo’]. ", bar = ". $_REQUEST[‘bar’]. "<P>"); } print("<form method=post action="example. php">"); print("<input type=text name="foo" value="zot">"); print("<input type=hidden name="bar" value=3>"); print("<input type=submit>"); print("</form>"); print("</BODY></HTML>"); ? > 14

Operators • Same operators available as in Java: +, -, *, /, %, ++,

Operators • Same operators available as in Java: +, -, *, /, %, ++, -- (both pre/post) +=, -=, *=, etc. <, >, <=, >=, ==, !=, &&, ||, XOR, ! 15

Assignments • PHP will convert types for you to make assignments work • Examples:

Assignments • PHP will convert types for you to make assignments work • Examples: print(1 + "2"); // 3 print("3 x" + 10. 5); // 13. 5 $s = "hello". 55; print("$s<p>"); // hello 55 16

Arrays • Arrays in PHP are more like hash tables, i. e. associative arrays

Arrays • Arrays in PHP are more like hash tables, i. e. associative arrays – The key doesn’t have to be an integer • 1 D arrays – Use [] to access each element, starting at 0 – Ex: $arr[0] = “hello”; $arr[1] = “there”; $arr[2] = “zot”; $i=0; print(“$arr[$i] whats up!<p>”); // Outputs : hello whats up! 17

Arrays • Often we just want to add data to the end of the

Arrays • Often we just want to add data to the end of the array, we can do so by entering nothing in the brackets: $arr[] = “hello”; $arr[] = “there”; $arr[] = “zot”; print(“$arr[2]!<p>”); // Outputs : zot! 18

Array Functions • There are many array functions; here are just a few: count($arr);

Array Functions • There are many array functions; here are just a few: count($arr); // Returns # items in the array sort($arr); // Sorts array_unique($arr); // Returns $arr without duplicates print_r($var); // Prints contents of a variable // useful for outputting an entire array // as HTML in_array($val, $arr) // Returns true if $val in $arr 19

Multi-Dimensional Arrays • To make multi-dimensional arrays just add more brackets: $arr[0][0]=1; $arr[0][1]=2; $arr[1][0]=3;

Multi-Dimensional Arrays • To make multi-dimensional arrays just add more brackets: $arr[0][0]=1; $arr[0][1]=2; $arr[1][0]=3; . . etc. 20

Arrays with Strings as Key • So far we’ve only seen arrays used with

Arrays with Strings as Key • So far we’ve only seen arrays used with integers as the index • PHP also allows us to use strings as the index, making the array more like a hash table • Example: $fat[“big mac”] = 34; $fat[“quarter pounder”]=48; $fat[“filet o fish”]=26; $fat[“large fries”]=26; print(“Large fries have “. $fat[“large fries”]. “ grams of fat. ”); // Output : Large fries have 26 grams of fat Source: www. mcdonalds. com 21

Iterating through Arrays with foreach • PHP provides an easy way to iterate over

Iterating through Arrays with foreach • PHP provides an easy way to iterate over an array with the foreach clause: • Format: foreach ($arr as $key=>$value) { … } • Previous example: foreach($fat as $key=>$value) { print(“$key has $value grams of fat. <p>”); } Output: big mac has 34 grams of fat. quarter pounder has 48 grams of fat. filet o fish has 26 grams of fat. large fries has 26 grams of fat. 22

Foreach • Can use foreach on integers too: $arr[]="foo"; $arr[]="bar"; $arr[]="zot"; foreach ($arr as

Foreach • Can use foreach on integers too: $arr[]="foo"; $arr[]="bar"; $arr[]="zot"; foreach ($arr as $key=>$value) { print("at $key the value is $value "); } Output: at 0 the value is foo at 1 the value is bar at 2 the value is zot If only want the value, can ignore the $key variable 23

Control Statements • In addition to foreach, we have available our typical control statements

Control Statements • In addition to foreach, we have available our typical control statements – If – While – Break/continue – Do-while – For loop 24

IF statement • Format: if (expression 1) { // Executed if expression 1 true

IF statement • Format: if (expression 1) { // Executed if expression 1 true } elseif (expression 2) { // Executed if expression 1 false expresson 2 true } … else { // Executed if above expressions false } 25

While Loop • Format: while (expression) { // executed as long as expression true

While Loop • Format: while (expression) { // executed as long as expression true } 26

Do-While • Format: do { // executed as long as expression true // always

Do-While • Format: do { // executed as long as expression true // always executed at least once } while (expression); 27

For Loop • Format: for (initialization; expression; increment) { // Executed as long as

For Loop • Format: for (initialization; expression; increment) { // Executed as long as expression true } 28

Control Example Counts # of random numbers generated between 0 -10 srand(time()); // Seed

Control Example Counts # of random numbers generated between 0 -10 srand(time()); // Seed random # generator with time for ($i=0; $i<100; $i++) { $arr[]=rand(0, 10); // Random number 0 -10, inclusive } $i=0; while ($i<=10) { // Initialize array of counters to 0 $count[$i++]=0; } // Count the number of times we see each value foreach ($arr as $key=>$value) { $count[$value]++; } // Output results foreach ($count as $key=>$value) { print("$key appeared $value times. "); } 29

Output 0 appeared 9 times. 1 appeared 9 times. 2 appeared 11 times. 3

Output 0 appeared 9 times. 1 appeared 9 times. 2 appeared 11 times. 3 appeared 14 times. 4 appeared 6 times. 5 appeared 7 times. 6 appeared 8 times. 7 appeared 11 times. 8 appeared 5 times. 9 appeared 9 times. 10 appeared 11 times. 30

Functions • To declare a function: function_name(arg 1, arg 2, …) { // Code

Functions • To declare a function: function_name(arg 1, arg 2, …) { // Code // Optional: return (value); } Unlike most languages, no need for a return type since PHP is weakly typed 31

Function Example: Factorial function fact($n) { if ($n <= 1) return 1; return ($n

Function Example: Factorial function fact($n) { if ($n <= 1) return 1; return ($n * fact($n-1)); } print(fact(5)); // Outputs 120 32

Scoping • Variables defined in a function are local to that function only and

Scoping • Variables defined in a function are local to that function only and by default variables are pass by value function foo($x, $y) { $z=1; $x=$y + $z; print($x); } $x=10; $y=20; foo($x, $y); print(“$x $y<p>”); // Outputs 21 // Outputs 10 20 33

Arrays: Also Pass By Value function foo($x) { $x[0]=10; print_r($x); print("<p>"); } $x[0]=1; $x[1]=2;

Arrays: Also Pass By Value function foo($x) { $x[0]=10; print_r($x); print("<p>"); } $x[0]=1; $x[1]=2; $x[2]=3; print_r($x); print("<p>"); foo($x); print_r($x); print("<p>"); Array ( [0] => 10 [1] => 2 [2] => 3 ) Array ( [0] => 1 [1] => 2 [2] => 3 ) Not changed! 34

Pass by Reference • To pass a parameter by reference, use & in the

Pass by Reference • To pass a parameter by reference, use & in the parameter list function foo(&$x, $y) { $z=1; $x=$y + $z; print($x); } $x=10; $y=20; foo($x, $y); print(“$x $y<p>”); // Outputs 21 20 35

Dynamic Functions • Functions can be invoked dynamically too • Useful for passing a

Dynamic Functions • Functions can be invoked dynamically too • Useful for passing a function as an argument to be invoked later function foo() { print("Hi<p>"); } $x="foo"; $x(); // Outputs “Hi” 36

Classes & Objects • PHP supports classes and inheritance • All instance variables are

Classes & Objects • PHP supports classes and inheritance • All instance variables are public in PHP 4 (PHP 5 allows private, protected) • Format for defining a class; the extends portion is optional class name extends base-class { var. Name; … function name() {… constructor code …} function method. Name() { … code … } • To access a variable or function, use $obj->var (no $ in front of the var) • To access instance variables inside the class, use $this->var needed to differentiate between member var and a new local var 37

Class Example class user { var $name; var $password; function user($n, $p) { $this->name=$n;

Class Example class user { var $name; var $password; function user($n, $p) { $this->name=$n; $this->password=$p; } function get. Salary() { // if this was real, we might // look this up in a database or something return 50000; } } Output: Joe Schmo - secret 50000 $joe = new user("Joe Schmo", "secret"); print($joe->name. " - ". $joe->password. "<p>"); print($joe->get. Salary(). "<p>"); 38

Objects in PHP 4 • Assigning an object makes a new copy, not a

Objects in PHP 4 • Assigning an object makes a new copy, not a reference like Java: $joe = new user("Joe Schmo", "secret"); $fred = $joe; $joe->password = "a 4 j 1%"; print_r($joe); // user Object ( [name] => Joe Schmo [password] => a 4 j 1% ) print("<p>"); print_r($fred); // user Object ( [name] => Joe Schmo [password] => secret ) print("<p>"); 39

Objects in PHP 5 • Assigning an object makes a reference to the existing

Objects in PHP 5 • Assigning an object makes a reference to the existing object, like Java: $joe = new user("Joe Schmo", "secret"); $fred = $joe; $joe->password = "a 4 j 1%"; print_r($joe); // user Object ( [name] => Joe Schmo [password] => a 4 j 1% ) print("<p>"); print_r($fred); // user Object ( [name] => Joe Schmo [password] => a 4 j 1% ) print("<p>"); 40

Other new items in PHP 5 • Mostly improvements in OOP model – Abstract

Other new items in PHP 5 • Mostly improvements in OOP model – Abstract classes and methods – Destructors – Cloning – instanceof – Reflection 41

Using PHP • Here we will focus on additional functions that will be helpful

Using PHP • Here we will focus on additional functions that will be helpful for you to complete the homework assignment – Type Checking • is_array, is_string, is_long, is_double – Useful string functions • strlen, implode, explode, substr, strstr, trim, char access – File I/O • fopen, fread, feof, fclose, fwrite – Some examples 42

Type Checking • PHP includes several functions to determine the type of a variable

Type Checking • PHP includes several functions to determine the type of a variable since it may not be obvious what the type is due to conversions is_int($x) is_double($x) is_array($x) is_string($x) is_null($x) // returns true if $x is an integer // returns true if $x is a double // returns true if $x is an array // returns true if $x is a string // returns true if $x is a null 43

String Functions • We can access a string as an array to retrieve individual

String Functions • We can access a string as an array to retrieve individual characters: $s=“hithere”; $z = $s[0]. $s[2]. $s[4]; print($z); // hte • We can also assign characters to the string: $s[2] = “F”; print($s); // hi. Fhere 44

Strings • String length: strlen($s) returns the length of the string $s="eat big macs";

Strings • String length: strlen($s) returns the length of the string $s="eat big macs"; for ($i=0; $i<(strlen($s)-1)/2; $i++) { $temp = $s[$i]; $s[$i] = $s[strlen($s)-$i-1]; $s[strlen($s)-$i-1] = $temp; } print($s); // Output : scam gib tae 45

Strings • Substring: Searches a string for a substring Prototype: string strstr (string haystack,

Strings • Substring: Searches a string for a substring Prototype: string strstr (string haystack, string needle) • Returns all of haystack from the first occurrence of needle to the end. • If needle is not found, returns FALSE. $email = ‘bhecker@acm. org'; $domain = strstr ($email, '@'); print ($domain); // prints @acm. org 46

Strings • strtolower($s) : returns $s in lowercase $s=“Ab. C”; $s = strtolower($s); //

Strings • strtolower($s) : returns $s in lowercase $s=“Ab. C”; $s = strtolower($s); // $s = “abc” • strtoupper($s) : returns $s in uppercase $s = “Ab. C”; $s = strtoupper($s); • trim($s) removed // $s = “ABC” : returns $s with leading, trailing whitespace $s = “ n ABC rn”; $s = trim($s); // $s = “ABC” Trim is useful to remove CR’s and Newlines when reading lines of data from text files or as input from a form (e. g. textbox, textarea) 47

Strings • Substring: Format: string substr (string, int start [, int length]) – Substr

Strings • Substring: Format: string substr (string, int start [, int length]) – Substr returns the portion of string specified by the start and length parameters. – If start is positive, the returned string will start at the start'th position in string, counting from zero. For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', and so forth. • Examples: $rest = substr ("abcdef", 1); // returns "bcdef" $rest = substr ("abcdef", 1, 3); // returns "bcd" 48

Implode • Implode is used to concatenate elements of an array into a single

Implode • Implode is used to concatenate elements of an array into a single string implode (string glue, array pieces) • Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element. • Examples $arr[]="A"; $arr[]="B"; $arr[]="C"; $s = implode(", ", $arr); // $s = “A, B, C” $s = implode("", $arr); // $s = “ABC” 49

Explode • Explode is used to create an array out of a string with

Explode • Explode is used to create an array out of a string with some delimiter array explode (string separator, string) • Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string separator. • Example $s="eat: large: fries"; $arr = explode(": ", $s); print_r($arr); print("<p>"); Output: Array ( [0] => eat [1] => large [2] => fries ) 50

File I/O • Opening a file: fopen • Format: int fopen (string filename, string

File I/O • Opening a file: fopen • Format: int fopen (string filename, string mode) – Filename is the complete path to the file to open; must have proper permissions – Mode is one of the following • 'r' - Open for reading only; place the file pointer at the beginning of the file. • 'r+' - Open for reading and writing; place the file pointer at the beginning of the file. • 'w' - Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it. • 'w+' - Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it. • 'a' - Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it. • 'a+' - Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it. – Returns: a file pointer used to reference the open file 51

File I/O • Reading from a text file: string fgets (int filepointer, int length)

File I/O • Reading from a text file: string fgets (int filepointer, int length) – Returns a string of up to length - 1 bytes read from the file pointed to by fp. – Reading ends when length - 1 bytes have been read, on a newline (which is included in the return value), or on EOF (whichever comes first). – We can use this function on files we have opened for reading 52

File I/O • Writing to a text file: int fwrite (int fp, string) –

File I/O • Writing to a text file: int fwrite (int fp, string) – fwrite() writes the contents of string to the file stream pointed to by fp. – The file must be opened for writing • Checking for end of file feof(int fp) Returns true if we have reached the end, false otherwise • Closing a file fclose(int fp) Use when done with the file and close the file pointer 53

File I/O example $fd = fopen ("/proc/cpuinfo", "r"); while (!feof ($fd)) { $oneline =

File I/O example $fd = fopen ("/proc/cpuinfo", "r"); while (!feof ($fd)) { $oneline = fgets($fd, 4096); print("$oneline "); } fclose ($fd); 54

fgets • IMPORTANT – Remember that fgets returns the string WITH the newline •

fgets • IMPORTANT – Remember that fgets returns the string WITH the newline • This is critical if you are going to perform comparisons – You’ll get a false match if the newline is not accounted for – Easiest technique: trim out the newlines $oneline = trim(fgets($fp, 1024)); 55

Example • Create a single PHP script that generates a form with a textarea

Example • Create a single PHP script that generates a form with a textarea – Allow the user to enter numbers in the textarea – Submit the form to the same script – Compute the sum of the numbers in the textarea and print it out 56

Example. php <? php header("Content-Type: text/html"); print("<HTML><HEAD><TITLE>My Page</TITLE>"); print("</HEAD>"); print("<BODY>"); if($_SERVER['REQUEST_METHOD'] != "POST") {

Example. php <? php header("Content-Type: text/html"); print("<HTML><HEAD><TITLE>My Page</TITLE>"); print("</HEAD>"); print("<BODY>"); if($_SERVER['REQUEST_METHOD'] != "POST") { // We are loading for the first time, // not receiving a form. So generate // a form allowing the user to enter // data in a text area and have it submitted // to this same script print("<FORM method=post action='example. php'>"); print("Enter numbers below. <p>"); print("<TEXTAREA name='my. Data' rows=10></TEXTAREA>"); print("<INPUT type=submit>"); print("</FORM>"); } 57

Example. php else { // We are receiving data from our form // Put

Example. php else { // We are receiving data from our form // Put the text data into an array. Each // is separated by a newline, so use explode // to parse $a = explode("n", $_REQUEST['my. Data']); // Here we loop through and add up the numbers $total = 0; foreach ($a as $key=>$value) { // Each element in the array is a string, // but note that each will contain a r // whitespace at the end, so you may wish // to trim these out. It is not really // necessary in this example but you will // probably want to trim for your homework $num = (int) trim($value); $total += $num; } print("The sum of your numbers is $total<p>"); } print("</BODY></HTML>"); ? > 58

Execution 59

Execution 59

Summary • PHP is an imperative language for the web • Similarities to C,

Summary • PHP is an imperative language for the web • Similarities to C, Java, and even interpreted languages • Can’t do everything since server side only – sometimes coupled with client-side languages such as Java. Script • PHP version 5 not quite backward compatible with PHP 4 • Easy to write sloppy code so one must be more disciplined in design of classes, functions, variables, HTML, documentation 60

Lots More to PHP • We have only scratched the surface, but there is

Lots More to PHP • We have only scratched the surface, but there is much more that PHP can do – – – – – Generate graphics (gd library) Networking, Sockets, IRC, Email Database Access LDAP Regular Expressions PDF Java XML Design methodologies (e. g. Fuse. Box, include files) Many more • See the excellent resources online – www. php. net – www. phpbuilder. com – www. zend. com 61

End of PHP 62

End of PHP 62