What is Perl What is it for

Document Sample
What is Perl What is it for Powered By Docstoc
					                     Web-Based Information                                                                   What is Perl & What is it for?
                           Systems                                                                      • Perl is an acronym for Practical Extraction and Report
                                                                                                          language.
                                               Fall 2007                                                • Perl is powerful and flexible like a high-level
         CMPUT 410: Perl, PHP, Cookies and other                                                          programming language, developed in the 1980s by
                                                                                                          Larry Wall. Perl 5 is object-oriented.
                                   Dr. Osmar R. Zaïane                                                  • 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
                                   University of Alberta                                                  capability and platform independence.
 Dr. Osmar R. Zaïane, 2001-2007     Web-based Information Systems          University of Alberta   1     Dr. Osmar R. Zaïane, 2001-2007   Web-based Information Systems   University of Alberta   2




                    Course Content
                                                                                                                         Objectives of Lecture 11
    •     Introduction                           •    Perl, PHP & Cookies                                                     Perl,
                                                                                                                              Perl, PHP, Cookies and Other
    •     Internet and WWW                       •    SGML / XML
    •     Protocols                              •    CORBA & SOAP
                                                                                                          • Introduce Perl language for CGI development
    •     HTML and beyond                        •    Web Services                                          (This is not a Perl course)
    •     Animation & WWW                        •    Search Engines
                                                                                                          • Introduce PHP for web application development
    •     CGI & HTML Forms                       •    Recommender Syst.                                     (This is not a PHP course)
    •     Dynamic Pages                          •    Web Mining                                          • Learn about magic cookies and what we can use
    •     Javascript + Ajax                      •    Security Issues                                       them for.
    •     Databases & WWW                        •    Selected Topics                                     • See some examples with cookies in Perl and
                                                                                                            Javascript.
                                                                     Web-based Applications               • See an example with PHP and database access
                       Outline of Lecture 11                                                               Perl the scripting Language
                                                                                                 • Perl is commonly used to write scripts.
          •     What is Perl?                                                                    • It is interpreted and is available on most
          •     Variables and Expressions                                                          platforms (free software foundation and GNU)
          •     Control Structures                                                               • It suffices to write a script in a text file, make
          •     File Input and Output                                                              it executable and run it.
          •     Pattern matching                                                                 • Initially designed to monitor software projects
          •     A CGI example with Perl                                                            and generate reports, Perl gained popularity
          •     Cookies and example with Perl                                                      thanks to the Internet & WWW. #!/usr/local/bin/perl
          •     Cookie example with JavaScript                                                   • Example
                                                                                                                                         $input=<STDIN>;
                                                                                                                                         print “$input”;
          •     PHP, let’s do it again
 Dr. Osmar R. Zaïane, 2001-2007     Web-based Information Systems   University of Alberta   5     Dr. Osmar R. Zaïane, 2001-2007   Web-based Information Systems   University of Alberta   6




                                   Perl Capabilities                                                   Programming and Debugging
• Perl has rich and easy-to-use built-in text                                                      • Perl programs are written in any text editor
  processing capabilities.                                                                         • Start the first line with #!/usr/local/bin/perl
• Perl is very flexible when it comes to file text                                                 • You can also run a perl expression in a
  processing and pattern matching.                                                                   command line with “perl ….”
• There are many intrinsic functions for                                                           • Debugging is tricky. There are debuggers
  manipulating strings                                                                               but they are not as good as C/C++ and Java
