CSCB20 Week 8. Introduction to Database and Web Application Programming. Anna Bretscher* Winter 2016

Similar documents
CSCB20 Week 8. Introduction to Database and Web Application Programming. Anna Bretscher* Winter 2017

Server side basics CS380

Web Programming Step by Step

URLs and web servers. Server side basics. URLs and web servers (cont.) URLs and web servers (cont.) Usually when you type a URL in your browser:

CSE 154 LECTURE 17: WEB SERVICES

PHP by Pearson Education, Inc. All Rights Reserved.

Lecture 12. PHP. cp476 PHP

Server side basics CSC 210

PHP. Interactive Web Systems

PHP Hypertext Preprocessor

Web Application Development (WAD) V th Sem BBAITM(Unit-1) By: Binit Patel

Web Scripting using PHP

PHP 1. Introduction Temasek Polytechnic

What is PHP? [1] Figure 1 [1]

Web Programming Paper Solution (Chapter wise)

Lecture 7 PHP Basics. Web Engineering CC 552

Part I. Web Technologies for Interactive Multimedia

PHP Personal Home Page PHP: Hypertext Preprocessor (Lecture 35-37)

Chapter 7:- PHP. Compiled By:- Sanjay Patel Assistant Professor, SVBIT.

1.1 A Brief Intro to the Internet

3. WWW and HTTP. Fig.3.1 Architecture of WWW

PHP: Hypertext Preprocessor. A tutorial Introduction

XML Processing & Web Services. Husni Husni.trunojoyo.ac.id

PHP. MIT 6.470, IAP 2010 Yafim Landa

Java Bytecode (binary file)

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Web Engineering (Lecture 08) WAMP

1.1 A Brief Intro to the Internet

Reading How the Web Works

Module 3 Web Component

Pace University. Fundamental Concepts of CS121 1

PHP Reference. To access MySQL manually, run the following command on the machine, called Sources, where MySQL and PhP have been installed:

Chapter 11 Outline. A Simple PHP Example Overview of Basic Features of PHP Overview of PHP Database Programming. Slide 11-2

Inf 202 Introduction to Data and Databases (Spring 2010)

LOON. Language Reference Manual THE LANGUAGE OF OBJECT NOTATION. Kyle Hughes, Jack Ricci, Chelci Houston-Borroughs, Niles Christensen, Habin Lee

CS6501 IP Unit IV Page 1

CNIT 129S: Securing Web Applications. Ch 3: Web Application Technologies

INTERNET PROGRAMMING. Software Engineering Branch / 4 th Class Computer Engineering Department University of Technology

1.1 A Brief Intro to the Internet

Java Applets, etc. Instructor: Dmitri A. Gusev. Fall Lecture 25, December 5, CS 502: Computers and Communications Technology

PHP and MySQL for Dynamic Web Sites. Intro Ed Crowley

Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Chapter 11 Introduction to PHP

Web Scripting using PHP

Global Servers. The new masters

CSC Web Technologies, Spring Web Data Exchange Formats

Full file at

PHP 5 Introduction. What You Should Already Know. What is PHP? What is a PHP File? What Can PHP Do? Why PHP?

PHP: The Basics CISC 282. October 18, Approach Thus Far

Instructor s Notes Web Data Management Web Client/Server Concepts. Web Data Management Web Client/Server Concepts

COMP284 Scripting Languages Lecture 14: JavaScript (Part 1) Handouts

Programming in Java Prof. Debasis Samanta Department of Computer Science Engineering Indian Institute of Technology, Kharagpur

UNIT -II. Language-History and Versions Introduction JavaScript in Perspective-

Web Engineering (CC 552)

Course Topics. The Three-Tier Architecture. Example 1: Airline reservations. IT360: Applied Database Systems. Introduction to PHP

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

Starting with a great calculator... Variables. Comments. Topic 5: Introduction to Programming in Matlab CSSE, UWA

Javascript. UNIVERSITY OF MASSACHUSETTS AMHERST CMPSCI 120 Fall 2010

Managing State. Chapter 13

(Frequently Asked Questions)

How to work with HTTP requests and responses

