Comp 519
Comp 519
Ullrich Hustadt
1 Overview
Information
Learning Outcomes
2 Background
Internet and WWW: A First Definition
Internet and WWW: History
Internet and WWW: A Modern Definition
Distributed Systems: Fundamental Questions
Distributed Systems: Model-View-Controller
Examples
Web Programming versus App Programming
• Module co-ordinator:
Dr Ullrich Hustadt, Ashton Building, Room 1.03,
[email protected]
• Delivery:
• Two or three lectures per week (≈28 in total)
• Two lab sessions per week (≈18 in total)
Refer to your personal timetable for dates, times, and places
• On-line resources:
http://cgi.csc.liv.ac.uk/~ullrich/COMP519/
• Assessment:
Four programming assignments each worth 25% of the module mark
(68 hours vs 48 hours on COMP518; one working day per week)
Recommended Books
Learning Outcomes
By the end of this module, a student should
1 have an understanding of the range of programming techniques and
languages available to organisations and businesses and be able to
choose an appropriate architecture for a web application;
2 be able to demonstrate abilities to design and implement maintainable
web sites;
3 be able to make informed and critical decisions regarding client
development using HTML and JavaScript;
4 be able to design and implement reasonably sophisticated server-side
applications using one or more suitable technologies;
5 have the knowledge to critically analyse and evaluate web applications;
6 have a critical and systematic understanding of web protocols.
Web 6= Internet
Internet
A physical network of networks connecting billions of computers and other
devices using common protocols (TCP/IP) for sharing and transmitting
information
Key distinction:
• The internet is hardware plus protocols while the world wide web is
software plus protocols
• The world wide web is an application using the internet to transmit
information, just like many others, for example, email, SSH, FTP
COMP519 Web Programming Lecture 1 Slide L1 – 6
Background Internet and WWW: History
History (1)
History (2)
History (3)
Current Applications:
• Communication via e-mail, Twitter, etc
• Joint manipulation of concepts and actions:
Collaborative editing, Crowd sourcing,
Wikis (Wikipedia)
• E-Commerce: Online auctions and markets
• Social media, social networks,
virtual learning environments
Web 6= Internet
Distributed systems
A system in which components located on networked computers
communicate and coordinate their actions by passing messages in order to
achieve a common goal
Web 6= Internet
Key points:
• The internet already eased the development of distributed systems by
providing an appropriate infrastructure for that
• The world wide web eases the development and deployment of
interfaces to such system via a combination of web pages and
ubiquitous web browers
• The world wide web then allows every (authorised) person to
instantaneously interact with such systems
• Search engines allow users to easily find distributed systems that are
useful to them
COMP519 Web Programming Lecture 1 Slide L1 – 11
Background Distributed Systems: Fundamental Questions
NLS
The PC Era
• 1981: IBM PC 5150
• 1983: Apple Lisa
First PC with a graphical user interface
• 1985: Microsoft Windows 1.0
• 1987: HyperCard
Hypermedia system for Mac OS
• 1988: HyperStudio
HyperCard clone for MS Windows
• 1991: Instant Update
Collaborative editor for Mac OS
• 1992: CU-SeeMe Video Conferencing
Key points:
• Model, View and Controller are stored and computed locally on the PC
• It took 24 years to catch up with NLS
• This architecture dominated the industry for about 20 years
COMP519 Web Programming Lecture 1 Slide L1 – 19
Background Examples
Key points:
• The data is stored on a server farm (the ‘cloud’) which also computes
the behaviour of the model
• The view is either computed on a server farm or on the terminal
• The terminal receives user inputs and either relays those to the server
farm or directly translates it into instructions for the model
• This architecture has fought for dominance for 15 years
• Will it dominate the future?
Ullrich Hustadt
3 HTTP
Introduction
History
Requests
Character Encodings
4 HTML
Introduction
History
Elements, Attributes and Values
5 Further Reading
HTTP
HTTP: History
HTTP: History
HTTP Requests
Browser/Client −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−→ Server
GET /index.html HTTP/1.1
Host: www.example.com
Character Encodings
Character Encodings
• When two systems exchange texts, then they need to agree which
encoding they are using
; A HTTP header uses ASCII
; A HTTP message body can use an arbitrary encoding
COMP519 Web Programming Lecture 2 Slide L2 – 7
HTML Introduction
HTML: Chronology
HTML: Chronology
HTML: Chronology
HTML: Chronology
Examples:
< title > My first HTML document </ title >
<a href =" http :// cgi . csc . liv . ac . uk /" > CS Website </ a >
Non-ASCII Characters
• The HTML5 specification defines a large number of named characters
with the general format &name;
; allows access to non-ASCII and reserved characters
Named char Rendered as Named char Rendered as
Examples
Ullrich Hustadt
6 HTML
HTML5 Documents
The head-element
The body-element
7 HTML Elements for the Body
Structure
Headings
Lists
Paragraphs
Div- and Span-element
Address
Hyperlinks
8 Further Reading
HTML5 Documents
Head
Body
Headings
• Sections are meant to be organised into a hierarchy
(not necessarily using nested section-elements)
• The hierarchy can be up to six levels deep
• The heading elements h1 to h6 allow to specify a heading for a section
at the corresponding level, with h1 being the highest level and
h6 the lowest
• Web browsers typically use font-size and font-weight to distinguish
between headings at different levels
<h1 > Fruit </ h1 >
<h2 > Apples </ h2 >
<h3 > Colour </ h3 >
<h3 > Taste </ h3 >
<h2 > Oranges </ h2 >
<h3 > Colour </ h3 >
<h3 > Taste </ h3 >
http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/headings.html
Lists
There are three different types of lists:
• Ordered list: ol-element with li-elements as content
<ol >
<li > Item 1 </ li >
<li > Item 2 </ li >
</ ol >
http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/lists.html
COMP519 Web Programming Lecture 3 Slide L3 – 9
HTML Elements for the Body Lists
Lists
There are three different types of lists:
• Ordered list: ol-element with li-elements as content
Typically uses numbers or letters to label each item in the list
• Unordered list: ul-element with li-elements as content
Typically uses bullet points to label each item in the list
• Definition list: dl-element typically with pairs of
dt-elements and dd-elements as content
<dl >
<dt > Internet </ dt >
<dd > is a physical network of networks < dd >
<dt > World Wide Web </ dt >
<dd > is a collection of interlinked multimedia documents </ dd >
</ dl >
http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/lists.html
Paragraphs
Best:
<div > The body - element of an HTML document may include
<ul >
<li > headings , and
<li > paragraphs
</ ul >
as well as many other things . </ div >
COMP519 Web Programming Lecture 3 Slide L3 – 14
HTML Elements for the Body Address
Address
Hyperlinks
Hyperlinks
Hyperlinks
http://w3.f.org/f.html http://www.cb.com/b.html
<! DOCTYPE html > <! DOCTYPE html >
< html lang =" en - GB " > < html lang =" en - GB " >
< head > < head >
< title > Document A </ title > < title > Document B </ title >
</ head > </ head >
< body > < body >
<h1 > Fruit </ h1 > <h1 > Fruit </ h1 >
< h2 id =" a " > Apples </ h2 > < h2 id =" p " > Peaches < h2 >
<h3 > Colour </ h3 > <h3 > Colour </ h3 >
<h3 > Taste </ h3 > <h3 > Taste </ h3 >
< h2 id =" o " > Oranges </ h2 > < h2 id =" o " > Other </ h2 >
<h3 > Colour </ h3 > <a href =" http :// w3 . f . org / f . html # a " >
<h3 > Taste </ h3 > Apples </ a > ,
</ body > <a href =" http :// w3 . f . org / f . html # o " >
</ html > Oranges </ a >.
<a href ="# p " > Peaches </ a >
were covered above .
</ body >
</ html >
See http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/fruit.html
and http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/links.html
Ullrich Hustadt
10 Further Reading
Text-level Elements
Text-level elements
Images
The void element img allows to include images into an HTML document
< img src =" URL " alt =" descr " ... / >
Attributes include
• src specifies the URL / file name of the image
(browsers can typically deal with JPEG, GIF and PNG images)
• alt gives an alternative description that will be shown if the image
cannot be displayed
• title title of the image
• width the reserved width to which the image should be scaled in pixels
• height the reserved height to which the image should be scaled in pixels
• style can be used as an alternative to height / width
• srcset responsive images, see https://developer.mozilla.org/
en-US/docs/Learn/HTML/Multimedia_and_embedding/
Responsive_images
COMP519 Web Programming Lecture 4 Slide L4 – 4
HTML Elements for the Body Images
Images
< img src ="/ images / ashton_detail . jpg " title =" Ashton Building "
alt =" The Ashton Building at the University of Liverpool "
width ="100" >
<a href =" index . html " > < img src =" home . png " alt =" Home " > </a >
Figures
Tables
Tables
A table-element represents caption
a whole table, including the
colgroup
caption, consisting of
• a caption-element
thead tr th th th
(optional)
• zero or more
colgroup-elements tr th td td
• a thead-element
(optional) table tbody tr th td td
• zero or more
tbody-elements or one or tr th td td
more tr-elements
• a tfoot-element
(optional) tfoot tr th td td
Tables
< table >
< caption > Average marks on 1 st Semester CSMS Modules </ caption >
< thead >
<tr > < th > </ th > < th > COMP516 </ th > < th > COMP517 </ th >
<th > COMP518 </ th > < th > COMP519 </ th >
</ tr >
</ thead >
< tbody >
<tr > < th >2015 -16 </ th > < td >66.0 </ td > < td >66.3 </ td >
<td >73.0 </ td > < td >71.9 </ td >
</ tr >
<tr > < th >2016 -17 </ th > < td >66.5 </ td > < td >75.9 </ td >
<td >70.9 </ td > < td >75.9 </ td >
</ tr >
<tr > < th >2017 -18 </ th > < td >66.2 </ td > < td >69.6 </ td >
<td >70.9 </ td > < td >66.4 </ td >
</ tr >
</ tbody >
</ table >
Tables
< table >
< caption > Average marks on 1 st Semester
CSMS Modules
</ caption >
< thead >
<tr > < th > </ th > < th > COMP516 </ th > < th > COMP517 </ th >
<th > COMP518 </ th > < th > COMP519 </ th >
</ tr >
</ thead >
< tbody >
<tr > < th >2015 -16 </ th > < td >66.0 </ td > < td >66.3 </ td >
<td >73.0 </ td > < td >71.9 </ td >
</ tr >
<tr > < th >2016 -17 </ th > < td >66.5 </ td > < td >75.9 </ td >
<td >70.9 </ td > < td >75.9 </ td >
</ tr >
<tr > < th >2017 -18 </ th > < td >66.2 </ td > < td >69.6 </ td >
<td >70.9 </ td > < td >66.4 </ td >
</ tr >
</ tbody >
</ table >
http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/tables.html
COMP519 Web Programming Lecture 4 Slide L4 – 10
HTML Elements for the Body Tables
http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/tables.html
Ullrich Hustadt
11 Style Sheets
Principle
History
Overview
12 Inline Styles
Overview
Properties and Values
13 Further Reading
Style Sheets
CSS: History
• Cascading Style Sheet are called cascading since they can be defined at
different levels:
1 Inline styles apply to a single HTML element
2 Document style sheets (aka embedded styles aka internal style sheets)
apply to all elements within the body-element of an HTML document
3 External style sheets can be linked and applied to numerous HTML
documents
• Lower-level (that is, lower-numbered) style sheets can typically override
higher-level style sheets
• Style sheets can specify how HTML elements should be presented on
different screen types and/or in print
• Web users can specify personalised style sheets that can override the
styles associated with an HTML document
This can be useful, for example, to specify larger font sizes for visually
impaired users
COMP519 Web Programming Lecture 5 Slide L5 – 4
Style Sheets Overview
• Size of content, padding, border, margin, and box as well as their style
(e.g. colour) can be changed
• Arranging boxes
Deals with the relative position of boxes to each other
COMP519 Web Programming Lecture 5 Slide L5 – 5
Inline Styles Overview
Inline Styles
Using the style attribute, one can specify the presentation style
for a single HTML element:
Within the value of the style attribute, list a sequence of
property:value pairs separated by semi-colons
Example:
To make an h1 element red with an italic font shape
• set the font-style property to italic and
• set the color property to red
< h1 style =" font - style : italic ; color : red " > A Red H1 Heading </ h1 >
< ol style =" list - style - type : upper - alpha " >
< li style =" color : red " > first thing </ li >
< li style =" color : blue " >
< spand style =" color : black " > second thing </ span > </ li >
</ ol >
< ul style =" list - style - type : square ; background : Red ; padding : 20 px ;" >
< li style =" background - color :# ff9999 ; padding : 5 px ; margin : 5 px " >
one thing </ li >
< li style =" background - color :# ff9999 ; padding : 5 px ; margin : 5 px " >
or another </ li >
</ ul >
< table style =" border - style : dashed ; border - color : blue " >
< caption style =" color : red ; font - style : italic ;
text - decoration : underline " > Student data </ caption >
< tr style =" background - color : red " > < th > Name </ th > < th > Age </ th > </ tr >
<tr > < td > Chris Smith </ td > < td >19 </ td > </ tr >
<tr > < td > Pat Jones </ td > < td >20 </ td > </ tr >
<tr > < td > Doogie Howser </ td > < td >15 </ td > </ tr >
</ table >
Ullrich Hustadt
15 Further Reading
• As one might expect, the first list item appears as specified by the style
while the second item is unaffected
• Note the vertical space between the first and second item due to
padding-bottom
COMP519 Web Programming Lecture 6 Slide L6 – 7
Document Style Sheets Selectors: Basic Forms
• Note the extra vertical space between the two list items is gone while there
is extra padding below the list
• The li-elements have inherited text decoration, font weight and background
colour from the ol-element, but not padding-bottom
COMP519 Web Programming Lecture 6 Slide L6 – 8
Document Style Sheets Inheritance
Inheritance
• In CSS, inheritance controls what happens when no value is explicitly
specified for a property of an element
• CSS distinguishes between inherited properties and non-inherited
properties
• When no value for an inherited property has been specified for an
element, it inherits the value of that property from its parent element
Example:
< ol class =" alert " >
<li > Help Me ! </ li >
<li >I ’ m trapped on a COMP519 slide ! </ li >
</ ol >
Here, the ol-element is the parent element of both li-elements
• The inheritance chain potentially goes up to the root element
• The root element is the html-element of a document
• The root element is given some initial, default value for each property
Inheritance
Inheritance
• CSS distinguishes between inherited properties and non-inherited
properties
• When no value for an inherited property has been specified for an
element, it inherits the value of that property from its parent element
• When no value for a non-inherited property has been specified for an
element, the property is given the initial, default value for that property
Example:
color is an inherited property,
padding-bottom is a non-inherited property
; If color and padding-bottom are not specified for an li-element,
then color is inherited from the parent ol-element (or other list
construct) while padding-bottom gets the initial value 0
Inheritance
Consider the style directive
table { background - color : yellow ;
border : 1 px solid black ; padding : 10 px ; margin : 10 px ; }
Inheritance
We can change what properties are inherited as follows:
table { background - color : yellow ;
border : 1 px solid black ; padding : 10 px ; margin : 10 px ; }
tbody , tr , td { border : inherit ; padding : inherit ; }
• border and padding are now inherited by the table cells (td elements)
from the table element
; table cells now have individual borders and extra padding
• Note that tbody and tr not just td must be set to inherit
; there must be an uninterrupted chain of inheritance
from table to td
COMP519 Web Programming Lecture 6 Slide L6 – 13
Document Style Sheets Inheritance
Debugging CSS
Google Chrome and Mozilla Firefox allow you to inspect individual
HTML elements and can tell you how its properties come about
Specificity
• It is possible to have more than one kind of style directive that apply to
the same HTML element
• It is also possible that these style directives assign different values to the
same property
Example: Consider the style directives
h1 { background - color : yellow ; color : blue ; }
. orange { background - color : orange ; text - decoration : underline ; }
# i1 { background - color : red ; font - style : italic ; }
together with
< h1 id =" i1 " class =" orange " > What properties does this heading have ? </ h1 >
• The selector #i1 is the most specific one and therefore determines
background-color
• For other properties, the heading inherits from all three directives
COMP519 Web Programming Lecture 6 Slide L6 – 15
Document Style Sheets Specificity
Specificity
• It is possible to have more than one kind of style directive that apply to
the same HTML element
• It is also possible that these style directives assign different values to the
same property
• For such ‘conflicting’ assignments, CSS uses specificity to determine
which assignment applies to an element:
Multiple Classes
Multiple Classes
Consider the style directives
. red1 { color : red ; background - color : yellow ; margin : 5 px ; }
. blue { color : blue ; margin : 5 px ; }
. red2 { color : red ; background - color : yellow ; margin : 5 px ; }
together with the HTML markup
<p class =" red1 blue " > class =" red1 blue " , blue after red1 in style sheet </ p >
<p class =" blue red1 " > class =" blue red1 " , blue after red1 in style sheet </ p >
<p class =" red2 blue " > class =" red2 blue " , red2 after blue in style sheet </ p >
<p class =" blue red2 " > class =" blue red2 " , red2 after blue in style sheet </ p >
that will be rendered as
• For two class style directives with conflicting assignments that apply to
the same element, the assignment that comes last in the style sheet is
applied
; problematic, as the style sheet might change
COMP519 Web Programming Lecture 6 Slide L6 – 18
Document Style Sheets Multiple Classes
Relative Selectors
Ullrich Hustadt
18 Further Reading
Attribute Selectors
Attribute Selectors
Attribute Selectors
Attribute Selectors
<! DOCTYPE html >
< html lang =" en - GB " >
< head >
< title > Attribute Selectors </ title >
< style type =" text / css " >
a [ href$ =". pdf "] {
padding - right : 20 px ;
padding - bottom : 5 px ;
background - image : url ( pdf - icon . png );
background - repeat : no - repeat ;
background - position : top right ;
}
a [ href ^="#"] {
background - color : gold ;
}
</ style >
</ head >
< body >
<a href =" report . pdf " > Report </ a > <a href ="# i1 " > Internal Link </ a >
</ body >
</ html >
Pseudo Classes
Pseudo Classes
Pseudo Classes
turns into
COMP519 Web Programming when the mouse
Lecture 7 Slide L7 – 9
Document Style Sheets Pseudo Elements
Pseudo Elements
Pseudo Elements
• Ideally, the developers of a website will place all style directives in one or
more external style sheets
• All web pages of that website will then link to those style sheets in order
to maintain a consistent look throughout the website
• Using external style sheets
• lowers the development cost and
• simplifies web design,
as the developers of the web pages can now focus on the content and
semantic markup of the pages,
the presentation is left to the pre-defined styles
CSS: Resources
1 Refsnes Data: CSS Tutorial. W3Schools Site. 12 October 2017.
https://www.w3schools.com/css/default.asp
(accessed 12 October 2017).
2 Refsnes Data: CSS Colors. W3Schools Site. 12 October 2017.
https://www.w3schools.com/cssref/css_colors.asp
(accessed 12 October 2017).
3 Refsnes Data: CSS Units. W3Schools Site. 12 October 2017.
https://www.w3schools.com/cssref/css_units.asp
(accessed 12 October 2017).
4 Web Education Community Group: Web Standards Curriculum: CSS.
Web Education Community Group Wiki. 28 January 2012.
http://www.w3.org/community/webed/wiki/Main_Page#CSS
(accesses 12 October 2017).
5 Bert Bos: Web Style Sheets: CSS tips & tricks. W3C. 27 July 2017.
https://www.w3.org/Style/Examples/007/
(accessed 12 October 2017).
COMP519 Web Programming Lecture 7 Slide L7 – 18
Further Reading
Ullrich Hustadt
• For a long time, web page layout was based on the extensive use of
div elements
• A web page would typically consist of roughly a handful of div elements
as follows:
< div id =" header " > ... </ div >
< div id =" nav " > ... </ div >
< div id =" main " >
< div id =" content " > ... </ div >
< div id =" ads " > ... </ div >
</ div >
< div id =" footer " > ... </ div >
possibly with additional div elements inside each of those
• Layout is then a matter of arranging those div elements
• Decisions on layout are a matter of design, not of technical possibility
; there is typically not one right answer
; this is not a topic for this module (web programming vs web design)
http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/layout2.html
COMP519 Web Programming Lecture 8 Slide L8 – 10
Layout Via Divisions Relevant Properties
http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/layout2.html
COMP519 Web Programming Lecture 8 Slide L8 – 11
Layout Via Divisions Relevant Properties
• However, if the style directives in the these different style sheets are
largely identical, this is not an optimal approach
; the same style directives exist in several files,
changes are error prone
• HTML5 provides three meachanisms to better deal with such a situation
• Import rules
• Media rules
• Support rules
COMP519 Web Programming Lecture 8 Slide L8 – 12
Layout Via Divisions Relevant Properties
• The language for media queries is an extension of the one we have seen
for the media attribute
Feature Queries
row 4 footer
This is only a glimpse of the possibilities of the CSS Grid Layout System
• CSS Flexbox Layout is a simpler layout system, typically used for parts
of a web page, not the whole page
• Flexbox distinguishes between flex containers and flex items within
those containers
• Unlike Grid, Flexbox distinguishes between a primary main axis
and a secondary cross axis
Images courtesy of Chris Coyier: A Complete Guide to Flexbox. CSS-Tricks. 28 September 2017.
https://css-tricks.com/snippets/css/a-guide-to-flexbox/ (accessed 18 October 2017).
COMP519 Web Programming Lecture 8 Slide L8 – 23
CSS Flexbox Layout Defining a Flexbox Layout
Images courtesy of Chris Coyier: A Complete Guide to Flexbox. CSS-Tricks. 28 September 2017.
https://css-tricks.com/snippets/css/a-guide-to-flexbox/ (accessed 18 October 2017).
COMP519 Web Programming Lecture 8 Slide L8 – 24
CSS Flexbox Layout Example
Width = 1000px
Width = 900px
http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/layout4.html
COMP519 Web Programming Lecture 8 Slide L8 – 25
Adaptive versus Responsive Design
Adaptive Design
Uses a limited number of different web pages and/or different styles
depending on media devices and media attributes
Responsive design
Uses a single web page and style that through the use of
• media queries,
• flexible grids,
• relative units and
• responsive images
tries to adjust to any media device with any media attributes at any time
Responsive design
Uses a single web page and style that through the use of media queries,
flexible grids, relative units and responsive images tries to adjust to any
media device with any media attributes at any time
Style Guide
Style Guide
• Use relative units to specify font sizes, not fixed pixel sizes
• Use images appropriately
; avoid bright background images that make foreground text
hard to read
; avoid clickable images instead of standard buttons for links
as they can slow down the download of your page
• Do not rely on specific window size or specific font size for layout as the
user might change those
; use an adaptive or responsive design
• Break a large web page into several smaller ones or provide a menu for
navigation
• Utilise style sheets to make changes to style and layout easy and ensure
consistency across a set of web pages
• Stick to standard features and test several browsers
COMP519 Web Programming Lecture 8 Slide L8 – 29
Further Reading
Ullrich Hustadt
25 Further Reading
Forms
Forms
Label
< label > First name ( s ): < input name =" first " id =" f1 " type =" text " > </ label >
Input
• The input element represents a ‘field’ that allows the user to enter
data of a certain type
• The type attribute of an input element determine what type of data
can be entered and in what form
Value of Data Form
type type control
text Text with no line breaks Text field
tel Phone number Text field
date Date (Year/Month/Day) Date control
email E-mail address Text field
file Zero or more files Button and file selector
color sRGB color Button and color picker
number Floating-point number Text field or spinner
password Password Text field with obscured input
Input
• The input element represents a ‘field’ that allows the user to enter
data of a certain type
• The type attribute of an input element determine what type of data
can be entered and in what form
Value of Data Form
type type control
checkbox A set of zero or more values Checkbox
from a predefined list
radio An enumerated value Radio button
button Button
submit Initiates form submission Button
reset Resets form Button
• Depending on the value of the type attribute, an input element will
have additional attributes that define its behaviour
COMP519 Web Programming Lecture 9 Slide L9 – 6
HTML Elements for the Body Form Controls
Input
• The input element represents a ‘field’ that allows the user to enter
data of a certain type
• Depending on the value of the type attribute, an input element will
have additional attributes that define its behaviour
• Common attributes include
• id: unique id used to identify the element with the document
• name: (unique) name used by the form processor to access input
• autofocus: automatically focus on this form control when the page
is loaded
• disabled: whether the form control is disabled
• required: whether the form control is required to have
a non-empty value for form submission
< input name =" studentid " id =" sid " type =" number "
min ="190000000" max ="999999999" >
< input type =" submit " >
Input
< form action =" process . php " >
< label for =" s1 " > Surname : </ label >
< input name =" surname " id =" s1 " type =" text " >
< label > First name : < input name =" first " id =" f1 " type =" text " >
</ label >
< label > StudentID : < input name =" studentid " id =" sid " type =" number "
min ="190000000" max ="999999999" > </ label >
< input type =" submit " >
</ form >
Input
< form action =" process . php " >
< label for =" s1 " > Surname : </ label >
< input name =" surname " id =" s1 " type = text >
< label > First name : < input name =" first " id =" f1 " type = text >
</ label >
< label > StudentID : < input name =" studentid " id =" sid " type = number
min ="190000000" max ="999999999" > </ label >
< input type =" submit " >
</ form >
• Entering ‘None’ into the first form and activating the submit button
sends level=UG and comment=None to process-comments.php
• Activating the hyperlink underlying ‘the first form’ focuses input on
the form with id c1
• Entering ‘None’ into the second form and activating the submit button
sends level=PG and comment=None to process-comments.php
• Activating the hyperlink underlyingLecture
COMP519 Web Programming
‘the9 second form’ focuses input on
Slide L9 – 11
HTML Elements for the Body Form Controls
Input: Submit
• An input element with type=submit represents a button that, when
activated, submits the form it is associated with
• Attributes include
• value: replaces the default label of the button
• name: (unique) name used by the form processor to access input
• formaction: Overwrite the
• formenctype: corrsponding
• formmethod: attributes of
• formnovalidate: the form
< input type = submit >
< input type = submit name =" action " value =" Submit essay " >
< input type = submit formaction =" save . php " >
Input: Number
<! - - The only allowed values below are 0.0 to 1.0 in steps of 0.1 -->
< input type = number name =" fraction " min ="0" max ="1" step ="0.1" required >
< input type = number name =" age " placeholder =" Enter your age " >
< input type = number name =" studentid " min ="190000000" max ="999999999" >
COMP519 Web Programming Lecture 9 Slide L9 – 15
HTML Elements for the Body Form Controls
Input: Text
• An input element with type=text represents a one line plain text field
for the element’s value
• Attributes include
• value: shown as ‘default’ value in the text field
• readonly: the value cannot be changed
• size: visible width of the field in characters
• minlength: minimum number of characters allowed to be entered
• maxlength: maximum number of characters allowed to be entered
• placeholder: a short hint describing the expected value of a text area
(disappears as soon as the user enters a value)
• pattern: a regular expression that the value has to match
< input type = text name =" surname " size ="100" required >
< input type = text name =" department " value =" Computer Science " readonly >
< input type = text name =" studentid " minlength ="9" maxlength ="9" >
Input: Password
Input: Checkbox
• An input element with type=checkbox represents a two-state control
(checkbox)
• The return value of a checked checkbox is on,
an unchecked checkbox returns nothing
• Attributes include
• value: replaces the ‘default’ return value
• checked: this element is selected by default
Most of the other attributes, for example, readonly are not available
< form action =" process . php " >
<p > What fruits do you like ? </p >
< label > Apples < input type = checkbox name =" fruit []" value =" a " > </ label >
< label > Oranges < input type = checkbox name =" fruit []" value =" o " > </ label >
< label > Peaches < input type = checkbox name =" fruit []" value =" p " > </ label >
< input type = submit >
</ form >
fruit[] is an array storing a subset
of {"a","o","p""} depending on
which checkboxes have been checked
COMP519 Web Programming Lecture 9 Slide L9 – 18
HTML Elements for the Body Form Controls
Input: Radio
• A set of input elements with type=radio represents a radio button
group in which only one form control can be selected/set to true
• For input elements to belong to the same radio button group
• they must be associated with the same form and
• their name-attributes must have the same value
• Attributes include
• value: replaces the ‘default’ return value on
• checked: this element is selected by default
Most of the other attributes, for example, readonly are not available
< form action =" process . php " >
<p > Please select your preferred contact method : <p >
< input type =" radio " id =" cc1 " name =" contact " value =" email " >
< label for =" cc1 " > Email </ label >
< input type =" radio " id =" cc2 " name =" contact " value =" phone " >
< label for =" cc2 " > Phone </ label >
< input type =" radio " id =" cc3 " name =" contact " value =" mail " >
< label for =" cc3 " > Mail </ label >
< input type = submit >
</ form >
COMP519 Web Programming Lecture 9 Slide L9 – 19
HTML Elements for the Body Form Controls
Input: Radio
Input: Radio
< form action =" process . php " >
<p > Please select your preferred contact method : <p >
< input type =" radio " id =" cc1 " name =" contact " value =" email " >
< label for =" cc1 " > Email </ label >
< input type =" radio " id =" cc2 " name =" contact " value =" phone " >
< label for =" cc2 " > Phone </ label >
< input type =" radio " id =" cc3 " name =" contact " value =" mail " >
< label for =" cc3 " > Mail </ label >
< input type = submit >
</ form >
Textarea
Select
• A select element represents a drop-down menu with pre-defined
options between which the user must select
• The content of a select element consists of a list of option elements
that represent those options
• A select-element can have several attributes, including
• id: unique id used to identify the element with the document
• name: (unique) name used by the form processor to access input
• multiple: allow multiple options to be selected
• required: an option must be selected that has a non-empty value
• disabled: the current selection can not be changed
• size: number of options to show to the user
• An option element can have several attributes, including
• label: the label used in the drop-down menu
• value: the value returned for the option
• selected: the option is selected by default
• disabled: the option is shown but cannot be selected
COMP519 Web Programming Lecture 9 Slide L9 – 23
HTML Elements for the Body Form Controls
Select
• A select element represents a drop-down menu with pre-defined
options between which the user must select
(often preferred over a radio button group)
• The content of a select element consists of a list of option elements
that represent those options
< label for =" module " > Select a module : </ label >
< select name =" module " >
< option value =" COMP517 " >
COMP517 : Object Oriented Software Development
</ option >
< option value =" COMP518 " >
COMP518 : Database and Information Systems
</ option >
< option value =" COMP519 " >
COMP519 : Web Programming
</ option >
</ select >
Select
< form action =" process . php " >
< label for =" module " > Select a module : </ label >
< select name =" module " >
< option value =" COMP517 " >
COMP517 : Object Oriented Software Development
</ option >
< option value =" COMP518 " >
COMP518 : Database and Information Systems
</ option >
< option value =" COMP519 " >
COMP519 : Web Programming
</ option >
</ select >
< input type =" submit " >
</ form >
Select
< form action =" process . php " >
< label for =" module " > Select a module : </ label >
< select name =" module " >
< option value =" COMP517 " >
COMP517 : Object Oriented Software Development
</ option >
< option value =" COMP518 " selected >
COMP518 : Database and Information Systems
</ option >
< option value =" COMP519 " >
COMP519 : Web Programming
</ option >
</ select >
< input type =" submit " >
</ form >
Select
< form action =" process . php " >
< label for =" module " > Your choice : </ label >
< select name =" module " required >
< option value ="" > Select a module </ option >
< option value =" COMP517 " >
COMP517 : Object Oriented Software Development
</ option >
< option value =" COMP518 " >
COMP518 : Database and Information Systems
</ option >
< option value =" COMP519 " >
COMP519 : Web Programming
</ option >
</ select >
< input type =" submit " >
</ form >
• That an option with a non-empty value is pre-selected is often not
desirable ; the user does not need to make a conscious choice
• Adding a default option with empty value and adding the attribute
required to the select element forces the user to make a conscious
choice
COMP519 Web Programming Lecture 9 Slide L9 – 27
Further Reading
Ullrich Hustadt
26 JavaScript
Motivation
Overview
Example
Scripts
Type System
27 Further Reading
JavaScript: Motivation
Scripting languages
Script
A user-readable and user-modifiable program that performs simple
operations and controls the operation of other programs
Scripting language
A programming language for writing scripts
JavaScript
JavaScript
• for security reason, scripts are limited in what they can do,
e.g. scripts cannot access the client’s filestore
JavaScript: History
JavaScript: Use
JavaScript scripts
must matc
Type h
Ullrich Hustadt
29 Arrays Literals
30 Storing Values
Variables
Assignments
Constants
32 Further Reading
Booleans
• JavaScript has a boolean datatype
with constants true and false (case sensitive)
• JavaScript offers the following boolean operators
&& (conjunction) || (disjunction) ! (negation)
• The truth tables for the boolean operators are as follows:
A B (A && B) A B (A || B)
true true B (true) true true A (true)
true false B (false) true false A (true)
false true A (false) false true B (true)
false false A (false) false false B (false)
A (! A)
true false
false true
COMP519 Web Programming Lecture 11 Slide L11 – 3
Primitive Data Types Booleans
Boolean Operators
• This means that && and || are not commutative, that is,
(A && B) is not the same as (B && A)
; often taken advantage of in programs
( denom != 0) && ( num / denom > 10)
Beware of Rounding
• You should also check what values are returned or what errors are
caused by log(0), sqrt(-1), 1/0, 0/0
(we’ll do that in another lecture)
Strings
• In JavaScript a string literal is a sequence of characters surrounded by
single-quotes or double-quotes
" This is a string " " true "
’ This is also a string ’ ’519 ’
• The escape character \ can be used to include single quotes in
single-quoted strings and double quotes in double-quoted strings:
’ This isn \ ’ t a " number " ’
" ’ We won ’ t sing \" God Save the Queen .\" ’"
• The escape character \ also must be used to include \ in a string
" This is a backslash \\" ’ This is a backslash \\ ’
• Additional escape characters are available, but do not make much sense
in the context of HTML
\b (backspace) \f (form feed) \n (newline)
\r (carriage return) \t (tab)
COMP519 Web Programming Lecture 11 Slide L11 – 8
Primitive Data Types Strings
Strings
String Operators
string.substr(start, [length])
Returns (up to) length characters of string beginning at start
"university".substr(3,2) // returns "ve" (count starts at 0)
string.indexOf(str, [start])
Returns the index number at which str starts in string after start
"university".indexOf("i",3) // returns 7 (count starts at 0)
string.match(regexp)
Returns an array of matching substrings for the regular expression
regexp in string
"0ab1".match(/[^0-9]/) // returns ["a"]
string.replace(regexp, str)
Replaces occurrences of regexp in string by str
"0ab1".replace(/[^0-9]/g,"c") // returns "0cc1"
Array Literals
Variables
Variables
Variables
Assignments
Constants
document . writeln (" Type of 23.0: " + typeof (23.0) + " < br >"
document . writeln (" Type of \"23\": " + typeof ("23") +" < br >"
var a
document . writeln (" Type of a : " + typeof ( a ) + " < br >"
Type of 23.0: number < br >
Type of "23": string < br >
Type of a : undefined < br >
• Read
• Chapter 20: The JavaScript Language: Data Types and Variables
• Chapter 20: The JavaScript Language: Calculations and Operators
of S. Schafer: Web Standards Programmer’s Reference.
Wiley Publishing, 2005.
Harold Cohen Library 518.532.S29 or
E-book http://library.liv.ac.uk/record=b2174141
• Read
• Chapter 3: Language Basics: Variables, Data Types, Operators (except
Relational and Equality)
• Chapter 4: Variables, Scope and Memory
of N. C. Zakas: Professional JavaScript for Web developers.
Wrox Press, 2009.
Harold Cohen Library 518.59.Z21 or
E-book http://library.liv.ac.uk/record=b2238913
COMP519 Web Programming Lecture 11 Slide L11 – 19
COMP519 Web Programming
Lecture 12: JavaScript (Part 3)
Handouts
Ullrich Hustadt
33 Type Conversion
Type Coercion
Type Casting
34 Comparison Operators
Equality
Less and Greater Than
Numbers Revisited: NaN and Infinity
Equality and Program Behaviour
35 Arrays
Definition
forEach-method
Array functions
Type Coercion
Type Coercion
When converting to boolean, the following values are considered false:
• the boolean false itself
• the number 0 (zero)
• the empty string, but not the string ’0’
• undefined
• null
• NaN
Type Casting
JavaScript provides several ways to explicitly type cast a value
• Apply an identity function of the target type to the value
"12" * 1 ; 12 !!"1" ; true
12 + "" ; "12" !!"0" ; true
false + "" ; "false" !!"" ; false
[12,[3,4]] + "" ; "12,3,4" !!1 ; true
[12,13] * 1 ; NaN
[12] * 1 ; 12
Type Casting
JavaScript provides several ways to explicitly type cast a value
• Wrap a value of a primitive type into an object
; JavaScript has objects Number, String, and Boolean with
unary constructors/wrappers for values of primitive types
(JavaScript does not have classes but prototypical objects)
Number("12") ; 12 Boolean("0") ; true
String(12) ; "12" Boolean(1) ; true
String(false) ; "false" Number(true) ; 1
• Use parser functions parseInt or parseFloat
parseInt("12") ; 12 parseFloat("2.5") ; 2.5
parseInt("2.5") ; 2 parseFloat("2.5e1") ; 25
parseInt("E52") ; NaN parseFloat("E5.2") ; NaN
parseInt(" 42") ; 42 parseFloat(" 4.2") ; 4.2
parseInt("2014Mar") ; 2014 parseFloat("4.2end") ; 4.2
Comparison Operators
JavaScript distinguishes between (loose) equality ==
and strict equality ===:
expr1 == expr2 Equal TRUE iff expr1 is equal to expr2
after type coercion
expr1 != expr2 Not equal TRUE iff expr1 is not equal to expr2
after type coercion
Comparison Operators
JavaScript distinguishes between (loose) equality ==
and strict equality ===:
expr1 === expr2 Strictly equal TRUE iff expr1 is equal to expr2,
and they are of the same type
expr1 !== expr2 Strictly not TRUE iff expr1 is not equal to expr2,
equal or they are not of the same type
Comparison Operators
JavaScript’s comparison operators also apply type coercion to their
operands and do so following the same rules as equality ==:
expr1 < expr2 Less than true iff expr1 is strictly less than expr2
after type coercion
expr1 > expr2 Greater than true iff expr1 is strictly greater than expr2
after type coercion
expr1 <= expr2 Less than true iff expr1 is less than or equal to expr2
or equal to after type coercion
expr1 >= expr2 Greater than true iff expr1 is greater than or equal to expr2
or equal to after type coercion
Equality
Why do we care whether 5 == true is true or false?
; it influences how our scripts behave
; it influences whether more complex objects are equal or not
PHP:
if (5) print ("5 is true ");
else print ("5 is not true ");
print (" and ");
if (5 == true ) print ("5 is equal to true ");
else print ("5 is not equal to true ");
Output: 5 is true and 5 is equal to true
JavaScript:
if (5) document . writeln ("5 is true ");
else document . writeln ("5 is not true ")
document . writeln (" and ")
if (5 == true ) document . writeln ("5 is equal to true ")
else document . writeln ("5 is not equal to true ")
Output: 5 is true and 5 is not equal to true
COMP519 Web Programming Lecture 12 Slide L12 – 12
Comparison Operators Equality and Program Behaviour
Equality
Why do we care whether 5 == true is true or false?
; it influences how our scripts behave
; it influences whether more complex objects are equal or not
PHP:
$array3 = array ("1.23 e2 " ,5);
$array4 = array ("12.3 e1 " , true );
if (( $array3 [1] == $array4 [1]) && ( $array3 [2] == $array4 [2]))
print (" The two arrays are equal ");
else print (" The two arrays are not equal ");
Output: The two arrays are equal
JavaScript:
$array3 = ["1.23 e2 " ,5]
$array4 = ["12.3 e1 " , true ]
if (( $array3 [1] == $array4 [1]) && ( $array3 [2] == $array4 [2]))
document . writeln (" The two arrays are equal ")
else document . writeln (" The two arrays are not equal ")
Output: The two arrays are not equal
COMP519 Web Programming Lecture 12 Slide L12 – 13
Comparison Operators Equality and Program Behaviour
Equality
Note: The way in which more complex data structures are compared
is also differs between PHP and JavaScript
PHP:
$array3 = array ("1.23 e2 " ,5);
$array4 = array ("12.3 e1 " , true );
if ( $array3 == $array4 )
print (" The two arrays are equal ");
else print (" The two arrays are not equal ");
Output: The two arrays are equal
JavaScript:
$array3 = ["1.23 e2 " ,5]
$array4 = ["12.3 e1 " , true ]
if ( $array3 == $array4 )
document . writeln (" The two arrays are equal ")
else document . writeln (" The two arrays are not equal ")
Output: The two arrays are not equal
COMP519 Web Programming Lecture 12 Slide L12 – 14
Arrays Definition
Arrays
Arrays
Arrays: Example
var array1 = [ ’ hello ’ , [1 , 2] , function () { return 5} , 43]
document . writeln ("1: array1 . length = "+ array1 . length +" < br >")
document . writeln ("2: array1 [3] ="+ array1 [3]+" < br >")
array1 [5] = ’ world ’
document . writeln ("3: array1 . length = "+ array1 . length +" < br >")
document . writeln ("4: array1 [4] ="+ array1 [4]+" < br >")
document . writeln ("5: array1 [5] ="+ array1 [5]+" < br >")
array1 . length = 4
document . writeln ("6: array1 [5] ="+ array1 [5]+" < br >")
var array2 = array1
array2 [3] = 7
document . writeln ("7: array1 [3] ="+ array1 [3]+" < br >")
1: array1 . length = 4 < br >
2: array1 [3] = 43 < br >
3: array1 . length = 6 < br >
4: array1 [4] = undefined < br >
5: array1 [5] = world < br >
6: array1 [5] = undefined < br >
7: array1 [3] = 7 < br >
Array functions
forEach-method
• The recommended way to iterate over all elements of an array is a
for-loop
for ( index = 0; index < arrayVar . length ; index ++) {
... arrayVar [ index ] ...
}
forEach-method
• Read
• Chapter 20: The JavaScript Language: Objects
of S. Schafer: Web Standards Programmer’s Reference.
Wiley Publishing, 2005.
Harold Cohen Library 518.532.S29 or
E-book http://library.liv.ac.uk/record=b2174141
• Read
• Chapter 3: Language Basics: Relational and Equality Operatos
• Chapter 5: Reference Types: The Array Type
• Chapter 5: Reference Types: Primitive Wrapper Types
of N. C. Zakas: Professional JavaScript for Web developers.
Wrox Press, 2009.
Harold Cohen Library 518.59.Z21 or
E-book http://library.liv.ac.uk/record=b2238913
COMP519 Web Programming Lecture 12 Slide L12 – 22
COMP519 Web Programming
Lecture 13: JavaScript (Part 4)
Handouts
Ullrich Hustadt
36 Control Structures
Conditional statements
Switch statements
While- and Do While-loops
For-loops
37 Functions
Defining a Function
Calling a function
Variable-length Argument Lists
Static Variables
Example
Nested Function Definitions
38 JavaScript Libraries
Control Structures
do {
statements
} while ( condition );
• As usual, curly brackets can be omitted if the loop onsists of only one
statement
Example:
// Compute the factorial of a given number
factorial = 1;
do {
factorial *= number - -;
} while ( number > 0);
• The break command can also be used in while-, do while-, and for-loops
and discontinues the execution of the loop
while ( value < 100) {
if ( value == 0) break ;
value ++
}
Functions
Function definitions can take several different forms in JavaScript
including:
function identifier ( param1 , param2 , ...) {
statements }
Functions
Function definitions can take several different forms in JavaScript
including:
function identifier ( param1 , param2 , ...) {
statements }
Calling a Function
A function is called by using the function name followed by a list of
arguments in parentheses
function identifier ( param1 , param2 , ...) {
...
}
... identifier ( arg1 , arg2 ,...) ... // Function call
JavaScript libraries
• Read
• Chapter 20: The JavaScript Language: Control Structures
• Chapter 20: The JavaScript Language: User-Defined Functions
of S. Schafer: Web Standards Programmer’s Reference.
Wiley Publishing, 2005.
Harold Cohen Library 518.532.S29 or
E-book http://library.liv.ac.uk/record=b2174141
• Read
• Chapter 3: Language Basics: Statements, Functions
• Chapter 5: Reference Types: The Function Type
of N. C. Zakas: Professional JavaScript for Web developers.
Wrox Press, 2009.
Harold Cohen Library 518.59.Z21 or
E-book http://library.liv.ac.uk/record=b2238913
COMP519 Web Programming Lecture 13 Slide L13 – 24
COMP519 Web Programming
Lecture 14: JavaScript (Part 5)
Handouts
Ullrich Hustadt
39 (User-defined) Objects
Object Literals
Object Constructors
Prototype Property
Public and Private Static Variables
Inheritance
Classes as Syntactic Sugar
40 Pre-defined Objects
Regular Expressions
String
Date
41 Further Reading
Object Literals
• JavaScript is an object-oriented language, but one without classes
• Instead of defining a class,
we can simply state an object literal
{ property1 : value1 , property2 : value2 , ... }
where property1, property2, . . . are property names
and value1, value2, . . . are values (expressions)
var person1 = {
age : (30 + 2) ,
gender : ’ male ’ ,
name : { first : ’Bob ’ , last : ’ Smith ’ } ,
interests : [ ’ music ’ , ’ skiing ’] ,
hello : function () { return ’ Hi ! I \ ’ m ’ + this . name . first + ’. ’ }
};
person1 . age --> 32 // dot notation
person1 [ ’ gender ’] --> ’ male ’ // bracket notation
person1 . name . first --> ’Bob ’
person1 [ ’ name ’][ ’ last ’] --> ’ Smith ’
COMP519 Web Programming Lecture 14 Slide L14 – 2
(User-defined) Objects Object Literals
Object Literals
var person1 = {
...
name : { first : ’Bob ’ , last : ’ Smith ’ } ,
hello : function () { return ’ Hi ! I \ ’ m ’ + this . name . first + ’. ’ }
};
person1 . hello () --> " Hi ! I ’ m Bob ."
Object Literals
var person1 = {
name : { first : ’Bob ’ , last : ’ Smith ’ } ,
greet : function () { return ’ Hi ! I \ ’ m ’ + name . first + ’. ’ } ,
full1 : this . name . first + " " + this . name . last ,
full2 : name . first + " " + name . last
};
person1 . greet () --> " Hi ! I ’ m undefined ."
person1 . full1 --> " undefined undefined "
person1 . full2 --> " undefined undefined "
• In person1.greet() the execution context of greet() is person1
; but name.first does not refer to person1.name.first
and this.name.first does not refer to person1.name.first
• In the (construction of the) object literal itself, this does not refer to
person1 but its execution context (the window object)
; none of name.first, name.last, this.name.first, and
this.name.last refers to properties of this object literal
Object Constructors
obj1 . setInstVar5 ( ’E ’)
obj2 . setInstVar5 ( ’F ’)
// ‘ instance method ’
Circle . prototype . area = function () {
return Circle . PI * this . r * this . r ; }
for/in-loop
• The for/in-loop allows us to go through the properties of an object
for ( var in object ) { statements }
• Within the loop we can use object[var] to access the value of the
property var
Inheritance
• The prototype property can also be used to establish
an inheritance relationship between objects
function Rectangle ( width , height ) {
this . width = width
this . height = height
this . type = ’ Rectangle ’
this . area = function () { return this . width * this . height }
}
/^\ s *[ a - z ]+\ s * $ / matches " abc " , " x " , " ab "
but not "0 abc " , " abc1 " , " AB " , ""
• The Date object can be used to access the (local) date and time
• The Date object supports various constructors
• new Date() current date and time
• new Date(milliseconds) set date to milliseconds since 1 January 1970
• new Date(dateString) set date according to dateString
• new Date(year, month, day, hours, min, sec, msec)
• Read
• Chapter 20: The JavaScript Language: Objects
of S. Schafer: Web Standards Programmer’s Reference.
Wiley Publishing, 2005.
Harold Cohen Library 518.532.S29 or
E-book http://library.liv.ac.uk/record=b2174141
• Read
• Chapter 5: Reference Types: The Object Type
• Chapter 6: Object-Oriented Programming
• Chapter 7: Anonymous Functions
of N. C. Zakas: Professional JavaScript for Web developers.
Wrox Press, 2009.
Harold Cohen Library 518.59.Z21 or
E-book http://library.liv.ac.uk/record=b2238913
COMP519 Web Programming Lecture 14 Slide L14 – 22
COMP519 Web Programming
Lecture 15: JavaScript (Part 6)
Handouts
Ullrich Hustadt
43 Further Reading
Window Object
• A window object represents an open window in a browser.
• If a document contain frames, then there is
• one window object, window, for the HTML document
• and one additional window object for each frame,
accessible via an array window.frames
• A window object has properties including
document document object for the window
history history object for the window
location location object (current URL) for the window
navigator navigator (web browser) object for the window
opener reference to the window that created the window
innerHeight inner height of a window’s content area
innerWidth inner width of a window’s content area
closed boolean value indicating whether the window is
(still) open
COMP519 Web Programming Lecture 15 Slide L15 – 3
Dynamic Web Pages Using JavaScript Window Object: Properties and Methods
Navigator Object
Properties of a navigator object include
navigator.appName the web brower’s name
navigator.appVersion the web brower’s version
Example: Load different style sheets depending on browser
< html > < head > < title > Navigator example </ title >
< script >
if ( navigator . appName == ’ Netscape ’) {
document . writeln ( ’ < link rel = stylesheet type =" text / css " ’+
href =" Netscape . css " > ’)
} else if ( navigator . appName == ’ Opera ’) {
document . writeln ( ’ < link rel = stylesheet type =" text / css " ’+
href =" Opera . css " > ’)
} else {
document . writeln ( ’ < link rel = stylesheet type =" text / css " ’+
href =" Others . css " > ’)
}
</ script > </ head >
COMP519 Web Programming Lecture 15 Slide L15 – 4
Dynamic Web Pages Using JavaScript Window Object: Properties and Methods
Window object
Methods provided by a window object include
• open(url, name [, features])
• opens a new browser window/tab
• returns a reference to a window object
• url is the URL to access in the new window; can be the empty string
• name is a name given to the window for later reference
• features is a string that determines various window features
The standard sequence for the creation of a new windows is not:
// new instance of ‘ Window ’ class
var newWin = new Window (...)
newWin . document . write ( ’ < html >... </ html > ’)
instead it is
// new window created by using ‘ open ’ with an existing one
var newWin = window . open (...)
newWin . document . write ( ’ < html >... </ html > ’)
COMP519 Web Programming Lecture 15 Slide L15 – 5
Dynamic Web Pages Using JavaScript Window Object: Properties and Methods
Window object
Methods provided by a window object include
• close()
• closes a browser window/tab
• focus()
• give focus to a window (bring the window to the front)
• blur()
• removes focus from a window (moves the window behind others)
• print()
• prints (sends to a printer) the contents of the current window
• null alert(message_string)
• creates a dialog box displaying message_string
• message_string is not interpreted as HTML markup
• focus shifts away from the current window to the dialog box
• the box contains an ‘OK’ button that the user will have to click
(alternatively, the dialog box can be closed)
for the execution of the remaining code to proceed
Example:
alert (" Local time : " + ( new Date ). toString ())
• bool confirm(message_string)
• creates a dialog box displaying message_string
• the box contains two buttons ‘Cancel’ and ‘OK’
• message_string is not interpreted as HTML markup
• focus shifts away from the current window to the dialog box
• the function returns true if the user selects ‘OK’, false otherwise
Example:
var answer = confirm (" Are you sure ?")
http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/jsValidate.html
COMP519 Web Programming Lecture 15 Slide L15 – 15
Further Reading
• Read
• Chapter 22 JavaScript Ojects and Dynamic HTML: Built-in JavaScript
Objects
of S. Schafer: Web Standards Programmer’s Reference.
Wiley Publishing, 2005.
Harold Cohen Library 518.532.S29 or
E-book http://library.liv.ac.uk/record=b2174141
• Read
• Chapter 8: The Browser Object Model
• Chapter 9: Client Detection
of N. C. Zakas: Professional JavaScript for Web developers.
Wrox Press, 2009.
Harold Cohen Library 518.59.Z21 or
E-book http://library.liv.ac.uk/record=b2238913
COMP519 Web Programming Lecture 15 Slide L15 – 16
COMP519 Web Programming
Lecture 16: JavaScript (Part 7)
Handouts
Ullrich Hustadt
45 Event-driven Programs
Introduction
Events
46 Extended Example
47 Further Reading
Arnaud Le Hors, et al, editors: Document Object Model (DOM) Level 3 Core Specification, Version 1.0,
W3C Recommendation 07 April 2004. World Wide Web Consortium, 2004.
https://www.w3.org/TR/DOM-Level-3-Core/ [accessed 9 January 2017]
COMP519 Web Programming Lecture 16 Slide L16 – 3
Dynamic Web Pages Using JavaScript Document Object and Document Object Model
// access its second tr element ; the list of children starts at 0 ( not 1).
var mySecondTrEle ment = myTbodyElement . childNodes [1];
Then – document.form1
Refers to the form named form1
– document.form1.celsius
Refers to the text field named celsius in document.form1
– document.form1.celsius.value
Refers to the attribute value in the text field named celsius
in document.form1
COMP519 Web Programming Lecture 16 Slide L16 – 5
Dynamic Web Pages Using JavaScript Accessing and Manipulating HTML Elements
Then
– document.getElementById(’celsius’)
Refers to the HTML element with ID celsius document
– document.getElementById(’celsius’).value
Refers to the attribute value in the HTML element with ID celsius
in document
• With JavaScript,
– we can define event handler functions for a wide variety of events
– event handler functions can manipulate the document object
(changing the web page in situ)
COMP519 Web Programming Lecture 16 Slide L16 – 10
Event-driven Programs Introduction
Events: Load
http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/jsOnload.html
COMP519 Web Programming Lecture 16 Slide L16 – 13
Event-driven Programs Events
• A focus event occurs when a form field receives input focus by tabbing
with the keyboard or clicking with the mouse
; onFocus attribute
• A change event occurs when a select, text, or textarea field loses focus
and its value has been modified
; onChange attribute
Example:
< form name =" form1 " method =" post " action =" process . php " >
< select name =" select " required
onChange =" document . form1 . submit ();" >
< option value ="" > Select a name </ option >
< option value ="200812345" > Tom Beck </ option >
< option value ="200867890" > Jim Kent </ option >
</ select >
</ form >
http://cgi.csc.liv.ac.uk/~ullrich/COMP284/examples/jsOnclick.html
• The interface will consist of a 3x3 table representing the board and a
section for messages, both of which will be generated dynamically
< body >
< table id =" t1 " > </ table >
< div id =" m1 " > </ div >
< script >... </ script >
</ body >
function clearMessage () {
m1 = document . getElementById (" m1 ");
m1 . style . display = " none ";
}
• Arguments x and y are the co-ordinates on which the player as placed a piece
• event is the event that was triggered and event.target gives us the
HTML element / table cell on which it was triggered
COMP519 Web Programming Lecture 16 Slide L16 – 22
Extended Example
function sleep ( ms ) {
return new Promise ( resolve = > setTimeout ( resolve , ms )) }
COMP519 Web Programming Lecture 16 Slide L16 – 25
Extended Example
• Read
• Chapter 21 The Document Object Model
• Chapter 22 JavaScript Ojects and Dynamic HTML
of S. Schafer: Web Standards Programmer’s Reference.
Wiley Publishing, 2005.
Harold Cohen Library 518.532.S29 or
E-book http://library.liv.ac.uk/record=b2174141
• Read
• Chapter 10: The Document Object Model
• Chapter 12: Events
of N. C. Zakas: Professional JavaScript for Web developers.
Wrox Press, 2009.
Harold Cohen Library 518.59.Z21 or
E-book http://library.liv.ac.uk/record=b2238913
COMP519 Web Programming Lecture 16 Slide L16 – 27
COMP519 Web Programming
Lecture 17: Python (Part 1)
Handouts
Ullrich Hustadt
48 Python
Overview
Example
Basic Syntax
Type System
50 Further Reading
Python: History
Types
Integers
• The Python immutable datatype int covers the integers
• Positive integers can be written in various ways
• Decimal literals (base 10):
A sequence of digits 0–9 not starting with 0
0 2012 40 1263978
• Binary literals (base 2):
A sequence of digits 0–1 prefixed by 0b or 0B
0b10 0b01 0b0 0b11011011
• Octal literals (base 8):
A sequence of digits 0–7 prefixed by 0o or 0O
0o10 0O20 0o40 0o1263978
• Hexadecimal literals (base 16):
A sequence of characters A–F and digits 0–9 prefixed by 0x or 0X
0x10 0X20 -0xFF -0x1236A7F
• Negative integers are obtained by applying the unary - operation to a
positive integer
COMP519 Web Programming Lecture 17 Slide L17 – 8
Primitive Data Types Integers
Integers
Modules
• A lot of functionality of Python is contained in modules
• The statement
import module1 [ , module2 [ ,... moduleN ]]
makes all functions from modules module1, module2 available, but all
function names must be prefixed by the module name
import math
print math . factorial (5)
• The statement
from module1 import fun1 [ , fun2 [ ,... funN ]]
imports the named functions from module module1 and makes them
available without the need for a prefix
from math import factorial
print factorial (5)
Complex Numbers
Strings
• String literals are elements of the immutable type str
• A string literal is a sequence of characters surrounded by single-quotes,
double-quotes, or triple-quotes
’chars’ single-quoted string
"chars" double-quoted string
’’’chars’’’ triple-quoted string, can span several lines and
"""chars""" contain single and double quotes, but not at
the start or end
’’’ This is a triple - quoted ’ string ’ containing " quotes "
and spanning more than one line ’ ’ ’
Strings
Strings
len(string)
Returns the length of a string as integer
len("university") # returns 10
string.lower()
Returns a copy of string with all characters lower-cased
"abaCUS".lower() # returns "abacus"
string.upper()
Returns a copy of string with all characters upper-cased
"abaCUS".upper() # returns "ABACUS"
Strings
string[start:after]
Returns the substring of string starting at start and ending at
after-1
"university"[3:5] # returns "ve"
string.find(str, [start])
Returns the position at which str starts in string after start
"university".find("i",3) # returns 7 (count starts at 0)
"university".find("z",0) # returns -1 (not found)
string.split(str)
Split string along occurrences of str into a list of substrings
"university".split("i") # returns ["un","vers","ty"]
"university".split("a") # returns ["university"]
"jabbaba".split("b") # returns ["ja","","a", "a"]
Booleans
Ullrich Hustadt
51 Complex Datatypes
Lists
Sets
Ranges
List and Set Comprehension
52 Equality and Comparison Operators
53 Special Values
nan and inf
None
54 Determining the Type of a Value
55 Type Conversion
56 Further Reading
List Literals
• List literals are Python’s equivalent to JavaScript’s array literals
• A list literal is a comma-separated list of values enclosed in square
brackets and it is of the mutable type list
• Each element of that list has an index position given by the number of
other elements preceding it
; the first index position is 0
• Each element of that list also has a negative index position,
with -1 for the last element, -2 for the second-last, etc
• The values in a list literal do not need to be of the same type
• The values in a list literal can include other list literals
(nested list literal)
[2 , ’two ’ , 3 , " three " , 1.1 e1 , [ True , 1.3+2 j ]]
| | | | | |
0 1 2 3 4 5
-6 -5 - 4 -3 -2 -1
COMP519 Web Programming Lecture 18 Slide L18 – 2
Complex Datatypes Lists
• It is possible to access a sublist (slice) of a list literal via the first index
position to include and the first index position to exclude:
listLiteral[start:after] (with start ≤ after)
0 1 2 3 4
| | | | |
[2 ,3 ,5 ,7 ,11][2:4] # returns [5 ,7]
[2 ,3 ,5 ,7 ,11][2:2] # returns []
[2 ,3 ,5 ,7 ,11][2:6] # returns [5 ,7 ,11]
COMP519 Web Programming Lecture 18 Slide L18 – 3
Complex Datatypes Lists
• With value not in set we can check whether value does not occur
in set
’ apple ’ not in { ’ apple ’ , ’ orange ’ , ’ pear ’} # False
’ citron ’ not in { ’ apple ’ , ’ orange ’ , ’ pear ’} # True
Op Meaning Op Meaning
== equal < strictly less than
!= not equal <= less than or equal
is object identity > strictly greater than
is not negated object identity >= greater than or equal
• Objects of different types, except different numeric types,
never compare equal
• The <, <=, > and >= operators will raise a TypeError when comparing a
complex number with another built-in numeric type or when the objects
are of different types that cannot be compared
1.23e2 <= 12.3e1 + 0j ; TypeError
"123" < 124 ; TypeError
False < 1 ; True
None
Type Conversion
• Python has several functions for type conversion
• int(value) converts a number or string value to an element of int
int(2.6) ; 2 int(-2.6) ; -2
int(True) ; 1 int(2 + 0j) ; TypeError
int("12") ; 12 int("2.0") ; ValueError
int(" 42 ") ; 42 int("\n42\t") ; 42
int("E52") ; ValueError int("2014Mar") ; ValueError
int("nan") ; ValueError int("inf") ; ValueError
int("None") ; TypeError
• float(value) converts a number or string value to an element of float
float(2) ; 2.0 float(-2) ; -2.0
float(True) ; 1.0 float(2.5 + 0j) ; Error
float("12.5e-1") ; 1.25 float("-2") ; -2.0
float(" 42.9 ") ; 42.9 float("\n-12.5e-1\t") ; -1.25
float("E52.1") ; Error float("20.14Mar") ; Error
float("nan") ; nan float("inf") ; inf
int("None") ; TypeError
COMP519 Web Programming Lecture 18 Slide L18 – 15
Type Conversion
Type Conversion
• Python has several functions for type conversion
• bool(value) converts value to an element of bool using
the truth testing procedure
• complex(real,imag) converts two floating-point numbers real and
imag to the complex number real + imag * 1j
• complex(value) converts a string or number value to an element of
complex
• str(value) converts value to an element of str
str(2) ; ’2’ str(-2.9) ; ’-2.9’
str(12.5e-1) ; ’1.25’ str(12.5e1) ; ’125.0’
str(True) ; ’True’ str(1.5 + 0j) ; ’(1.5+0j)’
str(math.nan) ; ’nan’ str(math.inf) ; ’inf’
str(None) ; ’None’
Remember: "The result is " + (5/2) produces a TypeError
"The result is " + str(5/2) must be used instead
Ullrich Hustadt
57 Storing Values
Variables
Assignments
Constants
59 Control Structures
Conditional Statements
While-loops
60 Further Reading
Variables / Names
• Strictly speaking, Python does not have variables,
it has names
• A Python (variable) name may consist of
letters, digits, and underscore,
but cannot start with a digit
; in contrast to JavaScript, the $ symbol is not allowed
• Python (variable) names are case sensitive
• Variables cannot be declared
• Variables cannot be given a type
; variables get their type from the value they are assigned to
• Python 3.6 introduced type annotations
counter : int
but this does not prevent variables from taking values of other types
(it helps static (type) analysis)
COMP519 Web Programming Lecture 19 Slide L19 – 2
Storing Values Variables
Variables / Names
Assignments
Assignments
Assignments
Constants
Lists
• If we assign a list literal to a variable, we have a list
list1 = [2 ,3 ,5 ,7 ,11]
• The operator del allows us the remove parts of a list (literal) list by
specifying a slice of it
; the list gets shorter if a non-empty slice is removed
del ( list1 [0]) # deletes element with index 0
del ( list1 [2:5]) # deletes elements with index 2 , 3 , 4
del ( list1 [:2]) # deletes elements with index 0 , 1
del ( list1 [3:]) # deletes elements with index 3 to end
del ( list1 [:]) # list1 becomes the empty list
COMP519 Web Programming Lecture 19 Slide L19 – 8
Storing Values Constants
Lists
b = [ ’A ’ , ’b ’ , ’a ’ , ’B ’]
b . sort () # b now is [ ’A ’ , ’B ’ , ’a ’ , ’b ’]
b . sort ( key = str . lower ) # b now is [ ’A ’ , ’a ’ , ’B ’ , ’b ’]
cmp = lambda v : ( v . upper () , v [0]. isupper ())
b . sort ( key = cmp ) # b now is [ ’a ’ , ’A ’ , ’b ’ , ’B ’]
Lists
a = [2 ,11 ,3 ,7 ,5]
sorted ( a ) # returns [2 ,3 ,5 ,7 ,11]
print ( a ) # prints [2 ,11 ,3 ,7 ,5]
Lists
list ( zip ([" Jim " , " Joe " , " Joy "] , [33 , 28]))
# returns [(" Jim " ,33) ,(" Joe " ,28)]
list ( zip ([" a " ," b " ," c "] ,[1 ,2 ,3] ,[ True , False , True ]))
# returns [(" a " ,1 , True ) ,(" b " ,2 , False ) ,(" c " ,3 , True )]
Tuples
Dictionaries
Dictionaries
• Accessing a key that is not in a dictionary results in an error:
dct = { ’ name ’: ’ Dave ’ , ’age ’: 23 , ’ height ’: ’185 cm ’ }
print ( dct [ ’ job ’])
KeyError : ’job ’
Dictionaries: Example
Control Structures
Conditional Statements
Python conditional statements take the following form
if condition :
suite
elif condition :
suite
else :
suite
Conditional Expressions
Since Python 2.5 also supports conditional expressions
if_true_expr if condition else if_false_expr
Switch Statements
• Python has no switch statement instead a conditional statement
has to be used
switch ( expr ) { if expr == expr1 :
case expr1 : statements1
statements1 elif expr == expr2 :
break ; statements2
case expr2 : elif expr == expr3 :
statements2 statements3
break ; else :
case expr3 : statements4
statements3
break ;
default :
statements4
break ;
}
While-loops
Python offers while-loops but has no do while-loops
while condition :
suite
else :
suite
While-loops
Ullrich Hustadt
61 Control Structures
For-loops
Try Statements
62 Functions
Defining a Function
Calling a Function
Variable-length Argument Lists
Static Variables
Nested Function Definitions
63 Further Reading
For-loops
for-loops in Python take the form
for var1 ,... , varN in sequence :
suite
else :
suite
For-loops
for i in range (3): for i in range (0 ,7 ,3):
print ( i ) print ( i )
0 0
1 3
2 6
// JavaScript
for ( i = 3 , j = 3; j >= 0; i ++ , j - -)
document . writeln ( i + " - " + j + " - " + i * j )
3 - 3 - 9 4 - 2 - 8
5 - 1 - 5 6 - 0 - 0
# Python
for i , j in zip ( range (3 ,100) , range (3 , -1 , -1)):
print ( str ( i ) + " - " + str ( j ) + " - " + str ( i * j ))
3 - 3 - 9
4 - 2 - 8
5 - 1 - 5
6 - 0 - 0
For-loops
Example: Iteration over a list
oldnames = [" Dave Jackson " , " Ullrich Hustadt "]
newnames = []
print ( newnames )
[ ’ Jackson , Dave ’ , ’ Hustadt , Ullrich ’]
Try Statements
Python offers try statements to deal with exceptions
(errors other than SyntaxErrors)
• First, the try-clause is executed
try :
suite • If no exception occurs, all except-clauses
except exception : are skipped
suite
except exception :
• If an exception occurs, execution of the
suite try-clause stops and a matching
... except-clause (if it exists) is executed
except :
suite
• An except-clause without exception
finally : matches any exception
suite • The optional finally-clause is always
executed
Try Statements
import math
try :
z = x / y
except NameError :
# Either x or y was not inialised
z = None
except Zer oDivis ionError :
# A division by zero has occurred , i . e . y == 0
if x != 0:
z = math . copysign (1 , x )* math . inf
else :
z = math . nan
except :
# Another error has occured , e . g . a TypeError
z = None
print ( z )
Initial value x = 1 x = 0 x = 1 x = 1
of x and y y = 0 y = 0 y = 1 y = ’1’ y = 1
Output inf nan None None 1
COMP519 Web Programming Lecture 20 Slide L20 – 7
Control Structures Try Statements
Defining a Function
Functions are elements of type function and can be defined as follows:
def identifier ( param1 , param2 , ...):
docstring
suite
Defining a Function
Functions are elements of type function and can be defined as follows:
def identifier ( param1 , param2 , ...):
suite
Calling a Function
A function is called by using the function name followed by a list of
arguments in parentheses
def identifier ( param1 , param2 , ...):
suite
Calling a Function
A function is called by using the function name followed by a list of
arguments in parentheses
def identifier ( param1 , param2 , ...):
suite
sumAll () # returns 0
sumAll (5) # returns 5
sumAll (5 ,4 ,3) # returns 12
Ullrich Hustadt
64 Functions
Variable Scope and Functions
Static Variables
65 Classes
Defining and Instantiating a Class
Class and Instance Attributes
Deleting Instances
Class Methods
Inheritance
Magic Methods
66 Further Reading
Scope of Variables
Sope of a Variable (Occurrence)
The region of a program or the sequence of execution steps of a program
in which we can validly refer to that variable (occurrence)
Main(1):
def state (s ,a ,k ,b ,l ,c , m ):
u=1, v=2, w=[0,1,2]
print ( s + ’: ’+ a + ’= ’+ str ( k )+ ’ , ’+
b + ’= ’+ str ( l )+ ’ , ’+ c + ’= ’+ str ( m ))
Outer(1):
x=1, y=2, z=[0,1,2]
def outer (x ,y , z ):
def inner ():
Traceback (most recent call last):
state ( ’ Inner (1) ’ , ’x ’ ,x , ’y ’ ,y , ’z ’ , z )
line 20, in <module>
x = 3
outer(u,v,w)
z [1] = 3
line 13, in outer
state ( ’ Inner (2) ’ , ’x ’ ,x , ’y ’ ,y , ’z ’ , z )
inner()
state ( ’ Outer (1) ’ , ’x ’ ,x , ’y ’ ,y , ’z ’ , z )
line 8, in inner
inner ()
state(’Inner(1)’,’x’,x,’y’,...)
y = 4
UnboundLocalError:
z [2] = 4
local variable ’x’
state ( ’ Outer (2) ’ , ’x ’ ,x , ’y ’ ,y , ’z ’ , z )
referenced before assignment
u , v , w = 1 , 2 , [0 ,1 ,2]
x in inner is a local variabe of inner
state ( ’ Main (1) ’ , ’u ’ ,u , ’v ’ ,v , ’w ’ , w )
x in inner is not the same as x in outer
outer (u ,v , w )
y in inner is the same as y in outer
state ( ’ Main (2) ’ , ’u ’ ,u , ’v ’ ,v , ’w ’ , w )
z in inner is the same as z in outer
Anonymous Functions
Python supports a weak form of anonymous functions:
lambda param1 , param2 , ...: expression
class Rectangle :
""" A simple rectangle class """
type = ’ Rectangle ’
• Class attributes are owned by the class itself and shared by all instances
of the class
• Instance attributes are owned by the specific instances of a class
• Instances can be given additional attributes (and methods) at any time
• Assigning a value to a class attribute via an instance creates a new
instance variable
• For an instance obj, obj.__dict__ returns a dictionary of all instance
variable and their values of obj
print (" Dictionary : " , r2 . __dict__ ," Type :" , r2 . type )
Dictionary : { ’ width ’: 5 , ’ height ’: 2} Type : Rectangle
‘Private’ Attributes
Deleting Instances
Inheritance
• In a class definition it is possible to specify one or more superclasses
from which a class should inherit attributes and methods:
class identifier ( Super1 , Super2 ,...):
docstring
suite
class Rectangle :
""" A simple rectangle class """
type = ’ Rectangle ’
Magic Methods
• __init__ and __del__ are examples of magic methods:
Methods that are invoked when a certain language constructs is used or
a particular condition becomes true
• Other examples include:
__getitem__ allows instances to use the [] (indexer) operators to
__setitem__ get or set a value
__str__ called by str(), print(), format() to obtain a
string representation of an instance
__eq__ called by comparison operator ==
__lt__ called by comparison operator <
__add__ called by binary operator +
__bool__ called for truth value testing and by bool(), should
return True or False
__iter__ called by for-loop to iterate over the elements
__next__ of an iterable object
COMP519 Web Programming Lecture 21 Slide L21 – 21
Classes Magic Methods
• A class implementing
__getitem__(self,key)
__setitem__(self,key,value)
allows instances to use the [] operator to access values
class Building :
def __init__ ( self , floors ):
self . __floors = [ None ]* floors
def __setitem__ ( self , floor_number , data ):
self . __floors [ floor_number ] = data
def __getitem__ ( self , floor_number ):
return self . __floors [ floor_number ]
• Read
• Section 9: Classes
(https://docs.python.org/3/tutorial/classes.html#classes)
of Python Software Foundation: The Python Tutorial.
Python Software Foundation, 21 December 2017.
https://docs.python.org/3/tutorial/
[accessed 21 December 2017]
• Read
• Chapter: Object-Oriented Programming (https://www.python-course.
eu/python3_object_oriented_programming.php)
• and all remaining chapters
of Bernd Klein: Python 3 Tutorial.
bodenseo Python Training Couses, 21 December 2017.
https://www.python-course.eu/python3_course.php
[accessed 21 December 2017]
COMP519 Web Programming Lecture 21 Slide L21 – 24
COMP519 Web Programming
Lecture 22: Python (Part 6)
Handouts
Ullrich Hustadt
68 Further Reading
Regular Expressions
Your task is to write a program that replaces URLs like these with
equivalent ones without occurrences of ‘..’:
http://www.myorg.co.uk/info/vat.html
are preserved
Solution: Replacing (//[^/]+.*/)[^/]+/../ by \1
removes superfluous dot-segments
; Substitution of regular expressions is useful for text modification
COMP519 Web Programming Lecture 22 Slide L22 – 4
Regular Expressions and Regular Expression Search Motivation
• \A is an assertion or anchor
• h, t, p, s, :, \/, c, a, t, d, o, g are characters
• ? and + are quantifiers
• [^\/] is a character class
• . is a metacharacter and \w is a special escape
• (cat|dog) is alternation within a capture group
• \1 is a backreference to a capture group
The re module
re.match(regexp,string,flags)
attempts to find a match for regexp at the start of string
returns a match object when regexp is found and None otherwise
re.match(r’[mM][rs]’,"Mr Dobbs") # MatchObject
re.match(r’[mM][rs]’,"Hi Mr Dobbs") # None
re.search(regexp,string,flags)
attempts to find a match for regexp anywhere in string
returns a match object when regexp is found and None otherwise
re.search(r’[mM][rs]’,"Hi Mr Dobbs") # MatchObject
re.search(r’[mM][rs]’,"Miss Dobbs") # None
re.finditer(regexp, string, flags)
returns a sequence of match objects for all non-overlapping matches
for regexp in string
COMP519 Web Programming Lecture 22 Slide L22 – 6
Regular Expressions and Regular Expression Search The re module
The re module
• The re module of Python provides functions that use regular expressions
The re module
• The re module of Python provides functions that use regular expressions
# 0123456789
m = re . search (r ’ cbc ’ ," ababcbcdcde ")
if m :
print (" Match found :" , m . group (0) ,\
" starts at " , m . start (0) ," and ends before " , m . end (0))
Match found : cbc , starts at 4 and ends before 7
# 012345678910
m = re . search (r ’[ bc ][ b - e ][^ bcd ] ’ ," ababcbcdcde ")
if m :
print (" Match at indices " , m . start (0) ,\
" to " , m . end (0) -1 ,":" , m . group (0))
Match at indices 8 to 10 : cde
COMP519 Web Programming Lecture 22 Slide L22 – 13
Further Reading
Ullrich Hustadt
• The constructs for regular expressions that we have so far are not
sufficient to match, for example, natural numbers of arbitrary size
• Also, writing a regular expressions for, say, a nine digit number
would be tedious
This is made possible with the use of quantifiers
regexp* Match regexp 0 or more times
regexp+ Match regexp 1 or more times
regexp? Match regexp 1 or 0 times as many times
regexp{n,} Match regexp at least n times as possible
regexp{n,m} Match regexp at least n but
not more than m times
regexp{n} Match regexp exactly n times
Quantifiers are greedy by default and match the longest leftmost sequence
of characters possible
COMP519 Web Programming Lecture 23 Slide L23 – 2
Regular Expressions and Regular Expression Search Quantifiers
m = re.search(r’cat|dog|bird’,ts)
if m: print("Match 1:",m.group(0))
Match 1: cat
m = re.search(r’dog|cat|bird’,ts)
if m: print("Match 2:",m.group(0))
Match 2: cat ; leftmost match is returned
m = re.search(r’dog|dogs’,ts)
if m: print("Match 3:",m.group(0))
Match 3: dog
m = re.search(r’dogs|dog’,ts)
if m: print("Match 4:",m.group(0))
Match 4: dogs ; if two alternatives match,
the leftmost alernative is returned
COMP519 Web Programming Lecture 23 Slide L23 – 14
Regular Expressions and Regular Expression Search Anchors
• Flags, added as argument to the functions of the module re, modify the
behaviour of those functions
• Inline flags, added to regular expressions, modify the behaviour of those
regular expressions
re.A (?a) Make \w, \W, \b, \B, \d, \D, \s, \S
perform ASCII-only matching instead of
Unicode matching
re . search (r ’\ w + ’ ," u \ u0169 \ u016f ")[0] # " u \ u0169 \ u016f "
re . search (r ’\ w + ’ ," u \ u0169 \ u016f " , re . A )[0] # "u"
re . search (r ’(? a )\ w + ’ ," u \ u0169 \ u016f ")[0] # "u"
re.M (?m) Make ’^’ match at the beginning of each line and
make ’$’ match at the end of each line
re . search (r ’ fire \ d$ ’ ," fire1 \ nfire2 ")[0] # " fire2 "
re . search (r ’ fire \ d$ ’ ," fire1 \ nfire2 " , re . M )[0] # " fire1 "
re . search (r ’(? m ) fire \ d$ ’ ," fire1 \ nfire2 ")[0] # " fire1 "
• Flags, added as argument to the functions of the module re, modify the
behaviour of those functions
• Inline flags, added to regular expressions, modify the behaviour of those
regular expressions
• Flags and inline flags can be used at the same time
(though that might not be good style)
• Several flags and inline flags can be combined
• Flags are combined using bitwise OR (the | operator)
• Inline flags are combined by forming a sequence of flag characters
re . search (r ’ Help . me ’ ," help \ nMe " , re . I | re . S )[0] # " help \ nMe "
re . search (r ’(? is ) Help . me$ ’ ," help \ nMe ")[0] # " help \ nMe "
re . search (r ’(? i ) Help . me ’ ," help \ nMe " , re . S ) # " help \ nMe "
ts = re . sub (r , convertF , ts )
print ( ts )
The temperature is Monday was 40.6 degrees Celsius
The temperature on Tuesday was 35.2 degrees Celsius
• Read
• Chapter 26: The Python Language: Regular Expressions
of S. Schafer: Web Standards Programmer’s Reference.
Wiley Publishing, 2005.
Harold Cohen Library 518.532.S29 or
E-book http://library.liv.ac.uk/record=b2174141
• Read
• Section 6.2: re — Regular expression operations
https://docs.python.org/3/library/re.html#module-re
of Python Software Foundation: The Python Standard Library,
3 October 2017. https://docs.python.org/3/library
[accessed 23 November 2017]
Ullrich Hustadt
Client requests
In the following we focus on client requests that are generated
using HTML forms
< html lang =" en - GB " >
< head > < title > My HTML Form </ title > </ head >
< body >
< form action =
" http :// student . csc . liv . ac . uk / cgi - bin / cgiwrap / uh / process "
method =" post " >
< label > Enter your user name :
< input type =" text " name =" username " >
</ label > < br >
< label > Enter your full name :
< input type =" text " name =" fullname " >
</ label > < br >
< input type =" submit " value =" Click for response " >
</ form >
</ body >
</ html >
Client requests
In the following we focus on client requests that are generated
using HTML forms
< html lang =" en - GB " >
< head > < title > My HTML Form </ title > </ head >
< body >
< form action =" http :// student . csc . liv . ac . uk / cgi - bin / cgiwrap / uh / process "
method =" post " >
< label > Enter your user name : < input type =" text " name =" username " > </ label > < br >
< label > Enter your full name : < input type =" text " name =" fullname " > </ label > < br >
< input type =" submit " value =" Click for response " >
</ form >
</ body >
</ html >
GET / cgi - bin / cgiwrap / uh / process ? username = dave & fullname = David
,→+ Davidson HTTP /1.1
Host : student . csc . liv . ac . uk
STDIN # empty
COMP519 Web Programming Lecture 24 Slide L24 – 8
CGI CGI I/O
STDIN # empty
COMP519 Web Programming Lecture 24 Slide L24 – 9
CGI CGI I/O
Making it work
For CGI programs to work on our systems you must proceed as follows:
1 You must have a directory
$HOME/public_html/cgi-bin/
Your public_html and cgi-bin directory must be both readable and
executable by everyone
2 Your CGI script must be placed in
$HOME/public_html/cgi-bin/
and must be executable by everyone but not readable by anyone
3 The CGI script can then be accessed using the URL
http://student.csc.liv.ac.uk/cgi-bin/cgiwrap/<user>/<script>
or http://student.csc.liv.ac.uk/cgi-bin/cgiwrapd/<user>/<script>
where <user> is your user name
and <script> is the filename of the script
(cgiwrapd provides debugging output, but does not reveal all errors)
print ( ’ ’ ’\
Content - type : text / html
print ( ’ < div > Clients IP address : ’ + user_ip + ’ </ div > ’)
print ( ’ < div > Clients hostname : ’ + host + ’ </ div > ’)
variable[’name’].value
– If name is not the name of a form control, results in a KeyError
– If the input for the form control with name name is empty,
results in a KeyError
– If several values were entered for the form control,
returns a list of those values (in no particular order)
variable.getvalue(’name’)
– If name is not the name of a form control, returns None
– If the input for the form control with name name is empty,
returns None
– If several values were entered for the form control,
returns a list of those values (in no particular order)
• Values have already been decoded
• Does not depend on whether the request method is GET or POST
variable[’name’].getfirst(’key’,default=None)
– If name is not the name of a form control, returns the default value
– If the input for the form control with name name is empty,
return the default value
– If several values were entered for the form control,
returns the first of those values (in no particular order)
variable.getlist(’name’)
– If name is not the name of a form control, returns the empty list
– If the input for the form control with name name is empty,
returns the empty list
– If several values were entered for the form control,
returns a list of those values (in no particular order)
• Values have already been decoded
• Does not depend on whether the request method is GET or POST
COMP519 Web Programming Lecture 24 Slide L24 – 24
Python CGI Programs Accessing and Processing Form Data: The cgi Module
# The form
< form action ="/ cgi - bin / cgiwrap / ullrich / process "
method =" post " >
< label > Enter your user name :
< input type =" text " name =" username " > </ label > < br >
< label > Enter your full name :
< input type =" text " name =" fullname " > </ label > < br >
< input type =" submit " value =" Click for response " >
</ form >
# The form
< form action ="/ cgi - bin / cgiwrap / ullrich / process "
method =" post " >
< label > Enter your user name :
< input type =" text " name =" username " > </ label > < br >
< label > Enter your full name :
< input type =" text " name =" fullname " > </ label > < br >
< input type =" submit " value =" Click for response " >
</ form >
• The web server will report an ‘Internal Server Error’ if scripts contain
syntax errors
; execute scripts first on the command line to check for syntax errors
• If a script raises an exception, then it depends on the web server
configuration what information is passed on
• The cgitb module provides a special exception handler for Python
scripts
; produces informative traceback information as HTML markup
• To activate the cgitb module use
import cgitb
cgitb . enable ()
Ullrich Hustadt
78 PHP
Motivation
79 Overview
Features
Applications
81 Further Reading
PHP
PHP Processing
PHP: Applications
PHP: Websites
Hello World !
Output:
< html lang = " en - GB " >
< head > < title > Hello World </ title > </ head >
< body > < h1 > Our first PHP script </ h1 >
<p > <b > Hello World ! </b > </p >
</ body > </ html >
PHP Scripts
• PHP scripts are typically embedded into HTML documents and are
enclosed between <?php and ?> tags
• A PHP script consists of one or more statements and comments
; there is no need for a main function (or classes)
• Statements end in a semi-colon
• Whitespace before and in between statements is irrelevant
(This does not mean its irrelevant to someone reading your code)
• One-line comments start with // or # and run to the end of the line or ?>
• Multi-line comments are enclosed in /* and */
Types
PHP has eight datatypes
• Four primitive types: • Two compound types:
• bool – booleans • array – arrays
• int – integers • object – objects
• float – floating-point numbers • Two special types:
• string – strings • resource
• NULL
Variables
Assignments
• Just like Java, JavaScript and Python, PHP uses the equality sign = for
assignments
$student_id = 200846369;
Binary Assignments
PHP also supports the standard binary assignment operators:
Constants
Constants
$circumfence = PI * $diameter ;
$distance = speed_of_light * $time ;
$myPet = ANIMALS [1];
<? php print " Type of 23: " . gettype (23). " \ n " ;
print " Type of 23.0: " . gettype (23.0). " \ n " ;
print " Type of \"23\": " . gettype ( " 23 " ). " \ n " ;
Comparison Operators
Type juggling also plays a role in the way PHP comparison operators work:
expr1 == expr2 Equal TRUE iff expr1 is equal to expr2
after type juggling
expr1 != expr2 Not equal TRUE iff expr1 is not equal to expr2
after type juggling
expr1 <> expr2 Not equal TRUE iff expr1 is not equal to expr2
after type juggling
expr1 === expr2 Identical TRUE iff expr1 is equal to expr2,
and they are of the same type
expr1 !== expr2 Not identical TRUE iff expr1 is not equal to expr2,
or they are not of the same type
Note: For ==, !=, and <>, numerical strings are converted to numbers
and compared numerically
"123" == 123 ; TRUE "123" === 123 ; FALSE
"123" != 123 ; FALSE "123" !== 123 ; TRUE
"1.23e2" == 123 ; TRUE 1.23e2 === 123 ; FALSE
"1.23e2" == "12.3e1" ; TRUE "1.23e2" === "12.3e1" ; FALSE
"10hello5" == 10 ; TRUE "10hello5" === 10" ; FALSE
5 == TRUE ; TRUE 5 === TRUE ; FALSE
COMP519 Web Programming Lecture 25 Slide L25 – 20
Types and Variables Comparisons
Comparison Operators
Type juggling also plays a role in the way PHP comparison operators work:
expr1 < expr2 Less than TRUE iff expr1 is strictly less than expr2
after type juggling
expr1 > expr2 Greater than TRUE iff expr1 is strictly greater than expr2
after type juggling
expr1 <= expr2 Less than TRUE iff expr1 is less than or equal to expr2
or equal to after type juggling
expr1 >= expr2 Greater than TRUE iff expr1 is greater than or equal to expr2
or equal to after type juggling
Note: For >, >=, <, and <= numerical strings are converted to numbers
and compared numerically
’35.5’ > 35 ; TRUE ’35.5’ >= 35 ; TRUE
’ABD’ > ’ABC’ ; TRUE ’ABD’ >= ’ABC’ ; TRUE
’1.23e2’ > ’12.3e1’ ; FALSE ’1.23e2’ >= ’12.3e1’ ; TRUE
"F1" < "G0" ; TRUE "F1" <= "G0" ; TRUE
TRUE > FALSE ; TRUE TRUE >= FALSE ; TRUE
5 > TRUE ; FALSE 5 >= TRUE ; TRUE
Note: For <=> numerical strings are converted to numbers and com-
pared numerically
’35.5’ <=> 35 ; 1 ’10hello5’ <=> 10 ; 0
’ABD’ <=> ’ABC’ ; 1 "F1" <=> "G0" ; -1
’99’ <=> ’100’ ; -1 ’1.23e2’ <=> ’12.3e1’ ; 0
TRUE <=> FALSE ; 1 0.0 <=> FALSE ; 0
5 <=> TRUE ; 0 ’FALSE’ <=> TRUE ; 0
Ullrich Hustadt
In PHP 5
• 1/0 returns FALSE and produces an error message
• 0/0 returns FALSE and produces an error message
and execution of the script continues!
In PHP 7
• 1/0 returns INF and produces an error message
• 0/0 returns NAN and produces an error message
and execution of the script continues!
http://www.php.net/manual/en/class.errorexception.php
COMP519 Web Programming Lecture 26 Slide L26 – 6
Primitive Datatypes Booleans
Booleans
Strings
Strings
PHP distinguishes between
• single-quoted strings and
• double-quoted strings
Strings
< body > <p > I shall not repeat myself . <p >
<p > I shall not repeat myself . <p >
<p > I shall not repeat myself . <p >
</ body >
Arrays
Arrays
Arrays
Arrays
PHP will determine the maximum value M among the integer indices in
$array and use the key K = M + 1; if there are no integer indices in
$array, then K = 0 will be used
; auto-increment for array keys
$arr4 [] = 51; // 0 = > 51
$arr4 [] = 42; // 1 = > 42
$arr4 [] = 33; // 2 = > 33
Arrays: foreach-loop
Arrays: foreach-loop
Example 1:
foreach ( array ( " Peter " , " Paul " , " Mary " ) as $value )
print " $value \ n " ;
Peter
Paul
Mary
Example 2:
$arr5 [2] = " Mary " ;
$arr5 [0] = " Peter " ;
$arr5 [1] = " Paul " ;
foreach ( $arr5 as $key = > $value )
print " The array maps $key to $value \ n " ;
The array maps 2 to Mary
The array maps 0 to Peter
The array maps 1 to Paul
Arrays: foreach-loop
Example 3:
$arr6 = array ( " name " = > " Peter " , " year " = > 2009);
Arrays: foreach-loop
Arrays: foreach-loop
Example:
$arr6 = array ( " name " = > " Peter " , " year " = > 2009);
foreach ( $arr6 as $key = > & $value ) { // Note : reference !
print " The array maps $key to $value \ n " ;
$value .= " - modified " ;
}
unset ( $value ); // Remove the reference from $value
print " \ n " ;
Array Assignments
• In JavaScript and Python, arrays were objects and as a consequence
array assignments were done by reference
• In PHP, this is not the case
$mem1 = memory_get_usage ();
$array1 = range (1 , 1000);
$mem2 = memory_get_usage ();
echo " (1) " , sprintf ( " %6 d " , $mem2 - $mem1 ) , " more bytes \ n " ;
$array2 = $array1 ;
$mem3 = memory_get_usage ();
echo " (2) " , sprintf ( " %6 d " , $mem3 - $mem2 ) , " more bytes \ n " ;
$array2 [1] += 10000;
echo " \ $array1 [1] = " , $array1 [1] , " | " ;
echo " \ $array2 [1] = " , $array2 [1] , " \ n " ;
$mem4 = memory_get_usage ();
echo " (3) " , sprintf ( " %6 d " , $mem4 - $mem3 ) , " more bytes \ n " ;
(1) 36920 more bytes
(2) 0 more bytes
$array1 [1] = 2 | $array2 [1] = 10002
(3) 36920 more bytes
The PHP implementation uses copy-on-write for array assignments
COMP519 Web Programming Lecture 26 Slide L26 – 21
Arrays Foreach-loops
Array Assignments
• The PHP implementation uses copy-on-write for array assignments
• If we want to two array variables to point to the same array literal, then
we need to use a reference
Array Operators
PHP has no stack or queue data structures,
but has stack and queue operators for arrays:
• array_push($array, value1, value2,...)
appends one or more elements at the end of the end of an array variable;
returns the number of elements in the resulting array
• array_pop($array)
extracts the last element from an array and returns it
• array_shift($array)
shift extracts the first element of an array and returns it
• array_unshift($array, value1, value2,...)
inserts one or more elements at the start of an array variable;
returns the number of elements in the resulting array
Note: $array needs to be a variable
NULL
NULL
Warning: Using NULL with == may lead to counter-intuitive results
$d = array ();
echo var_dump ( $d ) , "\n";
echo ’ is_null ( $d ): ’ , ( is_null ( $d )) ? " TRUE \ n " : " FALSE \ n " ;
echo ’ $d === null : ’ , ( $d === null ) ? " TRUE \ n " : " FALSE \ n " ;
echo ’ $d == null : ’ , ( $d == null ) ? " TRUE \ n " : " FALSE \ n " ;
array (0) {
}
is_null ( $d ): FALSE
$d === null : FALSE
$d == null : TRUE
Resources
A resource is a reference to an external resource
• resource fopen(filename, mode)
Returns a file pointer resource for filename access using mode on
success, or FALSE on error
Mode Operation Create Truncate
’r’ read file
’r+’ read/write file
’w’ write file yes yes
’w+’ read/write file yes yes
’a’ append file yes
’a+’ read/append file yes
’x’ write file yes
’x+’ read/write file yes
See http://www.php.net/manual/en/resource.php for further details
Resources
• bool fclose(resource)
• Closes the resource
• Returns TRUE on success
Resources
Printing
In PHP, the default command for generating output is echo
• void echo(arg1)
void echo arg1, arg2, ...
• Outputs all arguments
• No parentheses are allowed if there is more than one argument
• More efficient than print (and therefore preferred)
Printing
Printing
Ullrich Hustadt
Control Structures
Conditional Statements
The general format of conditional statements is very similar but not
identical to that in Java and JavaScript:
if ( condition ) {
statements
} elseif ( condition ) {
statements
} else {
statements
}
Conditional Statements/Expressions
Switch Statement
A switch statement in PHP takes the following form
switch ( $month ) {
case 1: case 3: case 5: case 7:
case 8: case 10: case 12:
$days = 31;
break ;
case 4: case 6: case 9: case 11:
$days = 30;
break ;
case 2:
$days = 28;
break ;
default :
$days = 0;
break ;
}
do {
statements
} while ( condition );
• As usual, curly brackets can be omitted if the loop consists of only one
statement
Example:
// Compute the factorial of $number
$factorial = 1;
do {
$factorial *= $number - -;
} while ( $number > 0);
For-loops
• The break command can also be used in while-, do while-, and for-loops
and discontinues the execution of the loop
while ( $value = array_shift ( $data ) {
$written = fwrite ( $resource , $value );
if (! $written ) break ;
}
Functions
Functions are defined as follows in PHP:
function identifier ( $ param1 , & $ param2 , ...) {
statements
}
Functions
Functions are defined as follows in PHP:
function identifier ( $ param1 , & $ param2 , ...) {
statements
}
Calling a Function
A function is called by using the function name followed by a list of
arguments in parentheses
function identifier ( $ param1 , & $ param2 , ...) {
...
}
... identifier ( arg1 , arg2 ,...) ...
• The list of arguments can be shorter as well as longer as
the list of parameters
• If it is shorter, then default values must have been specified for the
parameters without corresponding arguments
Example:
function sum ( $num1 , $num2 ) {
return $num1 + $num2 ;
}
echo " sum : " , sum (5 ,4) , " \ n " ;
$sum = sum (3 ,2);
Variables
PHP distinguishes three categories of variables:
• Local variables are only accessible in the part of the code in which they
are introduced
• Static variables are local variables within a function that retain their
value between separate calls of the function
Nested Functions
• The inner function does not have access to local variables of the outer
function
• The inner function can be called from outside the outer function
• The inner function is created the first time the outer function is called
• Calling the outer function twice will attempt to create the inner
function twice
; leads to an error that can be avoided by
if (! function_exists ( ’ inner ’ )) {
function inner ( $param3 , & $param4 , ...) { ... }
}
3: Bye
4: hello
COMP519 Web Programming Lecture 27 Slide L27 – 18
Functions Scope of Variables
• Since PHP 5.6, we can use the ... token in an argument list to denote
that the function accepts a variable number of arguments
• The arguments will be passed into the given variable as an array
$y = 3
$funcs = [ function ( $x ) use ( $y ) { return 2*( $x + $y ); } ,
function ( $x ) use ( $y ) { return 3+( $x + $y ); }];
foreach ( $funcs as $func ) {
echo $func (5) , " \ n " ;
}
16
11
Type Declarations
• PHP 5 introduced type declarations for function parameters
• PHP 7 added type declarations for the return value of a function
• By default, type juggling is still applied
• To enforce strict type checking the declaration
declare ( strict_types =1);
must be added at the start of the PHP file
function mult5 ( int $x ): int { return 5* $x ;}
echo " 1: " , mult5 (1) , "\n";
echo " 2: " , mult5 ( " 1.6 " ) , "\n";
echo " 3: " , mult5 ([1 ,2]) , " \ n " ;
// without strict_types =1 // with strict_types =1
1: 5 1: 5
2: 5 // not 8 nor 10 PHP Fatal error :
Uncaught TypeError
PHP Fatal error : PHP Fatal error :
Uncaught TypeError Uncaught TypeError
• PHP code in a library file must be enclosed within a PHP start tag
<?php and an end PHP tag ?>
• The incorporated content inherits the scope of the line in which an
include command occurs
• If no absolute or relative path is specified, PHP will search for the file
• first, in the directories in the include path include_path
• second, in the script’s directory
• third, in the current working directory
Ullrich Hustadt
HTML Forms
When considering Python CGI programming we have used HTML forms
that generated a client request that was handled by a Python CGI
program:
< form action =
" http :// student . csc . liv . ac . uk / cgi - bin / cgiwrap / uh / demo "
method = " post " >
...
</ form >
Now we will use a PHP script instead:
< form action = " http :// student . csc . liv . ac . uk / ∼ uh / demo . php "
method = " post " >
...
</ form >
• The PHP script file must be stored in a directory accessible by the web
server, for example $HOME/public_html, and be readable by the web
server
• The PHP script file name must have the extension .php, e.g. demo.php
COMP519 Web Programming Lecture 28 Slide L28 – 3
Available Information and Input Overview
PHP Environment
• phpinfo() displays information about the PHP installation and
EGPCS data (Environment, GET, POST, Cookie, and Server data)
for the current client request
• phpinfo(part) displays selected information
< html lang = " en - GB " >< head > </ head > < body >
<? php
phpinfo (); // Show all information
phpinfo ( INFO_VARIABLES ); // Show only info on EGPCS data
?>
</ body > </ html >
http://cgi.csc.liv.ac.uk/~ullrich/COMP284/examples/phpinfo.php
INFO_GENERAL The configuration, php.ini location, build date,
web server
INFO_CONFIGURATION Local and master values for PHP directives
INFO_MODULES Loaded modules
INFO_VARIABLES All EGPCS data
COMP519 Web Programming Lecture 28 Slide L28 – 5
Available Information and Input PHP Environment
• string ini_get(option)
• returns the value of the configuration option on success
• void ini_restore(option)
• restores a given configuration option to its original value
Server Variables
The $_SERVER array stores information about the web server
and the client request
; Similar to os.environ for Python CGI programs
< html lang = " en - GB " >< head > </ head > < body >
<? php
echo ’ Server software : ’ , $_SERVER [ ’ SERVER_SOFTWARE ’] , ’ <br > ’;
echo ’ Remote address : ’ , $_SERVER [ ’ REMOTE_ADDR ’] , ’ <br > ’;
echo ’ Client browser : ’ , $_SERVER [ ’ HTTP_USER_AGENT ’] , ’ <br > ’;
echo ’ Request method : ’ , $_SERVER [ ’ REQUEST_METHOD ’ ];
? > </ body > </ html >
http://cgi.csc.liv.ac.uk/~ullrich/COMP284/examples/server.php
Server software : Apache /2.2.22 ( Fedora )
Remote address : 10.128.0.215
Client browser : Mozilla /5.0 ... Chrome /41.0.2272.53 ...
Request method :
See http://php.net/manual/en/reserved.variables.server.php
for a list of keys
COMP519 Web Programming Lecture 28 Slide L28 – 7
Available Information and Input Form Data
Form Data
• Form data is passed to a PHP script via the three arrays:
$_POST Data from POST client requests
$_GET Data from GET client requests
$_REQUEST Combined data from POST and GET client requests
(derived from $_POST and $_GET)
; Accessing $_REQUEST is the equivalent in PHP to
accessing the ‘dictionary’ of a cgi.FieldStorage instance in
Python
< form action = " process . php " method = " post " >
< label > Enter your user name :
< input type = " text " name = " username " > </ label > < br >
< label > Enter your full name :
< input type = " text " name = " fullname " > </ label > < br >
< input type = " submit " value = " Click for response " > </ form >
$_REQUEST[’username’] Value entered into field with name ‘username’
$_REQUEST[’fullname’] Value entered into field with name ‘fullname’
COMP519 Web Programming Lecture 28 Slide L28 – 8
Available Information and Input Form Data
• Create a web-based system that asks the user to enter the URL of a file
containing bibliographic information
• Bibliographic informatiom will have the following form:
@entry {
name ={ Jonas Lehner } ,
name ={ Andreas Schoknecht } ,
title ={ < strong > You only live twice </ strong >} ,
}
@entry {
name ={ Andreas Schoknecht } ,
name ={ Eva Eggeling } ,
title ={ No End in Sight ?} ,
}
• The system should extract the names, count them, and create a table of
names and their frequency, ordered from most frequent to least frequent
Sessions
Sessions
Cookies
Browser −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−→ Server
GET /index.html HTTP/1.1
Host: intranet.csc.liv.ac.uk
Wikipedia Contributors: HTTP Cookie. Wikipedia, The Free Encyclopedia, 5 March 2014 20:50.
http://en.wikipedia.org/wiki/HTTP_cookie [accessed 6 Mar 2014]
PHP Sessions
Start a Session
• bool session_start()
• creates a session
• creates a session identifier (session id) when a session is created
• sets up $_SESSION array that stores session variables and session data
• the function must be executed before any other header calls
or output is produced
• string session_id([id])
• get or set the session id for the current session
• the constant SID can also be used to retrieve the current name and
session id as a string suitable for adding to URLs
• string session_name([name])
• returns the name of the current session
• if a name is given, the current session name will be replaced with the given
one and the old name returned
COMP519 Web Programming Lecture 28 Slide L28 – 18
PHP Sessions Start a PHP Session
• bool session_regenerate_id([delete_old])
• replaces the current session id with a new one
• by default keeps the current session information stored in $_SESSION
• if the optional boolean agument is TRUE, then the current session
information is deleted
; regular use of this function alleviates the risk of a session
being ‘hijacked’
<? php
session_start ();
echo " Session id : " , session_id () , " <br > " ;
echo " Session name : " , session_name () , " <br > " ;
s e s sion _ r e g e n e r a t e _ i d ();
echo " Session id : " , session_id () , " <br > " ; // changed
echo " Session name : " , session_name () , " <br > " ; // unchanged
?>
• bool session_start()
• resumes the current session based on a session identifier
passed via a GET or POST request, or passed via a cookie
• restores session variables and session data into $_SESSION
• the function must be executed before any other header calls
or output is produced
• $_SESSION array
• an associative array containing session variables and session data
• you are responsible for choosing keys (session variables)
and maintaining the associated values (session data)
• bool isset($_SESSION[key])
returns TRUE iff $_SESSION[key] has already been assigned a value
• bool session_start()
• $_SESSION array
• bool isset($_SESSION[key])
<? php
// Counting the number of page requests in a session
// Each web page contains the following PHP code
session_start ();
if (! isset ( $_SESSION [ ’ requests ’ ]))
$_SESSION [ ’ requests ’] = 1;
else
$_SESSION [ ’ requests ’ ]++;
echo " # Requests in this session so far : " ,
$_SESSION [ ’ requests ’] , " < br / >\ n " ;
?>
• bool session_destroy()
• destroys all of the data associated with the current session
• it does not unset any of the global variables associated with the session,
or unset the session cookie
• void session_unset()
• frees all session variables currently registered
• bool session_destroy()
• destroys all of the data associated with the current session
• void session_unset()
• frees all session variables currently registered
• bool setcookie(name, value, expires, path)
• defines a cookie to be sent along with the rest of the HTTP headers
<? php
session_start ();
session_unset ();
if ( session_id () != " " || isset ( $_COOKIE [ session_name ()]))
// force the cookie to expire
setcookie ( session_name () , session_id () , time () -2592000 , ’/ ’ );
session_destroy ();
?>
function d e s t r o y _ s e s s i o n_ a n d _d a t a () {
session_unset ();
if ( session_id () != " " || isset ( $_COOKIE [ session_name ()]))
setcookie ( session_name () , session_id () , time () -2592000 , ’/ ’ );
session_destroy ();
}
function count_requests () {
if (! isset ( $_SESSION [ ’ requests ’ ]))
$_SESSION [ ’ requests ’] = 1;
else $_SESSION [ ’ requests ’ ]++;
return $_SESSION [ ’ requests ’ ];
}
?>
http://cgi.csc.liv.ac.uk/~ullrich/COMP284/examples/page1.php
COMP519 Web Programming Lecture 28 Slide L28 – 26
PHP Sessions Example
function count_requests () {
if (! isset ( $_COOKIE [ ’ requests ’ ])) {
setcookie ( ’ requests ’ , 1 , time ()+31536000 , ’/ ’ );
return 1;
} else {
// $_COOKIE [ ’ requests ’]++ would not survive , instead use
setcookie ( ’ requests ’ , $_COOKIE [ ’ requests ’ ]+1 ,
time ()+31536000 , ’/ ’ ); // valid for 1 year
return $_COOKIE [ ’ requests ’ ]+1;
} }
?>
http://cgi.csc.liv.ac.uk/~ullrich/COMP284/examples/cpage1.php
COMP519 Web Programming Lecture 28 Slide L28 – 27
Authentication Overview
$error = ’ ’;
if ( isset ( $_POST [ ’ submit ’ ])) {
if ( checkCredentials ( $_REQUEST [ ’ user ’] , $_REQUEST [ ’ passwd ’ ])) {
$_SESSION [ ’ user ’ ]= $_REQUEST [ ’ user ’ ];
header ( " location : content . php " ); // Redirecting to Content
} else {
$error = " Username or Password is invalid . Try Again " ;
}
}
if ( isset ( $_SESSION [ ’ user ’ ])){
header ( " location : content . php " );
}
?>
COMP519 Web Programming Lecture 28 Slide L28 – 30
Authentication Example
http://cgi.csc.liv.ac.uk/~ullrich/COMP284/examples/content.php
COMP519 Web Programming Lecture 28 Slide L28 – 31
Authentication Example
Read
• Chapter 31: Using PHP
of S. Schafer: Web Standards Programmer’s Reference.
Wiley Publishing, 2005.
Harold Cohen Library 518.532.S29 or
E-book http://library.liv.ac.uk/record=b2174141
Ullrich Hustadt
class Rectangle {
protected $height ;
protected $width ;
Visibility
• Properties and methods can be declared as
public accessible everywhere
private accessible only within the same class
protected accessible only within the class itself and
by inheriting and parent classes
• For properties, a visibility class Vis {
public $public = 1;
declaration is required private $private = 2;
• For methods, a visibility protected $protected = 3;
declaration is optional protected function proFc () {}
private function priFc () {}
; by default, methods }
are public $v = new Vis ();
• Accessing a private or echo $v - > public ; # prints 1
echo $v - > private ; # Fatal Error
protected property /
echo $v - > protected ; # Fatal Error
method outside its visibility echo $v - > priFc (); # Fatal Error
is a fatal error echo $v - > proFc (); # Fatal Error
COMP519 Web Programming Lecture 29 Slide L29 – 5
Classes Class Constants
Constants
Destructors
• A class can have a destructor method __destruct that will be called as
soon as there are no other references to a particular object
class Employee {
static $totalNumber = 0;
public $name ;
Inheritance
Inheritance
class Rectangle {
protected $height ;
protected $width ;
Interfaces
interface Shape {
public function area ();
}
class Rectangle implements Shape {
...
}
Introspection Functions
There are functions for inspecting objects and classes:
bool class_exists(string class)
returns TRUE iff a class class exists
class_exists(’Rectangle’) # returns TRUE
string get_class(object obj)
returns the name of the class to which an object belongs
get_class($sq1) # returns ’Square’
bool is_a(object obj, string class)
returns TRUE iff obj is an instance of class named class
is_a($sq1,’Rectangle’) # returns TRUE
bool method_exists(object obj,string method)
returns TRUE iff obj has a method named method
method_exists($sq1,’area’) # returns TRUE
Introspection Functions
There are functions for inspecting objects and classes:
bool property_exists(object obj,string property)
returns TRUE iff object has a property named property
property_exists($sq1,’size’) # returns FALSE
get_object_vars(object)
returns an array with the accessible non-static properties of object
mapped to their values
get_object_vars($e2)
# returns ["name" => "Ben"]
get_class_methods(class)
returns an array of method names defined for class
get_class_methods(’Square’)
# returns ["__construct", "area"]
Connections
Connections: Example
# Connection information for the Departmental MySQL Server
$host = " mysql " ;
$user = " ullrich " ;
$passwd = " ------- " ;
$db = " ullrich " ;
$charset = " utf8mb4 " ;
$dsn = " mysql : host = $host ; dbname = $db ; charset = $charset " ;
# Useful options
$opt = array (
PDO :: ATTR_ERRMODE = > PDO :: ERRMODE_EXCEPTION ,
PDO :: AT T R _ D E F A U L T _ F ET CH _ MO DE = > PDO :: FETCH_ASSOC ,
PDO :: A T T R _ E M U L A T E _ P REPAR ES = > false
);
try {
$pdo = new PDO ( $dsn , $user , $passwd , $opt );
} catch ( PDOException $e ) {
echo ’ Connection failed : ’ ,$e - > getMessage ();
}
COMP519 Web Programming Lecture 29 Slide L29 – 16
The PDO Class Queries and Processing of Results
Queries
• The get all rows as an array of arrays from a result set stored in a
PDOStatement object, we can use the fetchAll() method
$rows = $result - > fetchAll ()
COMP519 Web Programming Lecture 29 Slide L29 – 18
The PDO Class Queries and Processing of Results
Prepared Statements
$name = ’ Ben ’;
$stmt1 - > bindParam ( ’: name ’ , $name , PDO :: PARAM_STR );
$stmt1 - > bindParam ( ’: email ’ , $email );
$email = ’ bj1@liv . ac . uk ’;
$slot = 20;
$stmt2 - > bindParam (1 , $slot , PDO :: PARAM_INT );
Transactions
Transactions
To support transactions, PDO provides the methods
beginTransaction()
– turns off auto-commit mode; changes to the database are not
committed until commit() is called
– returns TRUE on success or FALSE on failure
– throws an exception if another transaction is already active
commit()
– changes to the database are made permanent;
auto-commit mode is turned on
– returns TRUE on success or FALSE on failure
– throws an exception if no transaction is active
rollBack()
– discard changes to the database; auto-commit mode is restored
– returns TRUE on success or FALSE on failure
– throws an exception if no transaction is active
Transactions: Example
$pdo = new PDO ( ’ mysql : host =...; dbname =... ’ , ’ ... ’ , ’ ... ’ ,
array ( PDO :: ATTR_ERRMODE = > PDO :: ERRMODE_EXCEPTION ,
PDO :: A T T R _ E M U L A T E _ P R E P A R E S = > false ));
$pdo - > beginTransaction ();
try {
$userId = 1; $paymentAmount = 10.50;