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

LIS651 lecture 1 arrays functions & sessions

Embed Size (px)

DESCRIPTION

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. - PowerPoint PPT Presentation

Citation preview

Page 1: LIS651 lecture 1 arrays functions & sessions

LIS651 lecture 1arrays functions & sessions

Thomas Krichel

2008-10-25

Page 2: LIS651 lecture 1 arrays functions & sessions

today

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

Page 3: LIS651 lecture 1 arrays functions & 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

Page 4: LIS651 lecture 1 arrays functions & sessions

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"

Page 5: LIS651 lecture 1 arrays functions & sessions

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.

Page 6: LIS651 lecture 1 arrays functions & sessions

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

Page 7: LIS651 lecture 1 arrays functions & sessions

strlen()

• strlen(string) returns the length of the string string.$zip=trim($_POST['zipcode']);

$zip_length=strlen($zip);

print $zip_length;

// hopefully, prints 5

Page 8: LIS651 lecture 1 arrays functions & sessions

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!

Page 9: LIS651 lecture 1 arrays functions & sessions

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 &lt;div&gt; element do?

• Using htmlspecialchars() is considered to be good security because it prevents injection of HTML and especially its <script> element.

Page 10: LIS651 lecture 1 arrays functions & sessions

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”

Page 11: LIS651 lecture 1 arrays functions & sessions

more number functions

• abs() calculates the absolute valueprint 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

Page 12: LIS651 lecture 1 arrays functions & sessions

rand()

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

Page 13: LIS651 lecture 1 arrays functions & sessions

variable types

• Variables in PHP have types. You can check for typesis_numeric()

is_string()

is_int()

is_float()

• They all return a Boolean value.• They can be used to check the nature of a

variable.

Page 14: LIS651 lecture 1 arrays functions & sessions

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.

Page 15: LIS651 lecture 1 arrays functions & sessions

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

Page 16: LIS651 lecture 1 arrays functions & sessions

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

Page 17: LIS651 lecture 1 arrays functions & sessions

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);

Page 18: LIS651 lecture 1 arrays functions & sessions

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.

Page 19: LIS651 lecture 1 arrays functions & sessions

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.

Page 20: LIS651 lecture 1 arrays functions & sessions

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.

Page 21: LIS651 lecture 1 arrays functions & sessions

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.

Page 22: LIS651 lecture 1 arrays functions & sessions

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,"

Page 23: LIS651 lecture 1 arrays functions & sessions

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.

Page 24: LIS651 lecture 1 arrays functions & sessions

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;$euro_amount</td></tr>\n";

}

print "</table>";

• This prints the full price list. But it could also do the whole form. This is fabulous!

Page 25: LIS651 lecture 1 arrays functions & sessions

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”;

}

Page 26: LIS651 lecture 1 arrays functions & sessions

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;$euro_amount</td></tr>\n";

$count++;

}

Page 27: LIS651 lecture 1 arrays functions & sessions

print "</table>\n";

// This produces something like

// <table caption="price list">

// <tr><td align="left">Grosswald Export</td>

// <td align="right">&euro;1.45</td></tr>

// <tr><td align="left">Bruch Festbock</td>

// <td align="right"'>&euro;1.74</td></tr>

// </table>

Page 28: LIS651 lecture 1 arrays functions & sessions

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;

Page 29: LIS651 lecture 1 arrays functions & sessions

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

)

)

Page 30: LIS651 lecture 1 arrays functions & sessions

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.

Page 31: LIS651 lecture 1 arrays functions & sessions

simplest function

function beer_print {

print "beer\n";

}

beer_print() ; // prints: “beer” and newline

Page 32: LIS651 lecture 1 arrays functions & sessions

A more practical example

• Stephanie Rubino was an English teacher and objects to sentences likeYou 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

Page 33: LIS651 lecture 1 arrays functions & sessions

a function and its arguments• declare the arguments to the function in

parenthesisfunction rubino_print ($number, $singular,$plural) {

if($number == 1) {

print "one $singular";

}

else {

print "$number $plural";

}

}

rubino_print(3,'woman','women'); // prints: “3 women”

Page 34: LIS651 lecture 1 arrays functions & sessions

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 listfunction thomas_need($thing='beer') {

print "Thomas needs $thing.\n";

}

thomas_need(); // prints: “Thomas needs beer.”

thomas_need('vodka'); // prints: “Thomas needs vodka”.

Page 35: LIS651 lecture 1 arrays functions & sessions

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”

Page 36: LIS651 lecture 1 arrays functions & sessions

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”.

Page 37: LIS651 lecture 1 arrays functions & sessions

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.

Page 38: LIS651 lecture 1 arrays functions & sessions

utility function for database queriesfunction 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;

}

}

Page 39: LIS651 lecture 1 arrays functions & sessions

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!");}

}

Page 40: LIS651 lecture 1 arrays functions & sessions

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.

Page 41: LIS651 lecture 1 arrays functions & sessions

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

Page 42: LIS651 lecture 1 arrays functions & sessions

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.

Page 43: LIS651 lecture 1 arrays functions & sessions

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.

Page 44: LIS651 lecture 1 arrays functions & sessions

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>

Page 45: LIS651 lecture 1 arrays functions & sessions

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>

Page 46: LIS651 lecture 1 arrays functions & sessions

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.

Page 47: LIS651 lecture 1 arrays functions & sessions

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.

Page 48: LIS651 lecture 1 arrays functions & sessions

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.

Page 49: LIS651 lecture 1 arrays functions & sessions

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:

Page 50: LIS651 lecture 1 arrays functions & sessions

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

Page 51: LIS651 lecture 1 arrays functions & sessions

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.

Page 52: LIS651 lecture 1 arrays functions & sessions

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.

Page 53: LIS651 lecture 1 arrays functions & sessions

$_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();

}

Page 54: LIS651 lecture 1 arrays functions & sessions

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.

Page 55: LIS651 lecture 1 arrays functions & sessions

http://openlib.org/home/krichel

Thank you for your attention!

Please switch off machines b4 leaving!