19
Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 1 Web-Based Information Systems Dr. Osmar R. Zaïane University of Alberta Fall 2007 CMPUT 410: Perl, PHP, Cookies and other Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 2 What is Perl & What is it for? Perl is an acronym for Practical Extraction and Report language. Perl is powerful and flexible like a high-level programming language, developed in the 1980s by Larry Wall. Perl 5 is object-oriented. Perl is scripting language that combines features from awk and sed, yet as powerful as C. It is currently the most used language for CGI-based Web applications, probably because of text parsing capability and platform independence. Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 3 Perl, PHP & Cookies SGML / XML CORBA & SOAP Web Services Search Engines Recommender Syst. Web Mining Security Issues Selected Topics Course Content Introduction Internet and WWW Protocols HTML and beyond Animation & WWW CGI & HTML Forms Dynamic Pages Javascript + Ajax Databases & WWW Web-based Applications Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 4 Objectives of Lecture 11 Introduce Perl language for CGI development (This is not a Perl course) Introduce PHP for web application development (This is not a PHP course) Learn about magic cookies and what we can use them for. See some examples with cookies in Perl and Javascript. See an example with PHP and database access Perl Perl , PHP, Cookies and Other , PHP, Cookies and Other

Web-Based Information What is Perl & What is it for? Systemsugweb.cs.ualberta.ca/~c410/F07/410/slides/L11-410-F07.pdf · • Expressions are simple and concise • There are many

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Web-Based Information What is Perl & What is it for? Systemsugweb.cs.ualberta.ca/~c410/F07/410/slides/L11-410-F07.pdf · • Expressions are simple and concise • There are many

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 1

Web-Based Information Systems

Dr. Osmar R. Zaïane

University of Alberta

Fall 2007

CMPUT 410: Perl, PHP, Cookies and other

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 2

What is Perl & What is it for?• Perl is an acronym for Practical Extraction and Report

language.• Perl is powerful and flexible like a high-level

programming language, developed in the 1980s by Larry Wall. Perl 5 is object-oriented.

• Perl is scripting language that combines features from awk and sed, yet as powerful as C.

• It is currently the most used language for CGI-based Web applications, probably because of text parsing capability and platform independence.

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 3

• Perl, PHP & Cookies• SGML / XML • CORBA & SOAP• Web Services• Search Engines• Recommender Syst.• Web Mining• Security Issues• Selected Topics

Course Content• Introduction• Internet and WWW• Protocols• HTML and beyond• Animation & WWW• CGI & HTML Forms• Dynamic Pages• Javascript + Ajax• Databases & WWW

Web-based Applications

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 4

Objectives of Lecture 11

• Introduce Perl language for CGI development (This is not a Perl course)

• Introduce PHP for web application development (This is not a PHP course)

• Learn about magic cookies and what we can use them for.

• See some examples with cookies in Perl and Javascript.

• See an example with PHP and database access

PerlPerl, PHP, Cookies and Other, PHP, Cookies and Other

Page 2: Web-Based Information What is Perl & What is it for? Systemsugweb.cs.ualberta.ca/~c410/F07/410/slides/L11-410-F07.pdf · • Expressions are simple and concise • There are many

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 5

Outline of Lecture 11• What is Perl?• Variables and Expressions• Control Structures• File Input and Output• Pattern matching• A CGI example with Perl• Cookies and example with Perl• Cookie example with JavaScript• PHP, let’s do it again

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 6

Perl the scripting Language• Perl is commonly used to write scripts.• It is interpreted and is available on most

platforms (free software foundation and GNU)• It suffices to write a script in a text file, make

it executable and run it.• Initially designed to monitor software projects

and generate reports, Perl gained popularity thanks to the Internet & WWW.

• Example #!/usr/local/bin/perl$input=<STDIN>;print “$input”;

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 7

Perl Capabilities

• Perl has rich and easy-to-use built-in text processing capabilities.

• Perl is very flexible when it comes to file text processing and pattern matching.

• There are many intrinsic functions for manipulating strings

• Expressions are simple and concise• There are many ways to write the same thing in

Perl.Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 8

