Upload
others
View
16
Download
0
Embed Size (px)
Citation preview
CSCB20 – Week 8
Introduction to Database and Web Application Programming
Anna Bretscher*
Winter 2016 *thanks to Alan Rosselet for providing the slides these are adapted from.
Web Programming We have seen how HTML and CSS work together to create a Web page (HTML) with styling details applied (CSS) When you type a URL for an HTML document into a browser window:
o browser sends a request to the server (mathlab in this case), o the server locates the requested file (test.html), o sends that file back to the browser to be rendered
Rather than providing the name of a file in a URL, it is possible to give the name of a program:
o server executes the program o sends its output back to the browser to be rendered, e.g.: https://mathlab.utsc.utoronto.ca/…/hello.php
What is PHP? PHP == ‘PHP Hypertext Preprocessor’.
o Free and open-source, server-side scripting language designed specifically for the Web
o Used to generate dynamic web-pages
o Supported by most Web servers
PHP scripts o are bracketed by reserved PHP tags
o supports embedding of PHP scripts within HTML pages
o easy to learn operational behavior and common patterns for working with Web pages
PHP Overview (cont’d) • Interpreted language
• Scripts are parsed at run-time rather than compiled beforehand
• Executed on the server-side
• Source-code not visible to client
• ‘View Source’ in browsers does not display PHP code, only output produced by PHP code
• Various built-in functions allow for fast development
• Compatible with many popular databases
• LAMP (Linux, Apache, MySQL, PHP) is a common Web application platform – all components are free, open-source
• Syntax Perl- and C-like syntax. Relatively easy to learn
• Large function library
• Embedded directly into HTML
• Interpreted, no need to compile
• Loosely typed, like Python and JavaScript
PHP CSCB20 Databases and Web Apps
5
PHP Overview
PHP is but one of many server-side languages for developing dynamic Web app’s, other options include:
o Java Servlets with JSP, Ruby on Rails, ASP .Net
Why choose PHP?
o easy deployment – no complex infrastructure to set up
o compatible: supported by most popular Web servers
o simple: lots of built-in functionality; familiar syntax
o free and open source: anyone can run a PHP-enabled server free of charge
o available: installed on most commercial Web hosts, and on UTSC servers, including mathlab
Why PHP?
browser requests .html file (static content); o server sends file content
browser requests .php file (dynamic content); o server reads file, o executes any embedded script content, o sends output of script back to browser.
PHP Web Page Request Lifecycle
What does PHP code look like?• Structurally similar to C/C++, Java • Supports procedural and object-‐oriented paradigms • All PHP statements end with a semi-‐colon • Each PHP script must be enclosed in the reserved PHP
tag, denoted by
• PHP code block may contain statements, funcJon definiJons, variable-‐value references
<?php … ?>
<!-– hello.php --> <html><body> <strong>Hello World!</strong><br /> <?php print "<h2>Hello, World</h2>"; ?> </body></html>
Hello World in PHP
Output generated by PHP “print” and “echo” statements is inserted into the HTML returned to the browser. Q. How do you view the output of a PHP script from a browser? Place hello.php in your cscb20w16_space directory, then view in a browser with URL: https://mathlab.utsc.utoronto.ca/courses/cscb20w16/UTORid/hello.php
Variables in PHP • PHP variables begin with a “$” sign, both for
declaration and value reference
• Case-sensitive ($Foo != $foo != $fOo)
• Global and locally-scoped variables o global variables can be used anywhere o local variables restricted to a function or class
• Certain variable names reserved by PHP o Form variables ($_POST, $_GET) o Server variables ($_SERVER) o Etc.
Variable Usage and Comments
<?php $foo = 25; // Numerical variable $bar = “Hello”; // String variable $foo = ($foo * 7); // Multiplies foo by 7 $bar = ($bar * 7); // Invalid expression ?>
single-line comments are written as one of:
// single-line comment
# single-line comment multi-line comments bracketed by
/* multi-line comment ... */
Data TypesPHP is a loosely-typed language, like Python PHP basic types are:
o int, float, boolean, string, array, object, NULL o functions is_type() test whether a variable has a certain
type, e.g. is_string($myvar) Conversion between types is automatic in many cases, e.g.:
o string to int for “+” o int to float for “/”
Types can be “cast” to another type using:
$int_val = (int) “33”;
Strings $myvar = "hello"; print $myvar[1]; # prints “e”
square bracket notation for 0-based indexing catenation using “.” operator (not “+”)
print $myvar . "world"; # prints hello world strings quoted with double quotes are “interpreted”, meaning that embedded variables have their values inserted strings quoted with single quotes are not interpreted
print "$myvar world"; # prints hello world print '$myvar world'; # prints $myvar world
for loop for (initialization; condition; update) { statements
} uses same syntax as Java
for ($i = 10; $i >= 0; $i--) {
print "$i cubed is " . $i * $i * $i . ".\n";
}
for loop for (initialization; condition; update) { statements
} uses same syntax as Java
$name = "preprocessor";
for ($i = 0; $i < strlen($name); $i++) {
print "The next letter is".{$name[$i]}\n"; }
if/else statement if (condition) { statements;
} elseif (condition) { statements;
} else {
statements; }
• elseif clause and else clause are both optional • multiple elseif clauses may be used
<?php if ($user==“John”) { print “Hello John.”; } else { print “You aren’t John.”; } ?>
while loop same syntax as Java
while (condition) { statements;
}
or
do {
statements; } while (condition)
<?php $count=0; while($count<3) {
print “hello PHP. ”; $count += 1; // or // $count = $count + 1; // or // $count++;
} ?>
hello PHP. hello PHP. hello PHP.
Arrays (ie, lists) $myvar = array(); # create new array
$myvar = array(val0, val1, ..., valN);
$myvar[index]; # element at position index
$myvar[index] = val0; # assign element at index
$myvar[] = valN; # append valN
$a1 = array(); # empty, length-0 array
$a[2] = 12; # store 12 in 3rd position of array
$a2 = array("a", "sequence", "of", "strings"); $a2[] = "the end"; # new last element of $a2
foreach loop foreach ($array as $element) {
... }
Similar to Pythonʼ’s: for element in array: Simpler than regular “for” loop when using arrays $a = array("a", "sequence", "of", "strings"); for ($i = 0; i < count($a); $i++) {
print "the next word is {$a[$i]}\n"; } foreach ($a as $element) {
print "the next word is $element\n"; }
Embedded PHP We could use PHP print and/or echo statements to generate HTML output, e.g. <?php print "<html>\n<head>\n"; print "<title>PHP Squares</title>\n"; ... for ($i = 0; i <= 10; $i++) { print "<p>$i squared is $i*$i</p>\n";
} ?> What’s wrong with this approach? Suppose you want to change the page HTML …
Embedding PHP in HTMLWrite HTML literally. When scripting is needed to compute a value, embed PHP code. General format of a PHP script written within HTML file:
HTML elements ... <!-- output as HTML --> <?php
PHP code ... # output embedded within HTML ?> HTML elements ... <?php
PHP code ... ?> HTML elements ...
Embedding PHP in HTMLGeneral format of a PHP script written within HTML file: HTML elements ... <!-- output as HTML --> <?php PHP code ... # output embedded within HTML
?> HTML elements ... The PHP code in an embedded block may consist of statements, declarations, or expression values. Here’s a sample expression block: <?= $myvar ?>
which is equivalent to
<?php print $myvar; ?>
Embedding PHP in HTMLHereʼ’s our earlier “squares” calculator, with “poor style” print statements:
<?php
print "<html>\n<head>\n";
print "<title>PHP Squares</title>\n"; ...
for ($i = 0; i <= 10; $i++) {
print "<p>$i squared is $i*$i</p>\n";
}
?>
Embedding PHP in HTMLHereʼ’s our earlier “squares” calculator, now without print statements:
<html><head>
<title>PHP Squares</title>
... <?php
for ($i = 0; $i <= 10; $i++) { ?>
<p><?= $i ?> squared is <?= $i*$i ?> </p>
<?php } ?>
... </html>
FunctionsFunctions must be defined before then can be called. Function headers are of the format:
Note that no return type is specified.
function quadratic($a, $b, $c) { return -$b + sqrt($b*$b - 4*$a*$c) / (2*$a); } $x = -2; $y = 3; $root = quadratic(1, $x, $y-2);
Unlike variables, function names are not case sensitive foo(…) == Foo(…) == FoO(…)
function functionName($arg_1, $arg_2, …, $arg_n)
Query Strings and Parameters• We refer to Web pages using URL’s (Uniform Resource Locators),
of the form http://domain_name/path_value
• We can specify parameters to PHP scripts by appending a value to the end of the URL:
http://www.google.com/search?q=androidhttps://mathlab…./cscb20w16/utorid/rancid.php?film=vampire
• Parameter name=value pairs follow the “?” at the end of the URL path_value, in 2nd example param name is film, value is vampire
• Provides a mechanism by which a user can control/customize the behavior of a server-side PHP script
Query Strings and Parameters• PHP can retrieve parameter values using the $_REQUEST array:
$_REQUEST["parameter_name"]
• Returns the parameter’s value as a string
• Can check to see if a specific parameter is set using isset():
$country_name = $_REQUEST["country"]; $population = (int) $_REQUEST["population"]; if (isset($_REQUEST["code"])) {
$code = (int) $_REQUEST["code"]; } else { $code = -1;
}
Reading Files Two ways to read the contents of a text file: 1. file(“my_file.txt”); returns array of lines in my_file.txt 2. file_get_contents(“my_file.txt”); returns a single string containing all lines in my_file.txt <?php # display lines from file as a bulleted list $cities = file("cities.txt"); foreach ($cities as $city) { ?> <li> <?= $city ?> </li> <?php } ?>
Unpacking Arrays, Splitting StringsSometimes it is useful to be able to refer to the elements of an array by individual variable names, rather than using indices $movie_info = file("info.txt");
list($title,$year) = $movie_info;
# now can use $title rather than $movie_info[0]
A string consisting of delimited values can be split (same idea as in Python)
$title = "Databases and Web Programming";
$words = explode(" ", $title);
Reading Directories • If your application needs to read from a set of files in a
directory, how can your code automatically detect and read the specific files present?
• glob enables you to use pattern matching to select files
$notes = glob("note_*.txt");
foreach ($notes as $note) {
print $note;
}
• * is just one of several “regular expression” pattern-matching forms (others include matching on character ranges, matching digits, optional characters)
Web Services • In Assignment 2 we will use PHP embedded within an
HTML document to implement dynamic HTML content • However, HTML is only one of several kinds of data a
server could produce for use by a client
• A Web service refers to use of the Web’s HTTP protocol to invoke programs and retrieve their results
• The general idea is that we should be able to call programs using URL references, just as we do to refer to Web pages
• Like tradiJonal funcJons, Web-‐service programs can take parameters and produce results, which may be wriXen as HTML, but also as XML, JSON, plain text, or other formats
Web Services and PHP • The type of output produced by a Web service must be
explicitly specified, since it can take different
• The client needs to know how to interpret the byte values returned by the server
• HTTP, the Internet protocol used for Web URL requests and responses, provides a “Content-type” header for this purpose
• In PHP, the “type” of the result value(s) defaults to HTML (“text/html”), but can be explicitly specified using:
header("Content-type: type/subtype");
• The header() function must be called before a PHP script generates any output (since the client who called the script needs the header information to interpret that output)
MIME Content-‐Types • MIME types are used to communicate the type of data sent
by a server to a client (e.g. a jpeg image, or an html file), and vice versa (e.g. a file upload from a client)
• MIME types are specified in two parts: “type/subtype”, e.g.:
MIME type related file extension text/plain .txt text/html .html, .htm, ... text/css .css application/json image/png .png image/jpg .jpeg, .jpg, .jpe text/javascript .js
A PHP Web service • Let’s examine a simple example of a PHP Web service that
take “base” and “exp” parameters, and returns the base raised to the exp (exponent) power.
• A URL to invoke this service might look like this:
hXps://mathlab…/cscb20w16/utorid/power.php?base=5&exp=3 • How would we implement this service in PHP?
<?php header("Content-type: text/plain");
$base = (int) $_GET["base"];
$exp = (int) $_GET["exp"];
$result = pow($base, $exp);
print $result; ?>
Web Service Errors • When implementing a Web service, we must make
provision for errors, such as omission of a required parameter or an invalid parameter value. E.g.
https://mathlab…/utorid/power.php?base=5&exp=w
https://mathlab…/utorid/power.php?base=5
• How should such an error be reported?
• We could return an HTML error message, but what if the client (caller) takes the result and displays it in a result <div> on their Web page, now they display an opaque error message where the user expects a number
• We need a mechanism that will enable the caller to detect that the result is an error, as opposed to a result value.
HTTP Status Codes The Web’s HTTP protocol provides a mechanism for signaling the outcome of a request, that can be used for both ordinary Web pages (e.g. 404 Not Found), and for Web services (e.g. 400 illegal request)
HTTP code
Meaning
200 OK 301-303 page has moved (temporarily or
permanently) 400 illegal request 401 authentication required 403 you are forbidden to access this page 404 page not found 410 gone; missing data or resource 500 internal server error
A Web Service with Error HandlingWe could rewrite the power() Web service to detect missing or invalid parameters as follows:
<?php $base = $_GET["base"]; $exp = $_GET["exp"]; if (is_numeric($base) and is_numeric($exp)) { header("Content-type: text/plain"); ... as before for valid input ... } else {
header("HTTP/1.1 400 Invalid Request"); die("invalid request; required parameters"); } ?>
Web Service Output Types So far, our Web service examples have output values expressed as MIME type text/plain.
More commonly, a Web service invoked from a Web page will return an HTML fragment, XML data, or JSON data.
Why an HTML fragment? Because normally the result returned by a Web service will be inserted into an existing HTML document, e.g. as the content of a <div>
Web Service Output Types Suppose we want to generate an HTML list of factorial values, up to a user-supplied value of “n”: <?php header("Content-type: text/html"); $limit = (int) $_GET["n"]; $fact = 1; for ($i = 1; $i < $limit; $i++) { ?> <li>Factorial of <?= $i ?> is <?= $fact ?> </
li> <?php $fact = $fact * $i; } ?>
Later we’ll look at how an HTML fragment, like the one generated by this script could be inserted into a Web page