• Expressions are simple and concise                                                                 debuggers
• There are many ways to write the same thing in                                                   • Use “perl –w” or try with “perl –c”
  Perl.                                                                                            • Use print statements in your script to trace.
                       Outline of Lecture 11                                                                                                 Scalar Variables
                                                                                                          • Scalar variables start with $. Ex. $myVariable
          •     What is Perl?
                                                                                                          • A scalar variable can contain:
          •     Variables and Expressions
                                                                                                                – a string $myVariable=“this is a string”;
          •     Control Structures
                                                                                                                – a integer number $myVariable=42;
          •     File Input and Output                                                                           – a floating-point number $myVariable=49.33;
          •     Pattern matching
                                                                                                          • A string with “string” is evaluated while a
          •     A CGI example with Perl                                                                     string with ‘string’ is not evaluated:
          •     Cookies and example with Perl                                                                   – $myString = “this is your total: $total”;
          •     Cookie example with JavaScript
          •     PHP, let’s do it again
 Dr. Osmar R. Zaïane, 2001-2007      Web-based Information Systems           University of Alberta   9    Dr. Osmar R. Zaïane, 2001-2007     Web-based Information Systems   University of Alberta   1




                                                                                                                                             Arrays and Hash
                        Perl in Loosely Typed
                                                                                                           • Arrays in Perl are indexed from 0 to n-1
 • on-the-fly conversion                                                                                   • An array is prefixed with @:
                                   $x=“4”;                                                                         – @myArray = (‘bill’, ‘john’, ‘sue’, ‘Amelia’);
                                   $y=“5”
                                   $z=$x*$y + 2;                                                           • An element of an array is prefixed with $
 • concatenation                                                                                                   – $myArray[3] = ‘alpha’; $myVar=$myArray[0];
                                                                      $z
                                   $x=“Bill”;
                                                                  BillGates                                • $#myArray is the last index of @myArray
                                   $y=“Gates”
                                   $z=$x.$y;                                                               • Hash or associative array uses keys to
                                   $x=19;                              $z                                    reference elements %myHash
                                   $y=63;
                                   $z=$x.$y;                          1963                                         – $myHash{‘billy’} = 42; $myHash{$foo}=“abc”;
                        Outline of Lecture 11
                                                                                                                                          Print Block
           •     What is Perl?
           •     Variables and Expressions                                                       • Print a block of text (with or without variables) until a
                                                                                                   given label.
           •     Control Structures                                                              • Interprets escape sequences and variables
           •     File Input and Output                                                           • No need to escape the character “
           •     Pattern matching                                                                   $x=“221 Athabasca Hall”;
                                                                                                    Print << ENDFORM;
           •     A CGI example with Perl                                                            <form action=“program.cgi” method=“GET”>
           •     Cookies and example with Perl                                                      <INPUT type=“text” value=$x name=“address”>
                                                                                                    </form>
           •     Cookie example with JavaScript                                                     ENDFORM       The convention is to use capital letters for labels.
                                                                                                                                       Closing label not indented and alone in a line.
           •     PHP, let’s do it again
  Dr. Osmar R. Zaïane, 2001-2007   Web-based Information Systems   University of Alberta   13       Dr. Osmar R. Zaïane, 2001-2007      Web-based Information Systems   University of Alberta   1




                                    Conditionals                                                                                                   Loops
                                                                                                     •     while (condition) {statements}
• if (condition) {statements}
     – if ($number) {print “the number is not zero!”;}                                               •     until (condition) {statements}
• if (condition) {statements} else {statements}                                                      •     do {statements} while (condition);
• if (condition) {statements }                                                                       •     do {statements} until (condition);
  elsif (condition) {statements}                                                                     •     for (init;condition;increment) {statements}
  else {statements}                                                                                  •     foreach (list) {statement}
• Variable = (condition)? expression1 : expression2;                                                         – foreach $line (@myArray) {print “$line\n”;}
                                                                                                     • next, last, redo
                        Outline of Lecture 11                                                                                       Opening a File
           •     What is Perl?                                                                    • open(variable, filename)
                                                                                                          – open(MYFILE, “/usr/me/myfile.txt”);
           •     Variables and Expressions
                                                                                                  • Open for writing
           •     Control Structures                                                                       – open(MYFILE, “>/usr/me/myfile.txt”);
           •     File Input and Output                                                            • Open for reading
           •     Pattern matching                                                                         – open(MYFILE, “</usr/me/myfile.txt”);
                                                                                                  • Open for appending
           •     A CGI example with Perl
                                                                                                          – open(MYFILE, “>>/usr/me/myfile.txt”);
           •     Cookies and example with Perl                                                    • Closing a file with close(MYFILE)
           •     Cookie example with JavaScript
           •     PHP, let’s do it again
  Dr. Osmar R. Zaïane, 2001-2007   Web-based Information Systems   University of Alberta   17    Dr. Osmar R. Zaïane, 2001-2007    Web-based Information Systems   University of Alberta   1




   Reading/Writing to/from a File                                                                   Determining the status of a file

• $line=<MYFILE>                                                                                  •     if (-e “file”)                   # checks if file exists
• @lines=<MYFILE>                                                                                 •     if (-d “file”)                   # checks if file is directory
   $i=1;                                                                                          •     if (-f “file”)                   #checks if file is ordinary file
   while ($line=<MYFILE>) {                                                                       •     if (-l “file”)                   #checks if file is symbolic link
      chop $line;                                                                                 •     if (-r “file”)                   #checks if file is readable
      print “line $i:[$line]\n”;
                                                                                                  •     if (-w “file”)                   #checks if file is writable
      $i++;
    }                                                                                             •     if (-x “file”)                   # checks if file is executable