Programming and Debugging• Perl programs are written in any text editor• Start the first line with #!/usr/local/bin/perl

• You can also run a perl expression in a command line with “perl ….”

• Debugging is tricky. There are debuggers but they are not as good as C/C++ and Java debuggers

• Use “perl –w” or try with “perl –c”• Use print statements in your script to trace.

Page 3: Web-Based Information What is Perl & What is it for? Systemsugweb.cs.ualberta.ca/~c410/F07/410/slides/L11-410-F07.pdf · • Expressions are simple and concise • There are many

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 9

Outline of Lecture 11• What is Perl?• Variables and Expressions• Control Structures• File Input and Output• Pattern matching• A CGI example with Perl• Cookies and example with Perl• Cookie example with JavaScript• PHP, let’s do it again

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 10

Scalar Variables• Scalar variables start with $. Ex. $myVariable• A scalar variable can contain:

– a string $myVariable=“this is a string”;– a integer number $myVariable=42;– a floating-point number $myVariable=49.33;

• A string with “string” is evaluated while a string with ‘string’ is not evaluated:– $myString = “this is your total: $total”;

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 11

Perl in Loosely Typed• on-the-fly conversion

• concatenation

$x=“4”;$y=“5”$z=$x*$y + 2;

$x=“Bill”;$y=“Gates”$z=$x.$y;

BillGates$z

$x=19;$y=63;$z=$x.$y; 1963

$z

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 12

Arrays and Hash• Arrays in Perl are indexed from 0 to n-1• An array is prefixed with @:

– @myArray = (‘bill’, ‘john’, ‘sue’, ‘Amelia’);• An element of an array is prefixed with $

– $myArray[3] = ‘alpha’; $myVar=$myArray[0];• $#myArray is the last index of @myArray• Hash or associative array uses keys to

reference elements %myHash– $myHash{‘billy’} = 42; $myHash{$foo}=“abc”;

Page 4: Web-Based Information What is Perl & What is it for? Systemsugweb.cs.ualberta.ca/~c410/F07/410/slides/L11-410-F07.pdf · • Expressions are simple and concise • There are many

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 13

Outline of Lecture 11• What is Perl?• Variables and Expressions• Control Structures• File Input and Output• Pattern matching• A CGI example with Perl• Cookies and example with Perl• Cookie example with JavaScript• PHP, let’s do it again

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 14

Print Block

• Print a block of text (with or without variables) until a given label.

• Interprets escape sequences and variables• No need to escape the character “

$x=“221 Athabasca Hall”;Print << ENDFORM;<form action=“program.cgi” method=“GET”><INPUT type=“text” value=$x name=“address”></form>ENDFORM The convention is to use capital letters for labels.

Closing label not indented and alone in a line.

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 15

Conditionals

• if (condition) {statements}– if ($number) {print “the number is not zero!”;}

• if (condition) {statements} else {statements}• if (condition) {statements }

elsif (condition) {statements} else {statements}

• Variable = (condition)? expression1 : expression2;

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 16

Loops• while (condition) {statements}• until (condition) {statements}• do {statements} while (condition);• do {statements} until (condition);• for (init;condition;increment) {statements}• foreach (list) {statement}

– foreach $line (@myArray) {print “$line\n”;}• next, last, redo

Page 5: Web-Based Information What is Perl & What is it for? Systemsugweb.cs.ualberta.ca/~c410/F07/410/slides/L11-410-F07.pdf · • Expressions are simple and concise • There are many

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 17

Outline of Lecture 11• What is Perl?• Variables and Expressions• Control Structures• File Input and Output• Pattern matching• A CGI example with Perl• Cookies and example with Perl• Cookie example with JavaScript• PHP, let’s do it again

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 18

Opening a File• open(variable, filename)

– open(MYFILE, “/usr/me/myfile.txt”);• Open for writing

– open(MYFILE, “>/usr/me/myfile.txt”);• Open for reading

– open(MYFILE, “</usr/me/myfile.txt”);• Open for appending

– open(MYFILE, “>>/usr/me/myfile.txt”);• Closing a file with close(MYFILE)

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 19

Reading/Writing to/from a File

• $line=<MYFILE>• @lines=<MYFILE>

