Presentation is loading. Please wait.

Presentation is loading. Please wait.

LIS651 lecture 1 arrays functions & sessions Thomas Krichel 2008-10-25.

Similar presentations


Presentation on theme: "LIS651 lecture 1 arrays functions & sessions Thomas Krichel 2008-10-25."— Presentation transcript:

1 LIS651 lecture 1 arrays functions & sessions Thomas Krichel 2008-10-25

2 today geeky operators more string functions more number functions arrays the foreach() {} statement functions include() and require() sessions

3 geeky increment/decrement ++ is an operator that adds one. The value of the resulting expression depends on the position of the operator $a=4; print ++$a;// prints: 5 print $a;// prints: 5 $b=4; print $b++;// prints 4 print $b; // prints 5 -- works in the same way

4 geeky combined operators There are some combined operators that change a value and set it to the new one. For example $a+=$b ; is the same as $a=$a+$b; Same effect for -=, *=, /=, %=, and.= $a="I want "; $b="Balitka 8"; $a.=$b; print $a;// prints: "I want Baltika 8"

5 string functions There are a long list of string functions in the PHP reference manual. When you work with text, you should look at those string functions at http://www.php.net/manual/en/ref.strings.php Working with text is particularly important when checking the input of users into your form. I am looking at just a few of examples here. You really need to read the reference to see what is available.

6 trim() trim(string) removes the whitespace at the beginning and the end of the string string. It returns the transformed string. $input=" Festbock "; $output=trim($input); print "|$output|";// prints: |Festbock| whitespace is any of the following characters –the blank character –the newline –the carriage return –the tabulation character

7 strlen() strlen(string) returns the length of the string string. $zip=trim($_POST['zipcode']); $zip_length=strlen($zip); print $zip_length; // hopefully, prints 5

8 strip_tags() strip_tags(string) removes HTML tags from the string string $input=" But weiser"; print strip_tags($input); // prints: Butweiser $in=" "; print strip_tags($in); // prints nothing, hurray!

9 htmlspecialchars() htmlspecialchars(string) makes XML entities out of XML special characters in the string string.,&, and " are transformed. It returns the transformed string. $in="What does the element do?"; print htmlspecialchars($in); // prints: What does the <div> element do? Using htmlspecialchars() is considered to be good security because it prevents injection of HTML and especially its element.

10 substr() substr( string, start, offset) returns the substring of a string string starting at position start, with length offset. $string=I like beer.; $sub=substr($string, 2, 4); print $sub; // prints like

11 more number functions abs() calculates the absolute value print abs(-3)// prints: 3 print abs(3)// prints: 3 max() and min() return maximum and minimum print min(2,3)// prints: 2 rand( min, max ) returns a random integer between the integers min and max, included. The list of functions that use numbers is http://php.net/manual/en/ref.math.php

12 rand() rand( min, max ) returns a random integer between the integers min and max, included.

13 variable types Variables in PHP have types. You can check for types is_numeric() is_string() is_int() is_float() They all return a Boolean value. They can be used to check the nature of a variable.

14 arrays The variables we have looked at up until now are scalars. They only contain one piece of data. Arrays are variables that can contain more than one piece of data. –For example, a six pack in conveniently represented as an array of cans of beer. –For another example, a class is a group of people, each having a name, a social security number, etc.

15 numeric arrays An numeric array has key value pairs where the keys are numbers. $good_beers[0]="Baltika 8"; $good_beers[1]="Bruch Festbock"; or as follows $lousy_beers=array("Miller Lite", "Sam Adams", "Budweiser"); print $lousy_beers[0];// prints: Miller Lite print $lousy_beers[2];// prints: Budweiser

16 keeping count in numeric arrays For numeric arrays, you can add members very simple without keeping track of number. $beers=array("Karlsberg", "Bruch") ; $beers[]="Budweiser"; // $beer now has Karlberg, Bruch and Budweiser print count($beers) ; // prints 3

17 string arrays Sometimes you need data structured by a string. For example for a price list. $price['Grosswald Export']=1.45; $price['Bruch Festbock']=1.74; // the array $price has strings as keys An equivalent way to declare this is $price=array('Grosswald Export' => 1.45, 'Bruch Festbock' => 1.74);

