550 likes | 688 Views
Thomas Krichel 2008-10-25. LIS651 lecture 1 arrays functions & sessions. today. geeky operators more string functions more number functions arrays the foreach() {} statement functions include() and require() sessions. geeky increment/decrement.
E N D
Thomas Krichel 2008-10-25 LIS651 lecture 1arrays functions & sessions
today • geeky operators • more string functions • more number functions • arrays • the foreach() {} statement • functions • include() and require() • sessions
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
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"
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.
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
strlen() • strlen(string) returns the length of the string string. $zip=trim($_POST['zipcode']); $zip_length=strlen($zip); print $zip_length; // hopefully, prints 5
strip_tags() • strip_tags(string) removes HTML tags from the string string $input="<b>But</b>weiser"; print strip_tags($input); // prints: Butweiser $in="<a href=\"http://porn.com\"><img src=\"http://porn.com/ad.gif\"/></a>"; print strip_tags($in); // prints nothing, hurray!
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 <div> 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 <script> element.
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”
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
rand() • rand( min , max ) returns a random integer between the integers min and max, included.
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.
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.
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
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
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);
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.
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.
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.
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.
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,"
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.
another foreach() example • Recall the $price string array. • Another example illustrates print "<table caption=\"price list\">\n"; foreach ($price as $item => $euro_amount) { print "<tr><td>$item</td>\n"; print "<td>€$euro_amount</td></tr>\n"; } print "</table>"; • This prints the full price list. But it could also do the whole form. This is fabulous!
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<br/>\n”; }
the well-aligned price table $l_r=array('left','right'); $count=0; // counter of elements printed print "<table caption=\"price list\">\n"; foreach ($price as $item => $euro_amount) { print "<tr><td align=\"$l_r[$count % 2]\""; print "$item"; $count++; print "</td>\n<td align=$l_r[$count % 2]\"> €$euro_amount</td></tr>\n"; $count++; }
print "</table>\n"; // This produces something like // <table caption="price list"> // <tr><td align="left">Grosswald Export</td> // <td align="right">€1.45</td></tr> // <tr><td align="left">Bruch Festbock</td> // <td align="right"'>€1.74</td></tr> // </table>
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;
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 ) )
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.
simplest function function beer_print { print "beer\n"; } beer_print() ; // prints: “beer” and newline
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
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”
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”.
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”
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”.
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.
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; } }
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!");} }
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.
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'] wherename 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
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.
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 <?php and ?>, just like in a PHP script. • Here is an example to use include to build the basic web page.
top.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head><title>$title</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <link rel="stylesheet" type="text/css" href="main.css"/> </head> <body>
bottom.html <p id="validator"> <a href="http://validator.w3.org/check?uri=referer"><img style="border: 0pt" src="http://wotan.liu.edu/valid-xhtml10.png" alt="Valid XHTML 1.0!" height="31" width="88" /></a> </p> </body> </html>
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 <?php $title ?> $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.
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.
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.
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:
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