$i=1;while ($line=<MYFILE>) {

chop $line;print “line $i:[$line]\n”;$i++;

}

• print MYFILE “this will go in the file as a line\n”;

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 20

Determining the status of a file

• if (-e “file”) # checks if file exists• if (-d “file”) # checks if file is directory• if (-f “file”) #checks if file is ordinary file• if (-l “file”) #checks if file is symbolic link• if (-r “file”) #checks if file is readable• if (-w “file”) #checks if file is writable• if (-x “file”) # checks if file is executable• …

Page 6: Web-Based Information What is Perl & What is it for? Systemsugweb.cs.ualberta.ca/~c410/F07/410/slides/L11-410-F07.pdf · • Expressions are simple and concise • There are many

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 21

Outline of Lecture 11• What is Perl?• Variables and Expressions• Control Structures• File Input and Output• Pattern matching• A CGI example with Perl• Cookies and example with Perl• Cookie example with JavaScript• PHP , let’s do it again

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 22

The power of Perl

• One of the most powerful and attractive capabilitites of Perl is the use of regular expressions for pattern matching.

• Allows large amount of text to be searched with relatively simple expressions.

• if ($myString eq “hello”) # equality operator• if ($myString =~ /hello/) # matching operator

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 23

Pattern Matching

• if ($myString =~ /^hello/) # at the beginning• if ($myString =~ /hello$/) # at the end• if ($myString !~ /hello/) # no match• if ($myString =~ / \b (\w+ ing ) \b/x)

– $1 would be mached with a word ending with “ing”– /x ignores spaces /i ignores case

• if ($myString =~ / [^a-z0-9]/) – matches any character not in a to z and 0 to 9

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 24

Substitutions

• Substitution is replacing substrings with other substrings.

• $myString =~ s/\t/\s/g;