CSC Web Programming. Introduction to JavaScript

Writing Servlets and JSPs p. 1 Writing a Servlet p. 1 Writing a JSP p. 7 Compiling a Servlet p. 10 Packaging Servlets and JSPs p.

Static Webpage Development

Using Development Tools to Examine Webpages

Hello everyone! Page 1. Your folder should look like this. To start with Run your XAMPP app and start your Apache and MySQL.

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End

Programming the Web 06CS73 INTRODUCTION AND OVERVIEW. Dr. Kavi Mahesh, PESIT, Bangalore. Textbook: Programming the World Wide Web

PHP + ANGULAR4 CURRICULUM 6 WEEKS

COSC 2206 Internet Tools. The HTTP Protocol

CGS 3066: Spring 2015 JavaScript Reference

The role of semantic analysis in a compiler

Functional Programming Languages (FPL)

PHP CURRICULUM 6 WEEKS

Hypertext Transport Protocol

The PHP language. Teaching you everything about PHP? Not exactly Goal: teach you how to interact with a database via web

welcome to BOILERCAMP HOW TO WEB DEV

Quiz 1 Review Session. November 17th, 2014

BEFORE CLASS. If you haven t already installed the Firebug extension for Firefox, download it now from

C++ Programming: From Problem Analysis to Program Design, Third Edition

COMP284 Scripting Languages Lecture 11: PHP (Part 3) Handouts

JavaScript: Introduction, Types

RESTful Services. Distributed Enabling Platform

Lecture 3: Web Servers / PHP and Apache. CS 383 Web Development II Monday, January 29, 2018

Session 8. Reading and Reference. en.wikipedia.org/wiki/list_of_http_headers. en.wikipedia.org/wiki/http_status_codes

Distributed Databases and Remote Access to a Database

Backend Development. SWE 432, Fall 2017 Design and Implementation of Software for the Web

Dreamweaver is a full-featured Web application

Such JavaScript Very Wow

Assignment #3 CSCI 201 Spring % of course grade Title Weathermeister Back-End API Integration

CS 377 Database Systems. Li Xiong Department of Mathematics and Computer Science Emory University

10.1 Overview of Ajax

Programming the World Wide Web by Robert W. Sebesta

B. V. Patel Institute of BMC & IT 2014

Overview: Programming Concepts. Programming Concepts. Names, Values, And Variables

Overview: Programming Concepts. Programming Concepts. Chapter 18: Get With the Program: Fundamental Concepts Expressed in JavaScript

COMP284 Scripting Languages Lecture 9: PHP (Part 1) Handouts

Databases on the web

Creating HTML files using Notepad

Java4340r: Review. R.G. (Dick) Baldwin. 1 Table of Contents. 2 Preface

Web System and Technologies (Objective + Subjective)

Transcription:

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 PHP Overview Embedded directly into HTML Interpreted, no need to compile Loosely typed, like Python and JavaScript CSCB20 Databases and PHP 5

Why PHP? 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 PHPenabled server free of charge o available: installed on most commercial Web hosts, and on UTSC servers, including mathlab

PHP Web Page Request Lifecycle 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.

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?> PHP code block may contain statements, funcjon definijons, variable- value references

Hello World in PHP <!- hello.php --> <html><body> <strong>hello World!</strong><br /> <?php print "<h2>hello, World</h2>";?> </body></html> 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 Types PHP 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; <?php if ($user== John ) { print Hello John. ; else { print You aren t John. ;?> elseif clause and else clause are both optional multiple elseif clauses may be used

while loop same syntax as Java while (condition) { statements; do { or 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 3 rd 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 HTML Write 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 HTML General 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 HTML Hereʼ 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 HTML Hereʼ 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>

Functions Functions must be defined before then can be called. Function headers are of the format: function functionname($arg_1, $arg_2,, $arg_n) 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( )

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=android https://mathlab./cscb20w16/utorid/rancid.php?film=vampire Parameter name=value pairs follow the? at the end of the URL path_value, in 2 nd 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 Strings Sometimes 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 patternmatching 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 200 OK Meaning 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 Handling We 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