• print MYFILE “this will go in the file as a line\n”;                                            •     …
                       Outline of Lecture 11
                                                                                                                              The power of Perl
          •     What is Perl?
          •     Variables and Expressions                                                        • One of the most powerful and attractive
          •     Control Structures                                                                 capabilitites of Perl is the use of regular
          •     File Input and Output                                                              expressions for pattern matching.
          •     Pattern matching                                                                 • Allows large amount of text to be searched
          •     A CGI example with Perl                                                            with relatively simple expressions.
          •     Cookies and example with Perl                                                    • if ($myString eq “hello”) # equality operator
          •     Cookie example with JavaScript                                                   • if ($myString =~ /hello/) # matching operator
          •     PHP , let’s do it again
 Dr. Osmar R. Zaïane, 2001-2007   Web-based Information Systems   University of Alberta   21    Dr. Osmar R. Zaïane, 2001-2007    Web-based Information Systems   University of Alberta   2




                                                                                                                                   Substitutions
                              Pattern Matching
 •     if ($myString =~ /^hello/) # at the beginning                                             • Substitution is replacing substrings with
 •     if ($myString =~ /hello$/) # at the end                                                     other substrings.
 •     if ($myString !~ /hello/) # no match                                                      • $myString =~ s/\t/\s/g;
 •     if ($myString =~ / \b (\w+ ing ) \b/x)
         – $1 would be mached with a word ending with “ing”                                      • Spliting                        @myarray = split(/*/,$myString)
         – /x ignores spaces /i ignores case
 • if ($myString =~ / [^a-z0-9]/)
         – matches any character not in a to z and 0 to 9
                                                                                                    #-------------------------------------------------------------------------

                           Outline of Lecture 11                                                    #######          Getting the input from STDIN or command line
                                                                                                    #------------------------------------------------------------------------
                                                                                                                                                                                    Parsing CGI                   inpu
                                                                                                    $my_input = ($ENV{REQUEST_METHOD} eq "POST") ?
                                                                                                            <STDIN> : $ENV{QUERY_STRING};
              •     What is Perl?                                                                    #------------------------------------------------------------------------
                                                                                                    #######          Splitting input by parameter and value
              •     Variables and Expressions                                                       #-------------------------------------------------------------------------
                                                                                                    @my_QUERY_LIST = split( /&/, $my_input);                         # Splitting all pairs
              •     Control Structures                                                              foreach $item (@my_QUERY_LIST) {
                                                                                                         ($my_param, $my_value) = split( /=/, $item);                # Splitting variables and values
              •     File Input and Output                                                                $my_value =~ s/\+/ /g;                                      # Change +'s to spaces
                                                                                                         $my_value =~ s/\s*$//;                                       # eliminate spaces at the end
              •     Pattern matching                                                                     $my_value =~ s/\%0D\%0A/\n/g;
                                                                                                         $my_value =~ s/%(..)/pack('C',hex($1))/ge;
              •     A CGI example with Perl                                                              if ($my_in{$my_param}) {
                                                                                                              $my_in{$my_param} .= ' ';
              •     Cookies and example with Perl                                                             $my_in{$my_param} .= $my_value;
                                                                                                          } else {
              •     Cookie example with JavaScript                                                             $my_in{$my_param} = $my_value;
                                                                                                          }
              •     PHP , let’s do it again                                                         }
     Dr. Osmar R. Zaïane, 2001-2007   Web-based Information Systems   University of Alberta   25        Dr. Osmar R. Zaïane, 2001-2007   Web-based Information Systems                  University of Alberta      2




                                                                                                                                               Another example
                   Snippet of CGI with Perl                                                                                                    accessing parameters in a CGI with Perl
                                                                                                    #-------------------------------------------------------------------------
                                                                                                    #######                Accessing parameters using the CGI module
$name = $my_in{‘variable1’};
$habit = $my-in{‘variable2’};                                                                       #                      and importing standard functions.
                                                                                                    #------------------------------------------------------------------------
…                                                                                                   use CGI qw( :standard );
print “Content-type: text/html\n\n”; #printing the header
# printing the page                                                                                 $dtd = " -//W3C//DTD HTML 4.01 Transitional//EN ";
print “<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">”;                           print( header());                  Returns: Content-type: text/html\n\n
print “<HTML><HEAD><TITLE>Testing Cookies</TITLE></HEAD>\n”;
                                                                                                    print( start_html({dtd=>$dtd, title => " My page title "}));
print “<BODY><h1>My page title</h1>\n”;
                                                                                                    $firstName=param(" fname");                                 Deals with tags in the header
…                                                                                                   $lastName=param(" lname ");                                 <HTML><HEAD><TITLE> up to <BODY>
                                                                                                    …
print “</BODY></HTML>\n”;                                                                                                                                                  No need to build the data
                                                                                                                                                                           structure and do all the parsing
                       Outline of Lecture 11
                                                                                                                                    Hidden Fields
          •     What is Perl?
          •     Variables and Expressions                                                         • You have used hidden fields in your
          •     Control Structures                                                                  assignment 2 to maintain some data
          •     File Input and Output                                                               between different forms in the same session.
          •     Pattern matching                                                                  • This data is lost in later sessions.
          •     A CGI example with Perl                                                           • Nothing is actually stored on the client.
          •     Cookies and example with Perl                                                     • How do we store data on the client to
          •     Cookie example with JavaScript                                                      maintain persistent data between sessions?
          •     PHP , let’s do it again
 Dr. Osmar R. Zaïane, 2001-2007    Web-based Information Systems   University of Alberta   29    Dr. Osmar R. Zaïane, 2001-2007    Web-based Information Systems             University of Alberta   3




                                                                                                                               Cookie Life Cycle
                                   Magic Cookies                                                 1                                                       2
                                                                                                                     Get URL1                                         Page1

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

 • The server creates the cookie and sends it to                                                                       Cookie                                         Cookie
   the browser which will send it back each
   time it connects to the server again.                                                          The browser always sends                                 The server may send back
                                                                                                  back the cookie to the                                   the cookie with changes
                                                                                                  server
                 Cookies are not Forever                                                                                           Passing Cookies
 • A cookie has an expiry date attached to it                                                    • The client receives a cookie in the HTTP
 • After the expiry date, the browser                                                              response header with Set-Cookie
   automatically deletes the cookie                                                              • Set-cookie: name=cName; value=cValue;…
 • If no expiry date is specified, the cookie last                                               • The CGI running on the server receives the
   only for the current session.                                                                   cookie in an HTTP variable HTTP-COOKIE
 • The expiry date is of the form:                                                               • When constructing the HTTP response header,
         WeekDay DD-Month-YYYY HH:MM:SS GMT                                                        the CGI adds a cookie with set-cookie.

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




                                                                                                                              Cookie Attributes
                  Restrictions on Cookies
                                                                                                 •     Name                              cookie name
 • Cookies are sent back only to the server that
   generated them or to the Internet domain                                                      •     Value                             value attached to cookie
   specified by the creator of the cookie.                                                       •     Domain                            domain that can receive cookie
 • Cookies can be restricted within a site (web                                                  •     Path                              restricts the cookie in the site
   server) using a specified path.
                                                                                                 •     Expires                           expiry date
 • The size of a cookie is limited to 4 Kb.
                                                                                                 •     Secure                            specifies that the cookie is
 • No more than 20 cookies can be created at a
   time.                                                                                                                                 encrypted (not very secure)
                            Syntax for Cookies                                                                 What are Cookies Used For?
 • A cookie with all its attributes is defines in
   one line with attributes separated by “;”                                                             • Cookies are used whenever a Web Application
                                                                                                           needs to store information on the client-side for
       Set-Cookie: name=test; value=20;                                                                    persistent state
       expires=Tuesday, 13 Feb 2007 16:00:00 GMT;
       domain=.ualberta.ca                                                                               • Used as a cart in e-commerce applications
                                                                                                         • Used to personalize web pages (user preferences)
 • The value can not have spaces and semi-
                                                                                                         • Used to identify users and sessions
   column, etc.    use escaped characters.
                                                                                                         • Used to track users on a site for user behaviour
 • If more than one cookie are needed by the                                                               analysis
   application then it is necessary to have each                                                         • Etc.
   cookie with one set-cookie line.
 Dr. Osmar R. Zaïane, 2001-2007   Web-based Information Systems        University of Alberta   37       Dr. Osmar R. Zaïane, 2001-2007   Web-based Information Systems   University of Alberta   3




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

                                                             • We want to create a                   <FORM name="myform" action=“cgi-bin/cookies.pl" >
                                                                                                     Enter your name: <input type="text" name= "variable1" size=20 > <br>
                                                               cookie to store in                    How often do you buy online
                                                               the browser                           : <input type="radio" name="variable2" Value="every day">Every day<br>
                                                                                                     : <input type="radio" name="variable2" Value="once a week">Once a week<br>
                                                               information about                     : <input type="radio" name="variable2" Value="once a month">Once a month<br>
                                                               the customer, the                     : <input type="radio" name="variable2" Value="rarely">Rarely<br>
                                                                                                     Please Select a product
                                                               preferences, as well                  : <input type="checkbox" name="var1">apple tree ($29) <br>
                                                                                                     : <input type="checkbox" name="var2">orange tree ($10) <br>
                                                               as the cart.                          : <input type="checkbox" name="var3">cherry tree ($12) <br>
                                                             • We will create                        : <input type="checkbox" name="var4">magnolia tree ($36) <br>
                                                                                                     Select shipment: <select name="variable3"> <option> FedEx <option selected> UP
                                                               different cookies.                      <option> Surface <option> Air <option> Urgent </select> <input type=submit>
                                                                                                     </form> </body> </html>
#######          Getting the input from STDIN or command line
                                                                                Parsing CGI             input
#------------------------------------------------------------------------
$my_input = ($ENV{REQUEST_METHOD} eq "POST") ?                                                                                 Generating Cookies in Perl
        <STDIN> : $ENV{QUERY_STRING};
 #------------------------------------------------------------------------
#######          Splitting input by parameter and value                                                         $name = $my_in{‘variable1’};
#-------------------------------------------------------------------------                                      $habit = $my-in{‘variable2’};
@my_QUERY_LIST = split( /&/, $my_input);                         # Splitting all pairs                          $expirydate=“Monday, 31-Dec-2006 23:59:00 GMT”;
foreach $item (@my_QUERY_LIST) {                                                                                $servers=“129.128.0”
     ($my_param, $my_value) = split( /=/, $item);                # Splitting variables and values               print “Set-Cookie: Customer=$name; expires=$expirydate; domain=$servers\n“;
     $my_value =~ s/\+/ /g;                                      # Change +'s to spaces                         print “Set-Cookie: Preference=$habit; expires=$expirydate\n“;
     $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}) {                                                                                   print “Content-type: text/html\n\n”;
          $my_in{$my_param} .= ' ';                                                                             print “<HTML><HEAD><TITLE>Testing Cookies</TITLE></HEAD>\n”;
          $my_in{$my_param} .= $my_value;                                                                       print “<BODY><h1>Testing Cookies</h1>\n”;
      } else {                                                                                                  print “The cookies have been set.”;
           $my_in{$my_param} = $my_value;                                                                       print “</BODY></HTML>\n”;
      }
}

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




                                                                                                                                           Outline of Lecture 11
                    Reading Cookies in Perl
                                                                                                                              •     What is Perl?
                                                                                                                              •     Variables and Expressions
sub readCookies {
       @rawCookies = split (/; /,$ENV{‘HTTP_COOKIE’});                                                                        •     Control Structures
       foreach (@cookies) {                                                                                                   •     File Input and Output
              ($cookieName, $cookieValue) = split (/=/, $_);
              $Cookies{$cookieName}=$cookieValue;                                                                             •     Pattern matching
       }                                                                                                                      •     A CGI example with Perl
       return %Cookies;
}
                                                                                                                              •     Cookies and example with Perl
                                                                                                                              •     Cookie example with JavaScript
                                                                                                                              •     PHP , let’s do it again
                                                                                                            function SetCookie (name, value) {
                                                                                                              var argv = SetCookie.arguments;
                                     Simple Example                                                           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;
   • See test1.html and test2.html                                                                            var secure = (argc < 5) ? argv[5] : false;
                                                                                                              document.cookie = name + "=" + escape (value) +
                                                                                                                     ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
                                                                                                                     ((path == null) ? "" : ("; path=" + path)) +
               test1.html                                    test2.html                                              ((domain == null) ? "" : ("; domain=" + domain)) +
                                                                                                                     ((secure == true) ? "; secure" : "");
                                                                                                            }
                                                                                                            function setC(form) {
                                                                                                              var expdate = new Date ();
                                                                                                              expdate.setTime (expdate.getTime() + (24 * 60 * 60 * 1000 * 31));
           HTML Form                                        Displays cookie content                           SetCookie (form.name, form.value, expdate);
           Generates cookies                                                                                }


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




                                                                                                          <script language="JavaScript“>
                                                                                                          function getCookieVal(offset) { // Get Cookie Value function
 Call setC() in the form for each possible input with onChange,                                             var endstr = document.cookie.indexOf (";", offset);
 onBlur, onClick, etc.                                                                                      if (endstr == -1) endstr = document.cookie.length;
                                                                                                            return unescape (document.cookie.substring(offset, endstr));
 For input fields with different values, call a function when form is
                                                                                                          }
 submitted.                                                                                               function GetCookie(name) { // Get Cookie function
                                                                                                            var arg = name+"=";
<form …>                                                                                                    var alen = arg.length;
  Enter your name:                                                                                          var clen = document.cookie.length;
  <input type=text size=30 name=“myname" onChange="setC(this)">                                             var i = 0;
</form>                                                                                                     while (i < clen) {
                                                                                                               var j = i + alen;
                                                                                                               if (document.cookie.substring(i, j) == arg) return getCookieVal(j);
                                                                                                               i = document.cookie.indexOf(" ", i) + 1;
<FORM name="myform" action="JavaScript:shopper()" >                                                            if (i == 0) break;
                                                                                                            }
                                                                                                            return null;
                                                                                                          }
                                                                                                          </script>
                         Outline of Lecture 11                                                         What is PHP & What is it for?
            •     What is Perl?                                                                   • PHP used to be an acronym for Personal Home
            •     Variables and Expressions                                                         Page tools, but it is now stands for PHP
            •     Control Structures                                                                Hypertext Processor since it expanded in scope.
            •     File Input and Output                                                           • It is a server-side scripting language which can
            •     Pattern matching                                                                  be embedded in HTML for Web applications.
            •     A CGI example with Perl                                                         • It competes with JSP, ASP and ColdFusion.
            •     Cookies and example with Perl                                                   • PHP is open source – PHP is free
            •     Cookie example with JavaScript                                                  • PHP is cross-platform (Unix and Windows) –
            •     PHP, let’s do it again                                                            Apache, fhttpd, Netscape, IIP, omni and others.
   Dr. Osmar R. Zaïane, 2001-2007   Web-based Information Systems   University of Alberta   49      Dr. Osmar R. Zaïane, 2001-2007   Web-based Information Systems   University of Alberta   5




           PHP is embedded in HTML                                                                             About your PHP processor
<HTML>
<HEAD><TITLE>PHP test number 1</TITLE></HEAD>                                                     <HTML>
<BODY>                                      The PHP processor                                     <HEAD><TITLE>PHP information</TITLE></HEAD>
<H1> Easy test in PHP</H1>                  parses the page to                                    <BODY>
<?php                                       execute php commands.                                 <?php
// everything here is for the PHP processor HTML does not need to                                 print(“Here is the information about PHP<br><br>\n”);
$firstname=‘John’;                          be rewritten in a                                     phpinfo();
$lastname = ‘Doe’;                          programming language                                  ?>
echo “$firstname $lastname”;                like with CGI.                                        </BODY>
?>                                                                                                </HTML>
<p> This is now HTML <?php echo $firstname ?></P>
</BODY>
</HTML>
                                                                                                                                         Variables
                                   Including files                                               • Like in Perl all variables start with $.
                                                                                                 • A scalar variable can contain:
 •     include(‘/filepath/filename’)                                      Generate                  –     a string $myVariable=“this is a string”;
                                                                          warning on
 •     include_once(‘/filepath/filename’)                                 failure                   –    a integer number $myVariable=42;
 •     require(‘/filepath/filename’)                                                                –    a floating-point number $myVariable=49.33;
                                                                          Throws
                                                                          exception on              –    a boolean $myVariable=TRUE;
 •     require_once(‘/filepath/filename’)
                                                                          failure                • Variables do not need to be declared before use
                                                                                                 • Variables are case sensitive however PHP is more
 _once is for files that include functions to
                                                                                                   permissive when it comes to keywords and
   avoid redeclaring them       fatal error.
                                                                                                   function names
 Dr. Osmar R. Zaïane, 2001-2007    Web-based Information Systems   University of Alberta   53      Dr. Osmar R. Zaïane, 2001-2007    Web-based Information Systems   University of Alberta   5




                                           Arrays
 • Arrays in PHP are hash tables by default
                                                                                                                                      More on arrays
 • They are implemented as associative arrays
   (vectors indexed by string values as well as                                                     •     current()
   integers)                                                                                        •     next()
                                                                                                    •     prev()                            Used to simulate stacks, queues and
 • No prefix with @ like in Perl                                                                                                            lists with arrays
         – $myArray = array(‘bill’, ‘john’, ‘sue’, ‘Amelia’);                                       •     reset()
 • An element of an array is prefixed with $                                                        •     end()
         – $myArray[3] = ‘alpha’; $myVar=$myArray[0];                                               •     key()
 • $myArray[‘french’] = “bonjour”;
                            Object Orientation                                                                                                      Conditionals
                                                                                                             • if (condition) {statements}
     class myClass extends myParent {                                                                        • if (condition) statement;
     var $var1;                                                                                              • if (condition) {statements} else {statements}
     …function myClass($arg) { $this->var=$arg;}
       function myFunc ($arg1, $arg2) {
                                                                                                             • if (condition) {statements }
         …                                                                                                     elseif (condition) {statements}
         print ($this->var1);                                                                                  else {statements}
        …                                                                                                    • switch (expresion) {case value: statements; break;
       }
     }                                                                                                                              case value statements; break;
                                                                                                                                    default: statements; }
     $foo= new myClass(“hello”);                                   Creating an instance
                                                                                                             • Variable = (condition)? expression1 : expression2;
     $foo->myFunc(33,21);                                          Invoking a method
 Dr. Osmar R. Zaïane, 2001-2007   Web-based Information Systems                University of Alberta   57        Dr. Osmar R. Zaïane, 2001-2007   Web-based Information Systems   University of Alberta   5




                                            Loops                                                                                                              Files
                                                                                                             •   $fd = fopen($filename, “r+”) or die(“can’t open”);
 •     while (condition) {statements}                                                                        •   $fstring= fread($fd, filesize($filename));
 •     while (condition) statement;                                                                          •   $fout =fwrite($fd, $fstring);
 •     do {statements} while (condition);                                                                    •   fclose($fd);
                                                                                                             •   $fd = fopen(http://www.cs.ualberta.ca/~zaiane/index.html,”r”);
 •     do statement; while (condition);                                                                      •   Read only     “r”
 •     for (init;condition;increment) {statements}                                                           •   Read and write     “r+”
 •     for (init;condition;increment) statement;                                                             •   Write only     “w”                         while (!eof($fd)) {
                                                                                                             •   Write and read ”w+”                          echo fgets($fd, 4096);
 •     foreach ($arrayVar, as $elementVar)                                                                   •   Write to the end     “a”                   }
       {statement}                                                                                           •   Read and write to the end     “a+”
         – foreach ($myArray as $line) {print “$line\n”;}                                                    •   Append a “b” for binary files
                      PHP and MySQL in brief                                                                                      Building error checking
                                                                                                          Main PHP error-checking function is called
•    $link=mysql_connect($hostname, $user, $password);                                                    die():
•    mysql_select_db($database);                                                                                      if ($error) die(“There was an error.”);
•    @mysql_select_db($database); //silent mode                                                                       mysql_query(“SELECT * FROM students
•    $query=“SELECT surname FROM perso WHERE ID>1234”);                                                                               WHERE name = ‘$searchstring’ ”)
•    $result=mysql_query($query);                                                                                            or die(“Please check the name and try again.”);

•    $nameRow=msql_fetch_row($result);                                                                    A built-in mechanism for error-checking is error messages:
       – $nameRow[0];                                                                                     mysql_error() returns an error message. You can also use mysql_errorno(), which returns
• $nameArray=msql_fetch_array($result);                                                                      an error number.

       – $nameArray[‘ID’];                                                                                   if (!mysql_select_db($db_name)) print(mysql_error());
• $nameObject=msql_fetch_object($result);
       – $nameObject->ID;                                                                                    if (!mysql_query($sql,$con)) {die('Error: ' . mysql_error());}
• msql_close($link);                                    Let’s see some of these in context

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




                    Connecting to MySQL                                                                                               Selecting a database
The basic command for initiating a MySQL                                                                  Next, we need a database to work with:
connection is:
mysql_connect($hostname, $user, $password);
                                                                                                          mysql_select_db($database);
e.g.
    $con = mysql_connect("warburg.cs.ualberta.ca","zaiane", "23x3z");
                                                                                                          e.g.               $database = 'students';
                                                                                                                             if (!mysql_select_db($database, $con))
    if (!$con) die('Could not connect: ' . mysql_error());                                                                     {
                                                                                                                               die('Could not open database: ' . mysql_error());
@ mysql_connect() is a silent mode: as a security                                                                              }
    precaution, the function won’t return a message.
              Making MySQL queries                                                                                                       SQL queries
MySQL queries can be made as follows:                                                               • After a SELECT, mysql_results() returns
                                                                                                      an integer called result identifier. Use:
mysql_query($query);                                                                                  $selected_rows = mysql_num_rows($result);
                                                                                                      to find out how many rows were returned
e.g.                                                                                                  by a successful SELECT.
$query = "SELECT Name from users WHERE grade < 55";                                                  $query = "SELECT Name from users WHERE grade < 55";
$result = mysql_query($query) or die ("Failed query");                                               $result = mysql_query($query) or die ("Failed query");
                                                                                                     $selected_rows=mysql_num_rows($result);
                                                                                                     echo "Found ".$selected_rows . " rows";
   Dr. Osmar R. Zaïane, 2001-2007     Web-based Information Systems   University of Alberta   65      Dr. Osmar R. Zaïane, 2001-2007   Web-based Information Systems   University of Alberta   6




                                     Combining calls                                                                              Fetching Data Sets
                                                                                                    • mysql_query and mysql_db_query simply return the status o
Instead of                                                                                            an operation, not the data;
 mysql_select_db($database);                                                                        • the fetching functions are:
 $result = mysql_query($query);                                                                        – mysql_fetch_row: returns row as enumerated array;
 you can also write:                                                                                   – mysql_fetch_object: returns row as object;
 $result = mysql_db_query($database, $query);                                                          – mysql_fetch_array: returns row as associative array;
                                                                                                       – mysql_result: returns one cell of data;
                 Fetching rows (mysql_fetch_row)                                                               Fetching objects (mysql_fetch_object)
$query = "SELECT ID, Name, Lname FROM users                                                        $query = "SELECT ID, Name, Lname FROM users
           WHERE grade > 30 ";                                                                               WHERE grade > 30 ";
$result = mysql_query($query) or die(" Query failed ");                                            $result = mysql_query($query) or die(" Query failed ");
 while(list($ID, $Nm, $surN) = mysql_fetch_row($result))                                            while($object = mysql_fetch_object($result))
  print(" $ID $Nm $surN <BR>\n ");                                                                 echo $object->ID. " ". $object-> Name. " ". $object-> Lname. " <BR>\n ";


               Fetching array (mysql_fetch_array)                                                                        Fetching fields (mysql_result)
$query = " SELECT ID, Name, Lname FROM users
                                                                                                   mysql_result takes three arguments: result identifier, row identifier, and (optionally) the field
          WHERE grade > 30 ";
$result = mysql_query($query) or die(" Query failed ");                                            $query = " SELECT ID, Name, Lname FROM users
 while($row = mysql_fetch_array($result))                                                                    WHERE ID = 12330 ";
  echo $row['ID']. " ". $row['Name']. " ". $row['Lname']. " <BR>\n ";                              $result = mysql_query($query) or die(" Query failed ");
                                                                                                   $field = mysql_result($result, 0, 0);

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




         A Full Example with MySQL                                                                                         PHP and ODBC in brief
<?php
$con = mysql_connect("warburg.cs.ualberta.ca","zaiane", "23x3z");                                  • Connecting to an ODBC
if (!$con) die('Could not connect: ' . mysql_error());                                               $conn=odbc_connect('somewhere', 'zaiane', '1234dw4');
if (!mysql_select_db('students', $con))
      die('Could not open database: ' . mysql_error());
                                                                                                     $sql="SELECT * FROM customers";
$query = " SELECT ID, Name, Lname FROM users                                                         $rs=odbc_exec($conn,$sql);
            WHERE grade > 30 ";
                                                                                                   • Retrieving a record
echo "<table border= \"1\"><TH>ID</TH><TH>First name</TH>
       <TH>Last name</TH></TR>\n ".                                                                      odbc_fetch_row($rs,2)
$result = mysql_query($query) or die(" Query failed ");                                            • Retrieving a field from a record
while($row = mysql_fetch_array($result))                                                                $studName=odbc_result($rs,1);                                     or
   echo "<tr><td>". $row['ID']. "</td><td>". $row['Name'].
         "</td><td>". $row['Lname']. “</td></tr>\n ";
                                                                                                        $studName=odbc_result($rs,"LastName");
echo "</table>".                                                                                   • Closing an ODBC connection
mysql_close($con);
?>                                                                                                      odbc_close($conn);
                                 PHP and ORACLE                                                            Let’s see some concrete examples
•   Different from MySQL and ODBC
•
•
    Will be covered in the lab
    Need to include OCI8 extension
                                                                                                                   with Perl and PHP.
          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);
     Dr. Osmar R. Zaïane, 2001-2007   Web-based Information Systems   University of Alberta   73    Dr. Osmar R. Zaïane, 2001-2007   Web-based Information Systems   University of Alberta   7