18 array functions There is a very large number of array functions. They are described in the array function reference. http://www.php.net/manual/en/ref.array.php Now we are just looking at some examples.

19 count() count() returns the size of an array $price['Grosswald Export']=1.45; $price['Bruch Festbock']=1.74; $product_number=count($price); print "We have $product_number products for you today."; // prints: We have 2 products for you today.

20 unset() This can be used to unset an element $beers_drunk('Amstel' => 'good', 'Miller' =>'ok', 'Budweiser'=>'lousy'); unset($beers_drunk('Amstel'); Now the array $beers_drunk only has two elements.

21 foreach() {} loop, numeric array The foreach loop loops over arrays. You use it as foreach($array as $element). The array $array is the array you are looping through. Each time you reach a new element, the current element is placed in $element.

22 a foreach() example $bottles=array('Amstel', 'Karlsberg', 'Sam Adams'); foreach($bottles as $beer) { print "Thomas has a $beer,\n"; } // prints: // "Thomas has a Amstel, // Thomas has a Karlsberg, // Thomas has a Sam Adams,"

23 foreach() loop, string array The foreach loop loops over arrays. You use it as foreach( $array as $key => $value ). The array $array is the array you are looping through. Each time you reach a new element, the current key is placed in $key and the value in $value.

24 another foreach() example Recall the $price string array. Another example illustrates print " \n"; foreach ($price as $item => $euro_amount) { print " $item \n"; print " €$euro_amount \n"; } print " "; This prints the full price list. But it could also do the whole form. This is fabulous!

25 foreach() example from the form $_GET is an array. You can loop through it. foreach($_GET as $control => $value) { print you set $control to $value \n; }

26 the well-aligned price table $l_r=array('left','right'); $count=0; // counter of elements printed print " \n"; foreach ($price as $item => $euro_amount) { print " <td align=\"$l_r[$count % 2]\""; print "$item"; $count++; print " \n €$euro_amount \n"; $count++; }

27 print " \n"; // This produces something like // // Grosswald Export // €1.45 // Bruch Festbock // €1.74 //

28 multiple arrays Example $products[0]['name']="Grosswald Pilsener"; $products[0]['price']=1.56; $products[1]['name']="Grosswald Export"; $products[1]['price']=1.34; $products[2]['name']="Bruch Landbier"; $products[2]['price']=1.22;

29 printing a debugging representation $a = array ('a' => 'apple', 'c' => array ('one', 'two')); print_r ($a); // prints a debugging representation: Array ( [a] => apple [c] => Array ( [0] => one [1] => two )

30 functions The PHP function reference is available on its web site http://php.net/quickref.php. It shows the impressive array of functions within PHP. But one of the strengths of PHP is that you can create your own functions as you please. If you recreate one of the built-in functions, your own function will have no effect.

31 simplest function function beer_print { print "beer\n"; } beer_print() ; // prints: beer and newline

32 A more practical example Stephanie Rubino was an English teacher and objects to sentences like You have ordered 1 bottles of Grosswald Pils. Let us define a function rubino_print(). It will take three arguments –a number to check for plural or singular –a word for the singular –a word for the plural

33 a function and its arguments declare the arguments to the function in parenthesis function rubino_print ($number, $singular,$plural) { if($number == 1) { print "one $singular"; } else { print "$number $plural"; } rubino_print(3,'woman','women'); // prints: 3 women

34 default arguments Sometimes you want to allow a function to be called without giving all its arguments. You can do this by declaring a default value, using an equal sign in the function list function thomas_need($thing='beer') { print "Thomas needs $thing.\n"; } thomas_need(); // prints: Thomas needs beer. thomas_need('vodka'); // prints: Thomas needs vodka.

35 rubino_print using common plurals function rubino_print ($num, $sing,$plur=1) { if($num == 1) { print "one $sing"; } elseif($plur ==1) { print "$num $sing"."s"; } else { print "$num $plur"; } rubino_print(6,'beer') // prints: 6 beers

36 return value Up until now we have just looked at the side effect of a function. "return" is a special command that returns a value. It takes the return value as a parameter return $result; When return is used, the function is left. Example function good_beer () { return 'Festbock'; } $beer=good_beer; print $beer ; // prints: Festbock.

37 rubino_print with return function rubino_print ($number, $singular,$plural) { if($number == 1) { return "one $singular"; } return "$number $plural"; } $order=rubino_print(2,"beer","beers"); print "you ordered $order\n"; // prints: you ordered 2 beers.

38 utility function for database queries function mysql_fetch_all($query) { $r=@mysql_query($query); if($err=mysql_error()) { return $err; } if( mysql_num_rows($r) ) { while($row=mysql_fetch_array($r)) { $result[]=$row; } return $result; }

39 usage example my $query="SELECT * FROM my_table"; if(is_array($rows=mysql_fetch_all($query)) { // do something } else { if (! is_null($rows)) { die("Query failed!");} }

40 visibility of variables Variables used inside a function are not visible from the outside. Example $beer="Karlsberg"; function yankeefy ($name='Sam Adams') { $beer=$name; } yankeefy(); print $beer;// prints: Karlsberg The variable inside the function is something different than the variables outside.

41 accessing global variables. There are two ways to change a global variable, i.e. one that is defined in the main script. One is just to call it as $GLOBAL['name'] where name is the name of the global variable. function yankeefy ($name="Sam Adams") { $GLOBALS['beer']="name"; } The other is to change it outside a function definition. Example in brewer_quiz.php

42 working with many source files Many times it is useful to split a PHP script into several files. PHP has two mechanisms. require(file) requires the to be included. If the file is not there, PHP exits with an error. include(file) includes the file.

43 require() and include() Both assume that you leave PHP. Thus within your included file you can write simple HTML. If you want to include PHP in your included file, you have to surround it by, just like in a PHP script. Here is an example to use include to build the basic web page.

44 top.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> $title

45 bottom.html <img style="border: 0pt" src="http://wotan.liu.edu/valid-xhtml10.png" alt="Valid XHTML 1.0!" height="31" width="88" />

46 trouble $title in the top.html is not understood as the title. It reads as $title, which means "idiot" for your web user. Even if you replace $title with $title is empty. The definition from the outer file is not seen in the included file. So you have to split into three files, and print the title in the main file. I leave that to you to figure out.

47 login.php & create_account.php Both require a database that has three fields –id which is an auto_increment int acting as a handle –username is the username of the account. it must be unique and this is enforced by mySQL –password is a varchar(41) because the sha1 of the password is stored. This is 40 chars long.

48 sessions You will recall that HTTP is a stateless protocol. Each request/response is self-contained. Statefulness is crucial in Web applications. Otherwise users have to authenticate every time they access a new page. Traditionally, one way to create statefulness is to use cookies. PHP uses cookies to create a concept of its own, sessions, that makes it all very easy.

49 cookies A cookie is a piece of attribute/value data. A server can send cookies as value of a HTTP header Set-Cookie:. Multiple headers may be sent. When the client visits the web site again, it will send the cookie back to the server with a HTTP header Cookie:

50 Set-Cookie Set-Cookie: name=value; [expires= date;] [path=path;] [domain= domain] [secure] where –name= is the variable name set in the cookie –value= is the variable's value –date= is a date when the cookie expires –path= restricts the cookie to be sent only when requests to a path starting with path are made –domain= restricts the sending of the cookie to a certain domain –secure restricts transmission to https

51 Cookies: The browser compares the request it wants to make with the URL and the domain that sent the cookie. If the path is not set the cookie will only be sent to a request with the originating URL. If the cookie matches the request a request header of the form Cookie: name1=value1 ; name2=value2 is sent.

52 sessions Sessions are a feature of PHP. PHP remembers a session through a special cookie PHPSESSID. To activate the sessions, include session_start(); at the beginning of your script, before any printing has been done. One a session is active, you have a special super-global variable $_SESSION. Session data is stored in special files on wotan.

53 $_SESSION This is an array where you can read and set variables that you want to keep during the session. if($_SESSION[user_name]) { print "welcome $_SESSION[user_name]"; } else { // show users login form print login_form(); }

54 ending sessions At 9 and 39 past each hour, wotan deletes all session files that have not been changed for 24 minutes or more. If you want to remove a session yourself, you can call session_destroy() in your script. An example is in visit.php.

55 http://openlib.org/home/krichel Thank you for your attention! Please switch off machines b4 leaving!


Download ppt "LIS651 lecture 1 arrays functions & sessions Thomas Krichel 2008-10-25."

Similar presentations


Ads by Google