• Spliting @myarray = split(/*/,$myString)

Page 7: Web-Based Information What is Perl & What is it for? Systemsugweb.cs.ualberta.ca/~c410/F07/410/slides/L11-410-F07.pdf · • Expressions are simple and concise • There are many

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 25

Outline of Lecture 11• What is Perl?• Variables and Expressions• Control Structures• File Input and Output• Pattern matching• A CGI example with Perl• Cookies and example with Perl• Cookie example with JavaScript• PHP , let’s do it again

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 26

#!/usr/local/bin/perl#-------------------------------------------------------------------------####### Getting the input from STDIN or command line #------------------------------------------------------------------------$my_input = ($ENV{REQUEST_METHOD} eq "POST") ?

<STDIN> : $ENV{QUERY_STRING};#------------------------------------------------------------------------####### Splitting input by parameter and value #-------------------------------------------------------------------------@my_QUERY_LIST = split( /&/, $my_input); # Splitting all pairsforeach $item (@my_QUERY_LIST) {

($my_param, $my_value) = split( /=/, $item); # Splitting variables and values$my_value =~ s/\+/ /g; # Change +'s to spaces $my_value =~ s/\s*$//; # eliminate spaces at the end$my_value =~ s/\%0D\%0A/\n/g; $my_value =~ s/%(..)/pack('C',hex($1))/ge; if ($my_in{$my_param}) {

$my_in{$my_param} .= ' ';$my_in{$my_param} .= $my_value;

} else { $my_in{$my_param} = $my_value;

}}

Parsing CGI input

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 27

$name = $my_in{‘variable1’};$habit = $my-in{‘variable2’};

print “Content-type: text/html\n\n”; #printing the header# printing the pageprint “<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">”;print “<HTML><HEAD><TITLE>Testing Cookies</TITLE></HEAD>\n”;print “<BODY><h1>My page title</h1>\n”;

print “</BODY></HTML>\n”;

Snippet of CGI with Perl

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 28

#-------------------------------------------------------------------------####### Accessing parameters using the CGI module# and importing standard functions. #------------------------------------------------------------------------use CGI qw( :standard );

$dtd = " -//W3C//DTD HTML 4.01 Transitional//EN ";print( header());print( start_html({dtd=>$dtd, title => " My page title "}));$firstName=param(" fname");$lastName=param(" lname ");…

Another example accessing parameters in a CGI with Perl

No need to build the data structure and do all the parsing

Returns: Content-type: text/html\n\n

Deals with tags in the header<HTML><HEAD><TITLE> up to <BODY>

Page 8: Web-Based Information What is Perl & What is it for? Systemsugweb.cs.ualberta.ca/~c410/F07/410/slides/L11-410-F07.pdf · • Expressions are simple and concise • There are many

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 29

Outline of Lecture 11• What is Perl?• Variables and Expressions• Control Structures• File Input and Output• Pattern matching• A CGI example with Perl• Cookies and example with Perl• Cookie example with JavaScript• PHP , let’s do it again

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 30

Hidden Fields

• You have used hidden fields in your assignment 2 to maintain some data between different forms in the same session.

• This data is lost in later sessions.• Nothing is actually stored on the client.• How do we store data on the client to

maintain persistent data between sessions?

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 31

Magic Cookies

• A cookie is some text like a text file that is passed transparently between the client (browser) and the server to maintain state information.

• The server creates the cookie and sends it to the browser which will send it back each time it connects to the server again.

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 32

Cookie Life CycleGet URL1 Page1

Cookie

Get URL2

Cookie

Page2

Cookie

43

21

The browser always sends back the cookie to the server

The server may send back the cookie with changes

Page 9: Web-Based Information What is Perl & What is it for? Systemsugweb.cs.ualberta.ca/~c410/F07/410/slides/L11-410-F07.pdf · • Expressions are simple and concise • There are many

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 33

Cookies are not Forever

• A cookie has an expiry date attached to it• After the expiry date, the browser

automatically deletes the cookie• If no expiry date is specified, the cookie last

only for the current session.• The expiry date is of the form:

WeekDay DD-Month-YYYY HH:MM:SS GMT

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 34

Passing Cookies

• The client receives a cookie in the HTTP response header with Set-Cookie

• Set-cookie: name=cName; value=cValue;…• The CGI running on the server receives the

cookie in an HTTP variable HTTP-COOKIE• When constructing the HTTP response header,

the CGI adds a cookie with set-cookie.

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 35

Restrictions on Cookies

• Cookies are sent back only to the server that generated them or to the Internet domain specified by the creator of the cookie.

• Cookies can be restricted within a site (web server) using a specified path.

• The size of a cookie is limited to 4 Kb.• No more than 20 cookies can be created at a

time.

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 36

Cookie Attributes

• Name cookie name• Value value attached to cookie• Domain domain that can receive cookie• Path restricts the cookie in the site• Expires expiry date• Secure specifies that the cookie is

encrypted (not very secure)

Page 10: Web-Based Information What is Perl & What is it for? Systemsugweb.cs.ualberta.ca/~c410/F07/410/slides/L11-410-F07.pdf · • Expressions are simple and concise • There are many

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 37

Syntax for Cookies• A cookie with all its attributes is defines in

one line with attributes separated by “;”Set-Cookie: name=test; value=20; expires=Tuesday, 13 Feb 2007 16:00:00 GMT; domain=.ualberta.ca

• The value can not have spaces and semi-column, etc. use escaped characters.

• If more than one cookie are needed by the application then it is necessary to have each cookie with one set-cookie line.

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 38

What are Cookies Used For?

• Cookies are used whenever a Web Application needs to store information on the client-side for persistent state

• Used as a cart in e-commerce applications• Used to personalize web pages (user preferences)• Used to identify users and sessions• Used to track users on a site for user behaviour

analysis• Etc.

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 39

Example with Cookies

• We want to create a cookie to store in the browser information about the customer, the preferences, as well as the cart.

• We will create different cookies.

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 40

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <HEAD> <title>Example of Forms with JavaScript</title></HEAD> <BODY bgcolor="#ffffff"> <center> <h1> Form Example</h1> </center>

<FORM name="myform" action=“cgi-bin/cookies.pl" >Enter your name: <input type="text" name= "variable1" size=20 > <br>How often do you buy online: <input type="radio" name="variable2" Value="every day">Every day<br>: <input type="radio" name="variable2" Value="once a week">Once a week<br>: <input type="radio" name="variable2" Value="once a month">Once a month<br> : <input type="radio" name="variable2" Value="rarely">Rarely<br> Please Select a product: <input type="checkbox" name="var1">apple tree ($29) <br> : <input type="checkbox" name="var2">orange tree ($10) <br> : <input type="checkbox" name="var3">cherry tree ($12) <br> : <input type="checkbox" name="var4">magnolia tree ($36) <br> Select shipment: <select name="variable3"> <option> FedEx <option selected> UPS<option> Surface <option> Air <option> Urgent </select> <input type=submit>

</form> </body> </html>

Page 11: Web-Based Information What is Perl & What is it for? Systemsugweb.cs.ualberta.ca/~c410/F07/410/slides/L11-410-F07.pdf · • Expressions are simple and concise • There are many

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 41

#-------------------------------------------------------------------------####### Getting the input from STDIN or command line #------------------------------------------------------------------------$my_input = ($ENV{REQUEST_METHOD} eq "POST") ?

<STDIN> : $ENV{QUERY_STRING};#------------------------------------------------------------------------

####### Splitting input by parameter and value #-------------------------------------------------------------------------@my_QUERY_LIST = split( /&/, $my_input); # Splitting all pairsforeach $item (@my_QUERY_LIST) {

($my_param, $my_value) = split( /=/, $item); # Splitting variables and values$my_value =~ s/\+/ /g; # Change +'s to spaces $my_value =~ s/\s*$//; # eliminate spaces at the end$my_value =~ s/\%0D\%0A/\n/g; $my_value =~ s/%(..)/pack('C',hex($1))/ge; if ($my_in{$my_param}) {

$my_in{$my_param} .= ' ';$my_in{$my_param} .= $my_value;

} else { $my_in{$my_param} = $my_value;

}}

Parsing CGI input

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 42

$name = $my_in{‘variable1’};$habit = $my-in{‘variable2’};$expirydate=“Monday, 31-Dec-2006 23:59:00 GMT”;$servers=“129.128.0”print “Set-Cookie: Customer=$name; expires=$expirydate; domain=$servers\n“;print “Set-Cookie: Preference=$habit; expires=$expirydate\n“;

print “Content-type: text/html\n\n”;print “<HTML><HEAD><TITLE>Testing Cookies</TITLE></HEAD>\n”;print “<BODY><h1>Testing Cookies</h1>\n”;print “The cookies have been set.”;print “</BODY></HTML>\n”;

Generating Cookies in Perl

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 43

sub readCookies {@rawCookies = split (/; /,$ENV{‘HTTP_COOKIE’});foreach (@cookies) {

($cookieName, $cookieValue) = split (/=/, $_);$Cookies{$cookieName}=$cookieValue;

}return %Cookies;

}

Reading Cookies in Perl

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 44

Outline of Lecture 11• What is Perl?• Variables and Expressions• Control Structures• File Input and Output• Pattern matching• A CGI example with Perl• Cookies and example with Perl• Cookie example with JavaScript• PHP , let’s do it again

Page 12: Web-Based Information What is Perl & What is it for? Systemsugweb.cs.ualberta.ca/~c410/F07/410/slides/L11-410-F07.pdf · • Expressions are simple and concise • There are many

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 45

Simple Example

• See test1.html and test2.html

test1.html test2.html

HTML FormGenerates cookies

Displays cookie content

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 46

function SetCookie (name, value) { var argv = SetCookie.arguments; var argc = SetCookie.arguments.length; var expires = (argc < 2) ? argv[2] : null; var path = (argc < 3) ? argv[3] : null; var domain = (argc < 4) ? argv[4] : null; var secure = (argc < 5) ? argv[5] : false; document.cookie = name + "=" + escape (value) +

((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + ((path == null) ? "" : ("; path=" + path)) + ((domain == null) ? "" : ("; domain=" + domain)) + ((secure == true) ? "; secure" : "");

} function setC(form) {

var expdate = new Date (); expdate.setTime (expdate.getTime() + (24 * 60 * 60 * 1000 * 31));SetCookie (form.name, form.value, expdate);

}

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 47

<form …>Enter your name: <input type=text size=30 name=“myname" onChange="setC(this)">

</form>

Call setC() in the form for each possible input with onChange, onBlur, onClick, etc.For input fields with different values, call a function when form is submitted.

<FORM name="myform" action="JavaScript:shopper()" >

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 48

<script language="JavaScript“>function getCookieVal(offset) { // Get Cookie Value function

var endstr = document.cookie.indexOf (";", offset); if (endstr == -1) endstr = document.cookie.length; return unescape (document.cookie.substring(offset, endstr));

} function GetCookie(name) { // Get Cookie function

var arg = name+"="; var alen = arg.length; var clen = document.cookie.length; var i = 0; while (i < clen) {

var j = i + alen; if (document.cookie.substring(i, j) == arg) return getCookieVal(j); i = document.cookie.indexOf(" ", i) + 1; if (i == 0) break;

} return null;

} </script>

Page 13: Web-Based Information What is Perl & What is it for? Systemsugweb.cs.ualberta.ca/~c410/F07/410/slides/L11-410-F07.pdf · • Expressions are simple and concise • There are many

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 49

Outline of Lecture 11• What is Perl?• Variables and Expressions• Control Structures• File Input and Output• Pattern matching• A CGI example with Perl• Cookies and example with Perl• Cookie example with JavaScript• PHP, let’s do it again

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 50

What is PHP & What is it for?• PHP used to be an acronym for Personal Home

Page tools, but it is now stands for PHP Hypertext Processor since it expanded in scope.

• It is a server-side scripting language which can be embedded in HTML for Web applications.

• It competes with JSP, ASP and ColdFusion.• PHP is open source – PHP is free• PHP is cross-platform (Unix and Windows) –

Apache, fhttpd, Netscape, IIP, omni and others.

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 51

PHP is embedded in HTML<HTML><HEAD><TITLE>PHP test number 1</TITLE></HEAD><BODY><H1> Easy test in PHP</H1><?php// everything here is for the PHP processor$firstname=‘John’;$lastname = ‘Doe’;echo “$firstname $lastname”;?><p> This is now HTML <?php echo $firstname ?></P></BODY></HTML>

The PHP processor parses the page to execute php commands. HTML does not need to be rewritten in a programming language like with CGI.

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 52

About your PHP processor

<HTML><HEAD><TITLE>PHP information</TITLE></HEAD><BODY><?phpprint(“Here is the information about PHP<br><br>\n”);phpinfo();?></BODY></HTML>

Page 14: Web-Based Information What is Perl & What is it for? Systemsugweb.cs.ualberta.ca/~c410/F07/410/slides/L11-410-F07.pdf · • Expressions are simple and concise • There are many

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 53

Including files

• include(‘/filepath/filename’)• include_once(‘/filepath/filename’)• require(‘/filepath/filename’)• require_once(‘/filepath/filename’)

_once is for files that include functions to avoid redeclaring them fatal error.

Generate warning on failure

Throws exception on failure

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 54

Variables• Like in Perl all variables start with $.• A scalar variable can contain:

– a string $myVariable=“this is a string”;– a integer number $myVariable=42;– a floating-point number $myVariable=49.33;– a boolean $myVariable=TRUE;

• Variables do not need to be declared before use• Variables are case sensitive however PHP is more

permissive when it comes to keywords and function names

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 55

Arrays• Arrays in PHP are hash tables by default• They are implemented as associative arrays

(vectors indexed by string values as well as integers)

• No prefix with @ like in Perl– $myArray = array(‘bill’, ‘john’, ‘sue’, ‘Amelia’);

• An element of an array is prefixed with $– $myArray[3] = ‘alpha’; $myVar=$myArray[0];

• $myArray[‘french’] = “bonjour”;

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 56

More on arrays

• current()• next()• prev()• reset()• end()• key()

Used to simulate stacks, queues and lists with arrays

Page 15: Web-Based Information What is Perl & What is it for? Systemsugweb.cs.ualberta.ca/~c410/F07/410/slides/L11-410-F07.pdf · • Expressions are simple and concise • There are many

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 57

Object Orientation

class myClass extends myParent {var $var1;…function myClass($arg) { $this->var=$arg;}

function myFunc ($arg1, $arg2) {…print ($this->var1);…}

}

$foo= new myClass(“hello”);$foo->myFunc(33,21);

Creating an instance

Invoking a method

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 58

Conditionals• if (condition) {statements}• if (condition) statement;• if (condition) {statements} else {statements}• if (condition) {statements }

elseif (condition) {statements} else {statements}

• switch (expresion) {case value: statements; break; case value statements; break;default: statements; }

• Variable = (condition)? expression1 : expression2;

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 59

Loops• while (condition) {statements}• while (condition) statement;• do {statements} while (condition);• do statement; while (condition);• for (init;condition;increment) {statements}• for (init;condition;increment) statement;• foreach ($arrayVar, as $elementVar)

{statement}– foreach ($myArray as $line) {print “$line\n”;}

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 60

Files• $fd = fopen($filename, “r+”) or die(“can’t open”);• $fstring= fread($fd, filesize($filename));• $fout =fwrite($fd, $fstring);• fclose($fd);• $fd = fopen(http://www.cs.ualberta.ca/~zaiane/index.html,”r”);• Read only “r”• Read and write “r+”• Write only “w”• Write and read ”w+”• Write to the end “a”• Read and write to the end “a+”• Append a “b” for binary files

while (!eof($fd)) {echo fgets($fd, 4096);

}

Page 16: Web-Based Information What is Perl & What is it for? Systemsugweb.cs.ualberta.ca/~c410/F07/410/slides/L11-410-F07.pdf · • Expressions are simple and concise • There are many

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 61

PHP and MySQL in brief• $link=mysql_connect($hostname, $user, $password);• mysql_select_db($database);• @mysql_select_db($database); //silent mode• $query=“SELECT surname FROM perso WHERE ID>1234”);• $result=mysql_query($query);• $nameRow=msql_fetch_row($result);

– $nameRow[0];• $nameArray=msql_fetch_array($result);

– $nameArray[‘ID’];• $nameObject=msql_fetch_object($result);

– $nameObject->ID;• msql_close($link); Let’s see some of these in context

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 62

Building error checkingMain PHP error-checking function is calleddie():

A built-in mechanism for error-checking is error messages:mysql_error() returns an error message. You can also use mysql_errorno(), which returns

an error number.

if ($error) die(“There was an error.”);mysql_query(“SELECT * FROM students

WHERE name = ‘$searchstring’ ”) or die(“Please check the name and try again.”);

if (!mysql_select_db($db_name)) print(mysql_error());

if (!mysql_query($sql,$con)) {die('Error: ' . mysql_error());}

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 63

Connecting to MySQLThe basic command for initiating a MySQLconnection is: mysql_connect($hostname, $user, $password);

e.g.

@ mysql_connect() is a silent mode: as a security precaution, the function won’t return a message.

$con = mysql_connect("warburg.cs.ualberta.ca","zaiane", "23x3z");if (!$con) die('Could not connect: ' . mysql_error());

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 64

Selecting a databaseNext, we need a database to work with:

mysql_select_db($database);

e.g. $database = 'students';if (!mysql_select_db($database, $con))

{die('Could not open database: ' . mysql_error());}

Page 17: Web-Based Information What is Perl & What is it for? Systemsugweb.cs.ualberta.ca/~c410/F07/410/slides/L11-410-F07.pdf · • Expressions are simple and concise • There are many

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 65

Making MySQL queriesMySQL queries can be made as follows:

mysql_query($query);

e.g.$query = "SELECT Name from users WHERE grade < 55";$result = mysql_query($query) or die ("Failed query");

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 66

SQL queries• After a SELECT, mysql_results() returns

an integer called result identifier. Use:$selected_rows = mysql_num_rows($result);to find out how many rows were returned by a successful SELECT.

$query = "SELECT Name from users WHERE grade < 55";$result = mysql_query($query) or die ("Failed query");$selected_rows=mysql_num_rows($result);echo "Found ".$selected_rows . " rows";

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 67

Combining calls

Instead ofmysql_select_db($database);$result = mysql_query($query);you can also write:

$result = mysql_db_query($database, $query);

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 68

Fetching Data Sets• mysql_query and mysql_db_query simply return the status of

an operation, not the data;• the fetching functions are:

– mysql_fetch_row: returns row as enumerated array;– mysql_fetch_object: returns row as object;– mysql_fetch_array: returns row as associative array;– mysql_result: returns one cell of data;

Page 18: Web-Based Information What is Perl & What is it for? Systemsugweb.cs.ualberta.ca/~c410/F07/410/slides/L11-410-F07.pdf · • Expressions are simple and concise • There are many

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 69

Fetching rows (mysql_fetch_row)

$query = "SELECT ID, Name, Lname FROM users WHERE grade > 30 ";

$result = mysql_query($query) or die(" Query failed ");while(list($ID, $Nm, $surN) = mysql_fetch_row($result))

print(" $ID $Nm $surN <BR>\n ");

Fetching array (mysql_fetch_array)$query = " SELECT ID, Name, Lname FROM users

WHERE grade > 30 ";$result = mysql_query($query) or die(" Query failed ");while($row = mysql_fetch_array($result))

echo $row['ID']. " ". $row['Name']. " ". $row['Lname']. " <BR>\n ";

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 70

Fetching objects (mysql_fetch_object)

$query = "SELECT ID, Name, Lname FROM users WHERE grade > 30 ";

$result = mysql_query($query) or die(" Query failed ");while($object = mysql_fetch_object($result))echo $object->ID. " ". $object-> Name. " ". $object-> Lname. " <BR>\n ";

Fetching fields (mysql_result)

$query = " SELECT ID, Name, Lname FROM users WHERE ID = 12330 ";

$result = mysql_query($query) or die(" Query failed ");$field = mysql_result($result, 0, 0);

mysql_result takes three arguments: result identifier, row identifier, and (optionally) the field.

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 71

A Full Example with MySQL<?php$con = mysql_connect("warburg.cs.ualberta.ca","zaiane", "23x3z");if (!$con) die('Could not connect: ' . mysql_error());if (!mysql_select_db('students', $con))

die('Could not open database: ' . mysql_error());$query = " SELECT ID, Name, Lname FROM users

WHERE grade > 30 ";echo "<table border= \"1\"><TH>ID</TH><TH>First name</TH>

<TH>Last name</TH></TR>\n ". $result = mysql_query($query) or die(" Query failed ");while($row = mysql_fetch_array($result))

echo "<tr><td>". $row['ID']. "</td><td>". $row['Name']. "</td><td>". $row['Lname']. “</td></tr>\n ";

echo "</table>". mysql_close($con);?>

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 72

PHP and ODBC in brief• Connecting to an ODBC

• Retrieving a record

• Retrieving a field from a record

• Closing an ODBC connection

$conn=odbc_connect('somewhere', 'zaiane', '1234dw4'); $sql="SELECT * FROM customers"; $rs=odbc_exec($conn,$sql);

odbc_fetch_row($rs,2)

$studName=odbc_result($rs,1);$studName=odbc_result($rs,"LastName");

or

odbc_close($conn);

Page 19: Web-Based Information What is Perl & What is it for? Systemsugweb.cs.ualberta.ca/~c410/F07/410/slides/L11-410-F07.pdf · • Expressions are simple and concise • There are many

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 73

PHP and ORACLE• Different from MySQL and ODBC• Will be covered in the lab• Need to include OCI8 extension

include("oci8_funcs.php");$conn=OCILogon('zaiane', 'mypassword', 'myDB'); $query="SELECT * FROM customers WHERE ID=123"; $stmt=OCIParse($conn,$query);OCIExecute($stmt, OCI_DEFAULT);$err_array = OCIError($stmt);if ($err_array) die(err_array['message']);OCIFetchStatement($stmt, $res, OCI_RETURN_NULLS);OCIFreeStatement($stmt);$curtomerName = $res['Customer_Name'][2];OCILogoff($conn);

Web-based Information Systems University of Alberta Dr. Osmar R. Zaïane, 2001-2007 74

Let’s see some concrete examples with Perl and PHP.