0% found this document useful (0 votes)
23 views689 pages

Comp 519

Uploaded by

theaihub41
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views689 pages

Comp 519

Uploaded by

theaihub41
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 689

COMP519 Web Programming

Lecture 1: Overview of COMP519


Handouts

Ullrich Hustadt

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents

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

COMP519 Web Programming Lecture 1 Slide L1 – 1


Overview Information

COMP519 Web 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)

COMP519 Web Programming Lecture 1 Slide L1 – 2


Overview Information

Recommended Books

1 C. Bates: Web Programming: Building Internet Applications (3rd ed).


John Wiley & Sons, 2006.
2 A. Beautieu: Learning SQL (2nd ed).
O’Reilly, 2009.
3 M. E. Davis and J.A. Phillips, Learning PHP & MySQL (2nd ed).
O’Reilly, 2007.
4 S. Schafer, Web Standards programmer’s reference: HTML, CSS,
JavaScript, Perl, Python, and PHP.
Wiley, 2005.
5 R. L. Schwartz, T. Phoenix, and bd foy: Learning Perl (6th ed).
O’Reilly, 2011.
6 N. C. Zakas: Professional Javascript for Web Developers (2nd ed).
Wiley, 2009.
http://readinglists.liverpool.ac.uk/modules/comp519.html
COMP519 Web Programming Lecture 1 Slide L1 – 3
Overview Learning Outcomes

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.

COMP519 Web Programming Lecture 1 Slide L1 – 4


Overview Learning Outcomes

Learning Outcomes in a Nutshell


By the end of this module, a student should
• be able to design, develop and evaluate web applications

COMP519 Web Programming Lecture 1 Slide L1 – 5


Background Internet and WWW: A First Definition

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

World Wide Web [Old]


A collection of interlinked multimedia documents
(web pages stored on internet connected devices and accessed using a
common protocol (HTTP))

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)

• 1969: ARPANET (precursor of the Internet)


• 1971: First e-mail transmission
• 1971: File Transfer Protocol (FTP)
• 1972: Vadic VA3400 modem (1,200 bit/s over phone network)
• 1977: RSA public-key cryptography
• 1977-79: EPSS/SERCnet (first UK networks
between research institutions)
• 1981: IBM PC 5150
• 1981: Hayes Smartmodem (300 bit/s; computer controlled)
• 1982: TCP/IP standardised
• 1985: FTP on TCP standardised

COMP519 Web Programming Lecture 1 Slide L1 – 7


Background Internet and WWW: History

History (2)

• mid 1980s: Janet (UK network between research institutions


with 2 Mbit/s backbone and 64 kbit/s access links)
• 1986: U.S. Robotics HST modem (9600 bit/s)
• late 1980s: TCP/IP networks expand across the world
• 1991: Janet adds IP service
• 1991: Gopher / World Wide Web
• 1991: GSM (second generation cellular network)
digital, circuit switched network for
full duplex voice telephony
• 1995: First public releases of JavaScript and PHP
• 1997: World Wide Web slowly arrives on mobile phones

COMP519 Web Programming Lecture 1 Slide L1 – 8


Background Internet and WWW: History

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

COMP519 Web Programming Lecture 1 Slide L1 – 9


Background Internet and WWW: A Modern Definition

Web 6= Internet

World Wide Web [New]


An infrastructure that allows to easily develop, deploy, and use distributed
systems

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

COMP519 Web Programming Lecture 1 Slide L1 – 10


Background Internet and WWW: A Modern Definition

Web 6= Internet

World Wide Web [New]


An infrastructure that allows to easily develop, deploy, and use distributed
systems

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

Distributed Systems: Fundamental Questions


Software developers have to consider a wide, but rather stable,
range of questions including:
• Where can or should computations take place?
• Where can or should data be stored?
• How fast can data be transferred/communicated?
• What is the cost of data storage/computations/communication depending on
how/where we do it?
• How robustly/securely can data storage/computations/communication be done
depending on how/where we do it?
• How much energy is available to support data
storage/computations/communication depending on how/where we do it?
• What is the legality of data storage/computations/communications depending
on how/where we do it?
The possible answers to each of these questions is also rather stable,
but the ‘right’ answers change

COMP519 Web Programming Lecture 1 Slide L1 – 12


Background Distributed Systems: Model-View-Controller

Distributed Systems: Model-View-Controller


We use the Model-View-Controller software design pattern
to discuss some of these questions in more detail:
• The model manages the behaviour and
data
• The view renders the model into a form
suitable for interaction
• The controller receives user input and
translates it into instructions for the
model

1 Where should the view be rendered?


• On the user’s computer
• On a central server (farm) possibly shared by a multitude of users

COMP519 Web Programming Lecture 1 Slide L1 – 13


Background Distributed Systems: Model-View-Controller

Distributed Systems: Model-View-Controller


We use the Model-View-Controller software design pattern
to discuss some of these questions in more detail:
• The model manages the behaviour and
data
• The view renders the model into a form
suitable for interaction
• The controller receives user input and
translates it into instructions for the
model
2 Where should the behaviour of the model be computed?
• Close to the user,
on a single computer exclusively used by the user
• Away from the user,
on a central server (farm) shared by a multitude of users
• Distributed,
on several computers owned by a large group of users
COMP519 Web Programming Lecture 1 Slide L1 – 14
Background Distributed Systems: Model-View-Controller

Distributed Systems: Model-View-Controller


We use the Model-View-Controller software design pattern
to discuss some of these questions in more detail:
• The model manages the behaviour and
data
• The view renders the model into a form
suitable for interaction
• The controller receives user input and
translates it into instructions for the
model
3 Where should the data for the model be held?
• Close to the user,
on a single computer exclusively used by the user
• Away from the user,
on a central server (farm) shared by a multitude of users
• Distributed,
on several computers owned by a large group of users
COMP519 Web Programming Lecture 1 Slide L1 – 15
Background Distributed Systems: Model-View-Controller

Distributed Systems: Fundamental Questions

• Software developers have to consider a wide, but rather stable,


range of questions
• The possible answers to each of these questions is also rather stable
• The ‘right’ answer to each these questions will depend on
• the domain in which the question is posed
• available technology
• available resources

• The ‘right’ answer to each of the questions changes over time


• We may go back and forth between the various answers
• The reasons for that are not purely technological, but includes
• legal factors
• social factors
• economic factors
COMP519 Web Programming Lecture 1 Slide L1 – 16
Background Examples

NLS

• 1960ies: Computer terminals start to be used


to interact with computers
• 1968: NLS “oN-Line System” (Douglas Engelbart, SRI)

A ‘networked’ computer system with


GUI, off-line mode, ‘e-mail’,
collaborative word processing,
hypertext, video conferencing
and mouse is demonstrated

(The picture shows one of several terminals connected to


a mainframe computer)
Videos of the demo are available at
http://www.youtube.com/watch?v=JfIgzSoTMOs

COMP519 Web Programming Lecture 1 Slide L1 – 17


Background Examples

Thin clients, fat clients and cloud clients


• 1970ies: Computer terminals continue to dominate
• 1978: DEC VT100
Intel 8080 processor
3 kb main memory
Monochrome graphics
Like NLS, this is a terminal connected to a
mainframe computer via serial lines
Key points:
• The data is stored on the mainframe computer which also computes the
behaviour of the model
• The view is computed on the mainframe computer and only displayed
on the terminal
• The terminal receives user inputs and relays it to the mainframe
computer that translates it into instructions for the model
• This architecture dominated the industry for about 20 years
COMP519 Web Programming Lecture 1 Slide L1 – 18
Background Examples

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

The Post-PC Era

• 1992: IBM Simon Personal Communicator (First smartphone)


• 1996: Nokia 9000 Communicator
• 2007: Apple iPhone
Samsung 32-bit RISC ARM
128MB main memory
4-16GB flash memory
‘Apps’ / Web browser

• 2011: Google Chromebook


Intel Atom processor
2GB main memory
16GB SSD
Web-based applications
In effect the Chromebook is a ’terminal’ connected to
Google’s servers and others via a wireless network
COMP519 Web Programming Lecture 1 Slide L1 – 20
Background Examples

The Post-PC Era

• 2011: Google Chromebook


Intel Atom processor
2GB main memory
16GB SSD
Web-based applications

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?

COMP519 Web Programming Lecture 1 Slide L1 – 21


Background Examples

Thin clients, fat clients and cloud clients

• The Google Chromebook gives very similar answers to the fundamental


questions as the DEC VT100
; the possible answers to the fundamental questions stay the same
• The PC gave very different answers to the fundamental questions
; the ‘right’ answers change with time
• The Google Chromebook is more advanced than the DEC VT100 in
(almost) every aspect
; we are not going around in circles,
we always advance technologically
COMP519 Web Programming Lecture 1 Slide L1 – 22
Background Web Programming versus App Programming

Web Programming versus App Programming


• Web Programming relies on web browsers as means to render
user interfaces that are coded in HTML/CSS
• Web Programming relies on HTTP as the main protocol to exchange
information within a distributed system
• Web-based apps use a mix of server-side and client-side computing
• Web-based apps can be changed almost instantaneously and on a
per-user basis
• App Programming relies on directly coded ‘native’ interfaces
(Swift/Java)
• App Programming can rely on arbitrary protocols to exchange
information within a distributed system
• Programmers have more flexibility and more control when developing
‘traditional’ apps

It is not obvious which approach is better and in which situation


COMP519 Web Programming Lecture 1 Slide L1 – 23
COMP519 Web Programming
Lecture 2: HTML (HTTP and HTML5 Basics)
Handouts

Ullrich Hustadt

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents

3 HTTP
Introduction
History
Requests
Character Encodings
4 HTML
Introduction
History
Elements, Attributes and Values
5 Further Reading

COMP519 Web Programming Lecture 2 Slide L2 – 1


HTTP Introduction

HTTP

• Web clients (web browsers) and web servers use


HTTP (Hypertext Transfer Protocol) to communicate with each other
• More generally, HTTP is an application-layer protocol for distributed
systems

COMP519 Web Programming Lecture 2 Slide L2 – 2


HTTP History

HTTP: History

• 1991 – HTTP 0.9


first documented version of the protocol
• 1996 – HTTP/1.0
first version of HTTP that was an Internet Engineering Task Force
(IETF) informational RFC (RFC 1945)
HTTP 0.9 and HTTP/1.0 require a separate TCP/IP connection for
every resource request
• 1997 – HTTP/1.1
first version of HTTP that was an Internet Engineering Task Force
(IETF) formal standard (RFC 2068)
HTTP/1.1 can reuse a TCP/IP connection to request several resources
from the same server
• 1997-2014
• 2015

COMP519 Web Programming Lecture 2 Slide L2 – 3


HTTP History

HTTP: History

• 1991 – HTTP 0.9


• 1996 – HTTP/1.0
• 1997 – HTTP/1.1
• 1997-2014
Minor improvements and clarifications of HTTP/1.1 are developed
• 2015 – HTTP/2
• Major revision of HTTP with focus on efficiency and privacy improvements
• HTTP/2 allows a server to push resources to client even before they are
requested
• HTTP/2 puts more emphasis on encrypted connections

COMP519 Web Programming Lecture 2 Slide L2 – 4


HTTP Requests

HTTP Requests
Browser/Client −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−→ Server
GET /index.html HTTP/1.1
Host: www.example.com

Browser/Client ←−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− Server


HTTP/1.1 200 OK Header
Date: Mon, 24 Sep 2018 22:38:34 GMT
Content-Type: text/html; charset=UTF-8
Content-Encoding: UTF-8
Content-Length: 138
Last-Modified: Wed, 10 Jan 2018 23:11:55 GMT
Server: Apache/2.4.34 (Unix) (Red-Hat/Linux)
ETag: "3f80f-1b6-3e1cb03b"
Accept-Ranges: bytes
Connection: close

<html> Message body


<head>
<title>An Example Page</title>
</head>
<body>
Hello World, this is a very simple HTML document.
</body>
</html>

Wikipedia Contributors: Wikipedia, The Free Encyclopedia, 16 September 2018 23:26


https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol. [accessed 13 Sep 2017]

COMP519 Web Programming Lecture 2 Slide L2 – 5


HTTP Character Encodings

Character Encodings

• Computers operate on bits (0/1) and sequences of bits


• To store a text, it needs to be encoded as a sequence of bits
To retrieve a text, a sequence of bits needs to be decoded back to a
sequence of characters
• Early examples of such encodings are
• 7-bit ASCII (American Standard Code for Information Interchange)
• 8-bit ANSI (American National Standards Institute)
• 8-bit Windows-1252
• 8-bit Mac OS Roman
• However these allow to encode at most 256 characters
; the languages of the world contain many more characters

COMP519 Web Programming Lecture 2 Slide L2 – 6


HTTP Character Encodings

Character Encodings

• UTF-8 is a modern solution to this problem:


(Almost?) every known character is mapped to a sequence of 1x8 bits
to 4x8 bits
• Within UTF-8, ANSI characters retain their encoding

Char ASCII ANSI UTF-8 Mac OS Roman


a 1100001 01100001 01100001 01100001
â 11100010 11100010 10001001
ä 11100100 11100100 10001010
α 11001001:10100011

• 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

Hypertext and HTML

• The Hypertext Markup Language is the language for specifying the


static part of a web page / elements of an interface
• The terms ‘hypertext’ and ‘hypermedia’ were coined by Ted Nelson in
1963 as part of a model he developed for creating and using linked
content
• The idea of hypertext is attributed to Vannevar Bush who in in 1945
described a hypothetical hypertext device called Memex in a magazine
article
• Hypertext documents contain links to other hypertext documents,
creating an associative trail that readers can choose to follow
• Markup is a general term for special symbols (tags) that are added to
plain text to provide additional information about document structure,
content type, formatting, etc

COMP519 Web Programming Lecture 2 Slide L2 – 8


HTML History

HTML: Chronology

• 1989, Berners-Lee HTML 1


Very basic, limited integration of multimedia added in 1993,
web browser Mosaic supported many additional features
• 1994, IETF HTML 2.0
Tried to standardize these additional features, but during 1994–96,
web browsers Netscape and IE supported many new, divergent features
• 1995, IETF HTML 3.0
Proposed, but never received approval
• 1996, W3C HTML 3.2
Again attempted to unify all features into a single standard
but also dropped some tags that were in HTML 2.0

COMP519 Web Programming Lecture 2 Slide L2 – 9


HTML History

HTML: Chronology

• 1997, W3C HTML 4.0


Tried to discourage the use of ‘frames’, dropped Netscape visual tags,
and introduced CSS; defined three variants:
• Strict: Deprecated elements are forbidden
• Transitional: Deprecated elements are allowed
• Frameset: Frames are allowed
• 1999, W3C HTML 4.01
Minor changes, the three variations are maintained
• 2000, ISO ‘ISO HTML’
ISO/IEC 15445:2000, based on HTML 4.01 Strict

COMP519 Web Programming Lecture 2 Slide L2 – 10


HTML History

HTML: Chronology

• 2000, W3C XHTML 1.0


Reformulation of all three HTML 4.01 variations in XML
Unlike HTML, anyone can define their own tags and attributes
Unlike HTML, XHTML requires strict adherence to coding rules
• 2001, W3C XHTML 1.1
Based on XHTML 1.0 Strict, introduces modules

COMP519 Web Programming Lecture 2 Slide L2 – 11


HTML History

HTML: Chronology

• 2014, W3C HTML5


Shifts the focus from ‘semantically describing scientific documents’ to
‘supporting web applications’
• 2016, W3C HTML 5.1
Adds features for more responsive web apps and improved navigation
• 2017, W3C HTML 5.1 2nd Edition

COMP519 Web Programming Lecture 2 Slide L2 – 12


HTML Elements, Attributes and Values

Elements, Attributes and Values


• The HTML5 specification defines a set of elements, attributes, and
attribute values and their meanings (semantics)
(there are more than 100 different elements alone)
• Authors of HTML documents should not use elements, attributes, or
attribute values for purposes other than their intended semantic purpose
; otherwise documents might not be processed correctly
(still, most authors violate this rule)
• HTML5 follows the separation of concerns design principle:
a system should be divided into parts with functionality that overlaps
as little as possible
; in HTML5 semantics and presentation are (mostly) separated
• For the full specification of the most recent version see
S. Faulkner, A. Eicholz, T. Leithead, A. Danilo, editors:
HTML 5.1 2nd Edition. W3C Recommendation, 3 October 2017.
https://www.w3.org/TR/html51/ (accessed 05 October 2017)

COMP519 Web Programming Lecture 2 Slide L2 – 13


HTML Elements, Attributes and Values

Elements, Attributes and Values

• Most elements consist of a start tag and a matching end tag,


with some content in between
• The general form of a start tag
< tagName attrib1 =" value1 " ... attribN =" valueN " >
where tagName is a non-empty sequence of alphanumberic ASCII chars,
attrib1,. . . ,attribN, N ≥ 0, are attributes and
value1,. . . ,valueN, N ≥ 0, are attribute values
• A end tag / closing tag takes the form
</ tagName >

Examples:
< title > My first HTML document </ title >
<a href =" http :// cgi . csc . liv . ac . uk /" > CS Website </ a >

COMP519 Web Programming Lecture 2 Slide L2 – 14


HTML Elements, Attributes and Values

Elements, Attributes and Values

• So-called void elements only have a start tag


area base br col embed hr img
input keygen link meta param source track wbr
• The start tags of void elements can be made self-closing by ending the
tag with /> instead of >, optionally preceded by a space
Examples:
<br > < br / > < br / >
< img alt =" Picture of Crowne Plaza " src =" pic . png " >
< img alt =" Picture of Crowne Plaza " src =" pic . png "/ >
< img alt =" Picture of Crowne Plaza " src =" pic . png " / >

• Comments take the form


<! - - Comment -->
and cannot be nested
COMP519 Web Programming Lecture 2 Slide L2 – 15
HTML Elements, Attributes and Values

Elements, Attributes and Values

• HTML5 distinguished between different categories of attributes


• Required attributes: needed by elements of a particular type
to function correctly
• Optional attributes: used to modify the default functionality of an element
• Standard attributes: supported by a large number of element types
• Event attributes: used to link an element to code that is run
if a particular event happens in the element’s context
• Standard attributes include:
• id: meant to provide a document-wide unique identifier for an element
that can be used to refer to that specifc element
• class: assigns an element to a named group either for semantic or
for presentation purposes
• title: assigns a subtextual explanation to an element; in a web browser
typically shown if the mouse ‘hovers’ over the element
• style: allows to change the presentation of an element

COMP519 Web Programming Lecture 2 Slide L2 – 16


HTML Elements, Attributes and Values

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

&acirc; â &lt; <


&auml; ä &gt; >
&alpha; α &amp; &
• Arbitrary characters can also be accessed using &#dec; and &#xhex;
where dec and hex are decimal and hexadecimal encodings for a
character
Named char Rendered as Named char Rendered as
Examples

&#x000E2; â &#x0003C; <


&#x000E4; ä &#x0003E; >
&#x003B1; α &#x00026; &
COMP519 Web Programming Lecture 2 Slide L2 – 17
Further Reading

Revision and Further Reading


Read
• Chapter 1: The Basics of 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

COMP519 Web Programming Lecture 2 Slide L2 – 18


COMP519 Web Programming
Lecture 3: HTML (HTLM5 Elements: Part 1)
Handouts

Ullrich Hustadt

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents

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

COMP519 Web Programming Lecture 3 Slide L3 – 1


HTML HTML5 Documents

HTML5 Documents

• An HTML5 document has a very simple form:


It consists of a DOCTYPE-declaration and an html-element
<! DOCTYPE html >
html-element
• An html-element has the form
< html >
head-element
body-element
</ html >
• It is recommended that the start tag of an html-element specifies the
language used in the document
< html lang =" en-GB " >

COMP519 Web Programming Lecture 3 Slide L3 – 2


HTML The head-element

Head

• The head-element should include a title-element


(typically appears in the (tab) title bar of a browser)
• The head-element should also include meta data
such as the author of the page, a description of its content, keywords
• The head-element can also include Cascading Style Sheet (CSS)
definitions or links to external style sheets
• The head-element can also include JavaScript code or links to files
containing such code
< head >
< title > The Highway Code </ title >
< meta charset =" UTF -8" >
< meta name =" author " content =" John Doe " >
< meta name =" description " content =" Rules of the UK Highway Code " >
< meta name =" keywords " content =" british , highway , highways , car , pedestrian " >
< link rel =" stylesheet " href =" default . css " >
< script src =" code . js " > </ script >
</ head >

COMP519 Web Programming Lecture 3 Slide L3 – 3


HTML The body-element

Body

• The body-element contains the content that is to be displayed by a


web browser including
• Articles, sections, footers, and navs
• Headings
• Paragraphs
• Lists and tables
• Images
• The body-element may contain PHP code that is executed by the
web server, producing HTML markup, that is then merged with the
other content before being send to a web browser
• The body-element may contain JavaScript code that reacts to events in
the web browser and can dynamically change the content

COMP519 Web Programming Lecture 3 Slide L3 – 4


HTML Elements for the Body Structure

Structuring the Body

• An article-element contains text that makes header-


sense on its own element
• A section-element contains text on the same nav-
theme element
• A header-element contains introductory text section-
for a document, article, or section elements aside-
• A footer-element typically contains the article- element
elements
author of the document, copyright information,
footer-
links to terms of use, contact information, etc
element
• A nav-element contains a set of navigation
Several of these could be
hyperlinks
in one body-element
• An aside-element contains related but
The elements are seman-
independent content to the articles/sections tic, not layout related

COMP519 Web Programming Lecture 3 Slide L3 – 5


HTML Elements for the Body Structure

Structuring the Body

article-elements and section-elements header-


are typically nested inside each other: element
• In an HTML document corresponding to a nav-
scientific paper one expects several element
section-elements (for introduction, section-
conclusion, etc) inside one article-element elements aside-
• In an HTML document corresponding to a article- element
newspaper one expects several elements
article-elements (one for each report/story) footer-
inside one section-element element
The whole newspaper would consist of several
section-elements (sport, business, etc)

COMP519 Web Programming Lecture 3 Slide L3 – 6


HTML Elements for the Body Headings

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

COMP519 Web Programming Lecture 3 Slide L3 – 7


HTML Elements for the Body Headings

Structure and Headings


< body >
< article >
< header >
<h1 > Temporal Logic Reasoning </ h1 >
< address > Ullrich Hustadt , University of Liverpool , UK </ address >
</ header >
<nav >
<ul > < li > < a href ="# Intro " > Introduction </ li >
<li > < a href ="# Exp " > Experiments </ li > </ ul >
<nav >
< section id =" Intro " >
<h2 > Introduction </ h2 >
</ section >
< section id =" Exp " >
<h2 > Experiments </ h2 >
< section >
<h3 > Experimental Setup </ h3 >
</ section >
< section >
<h3 > Observations </ h3 >
</ section >
</ section >
< footer > & copy ;2018 Ullrich Hustadt </ footer >
</ article >
</ body >

COMP519 Web Programming Lecture 3 Slide L3 – 8


HTML Elements for the Body Lists

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 >

Typically uses numbers or letters to label each item in the list


• Unordered list: ul-element with li-elements as content
<ul >
<li > Item 1 </ li >
<li > Item 2 </ li >
</ ul >

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

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

COMP519 Web Programming Lecture 3 Slide L3 – 10


HTML Elements for the Body Paragraphs

Paragraphs

• A paragraph is a group of sentences that is centred on a single idea


• HTML5 provides the p-element for paragraphs
<p > This Web site provides clients , customers , interested parties and
our staff with all of the information that they could want on
our products , services , success and failures .
</p >

• Several spaces within a paragraph will always be rendered as just one


• Line breaks will not be preserved
• The void element br can be used to force a line break
• Alignment will be determined by the style that applies
(typically, by default, paragraphs are only left-aligned)
• The p-element should not be used when a more specific element is
more appropriate

COMP519 Web Programming Lecture 3 Slide L3 – 11


HTML Elements for the Body Div- and Span-element

Div and Span

• The div-element and the span-element are used as containers for a


group of consecutive elements
• A common semantics or a common style can then be applied to all
elements of that container
< div lang =" en - US " >
<p > Compromise in colors is gray . </p >
<p > Most bad behavior comes from insecurity . </p >
</ div >
< div lang =" en - GB " >
<p > Compromise in colours is grey . </p >
<p > Most bad behaviour comes from insecurity . </p >
</ div >
< div lang =" en - US " > DIV : A tempest in a teapot . </ div >
< div lang =" en - GB " > DIV : A storm in a teacup . </ div >
< span lang =" en - US " > SPAN : A tempest in a teapot . </ span >
< span lang =" en - GB " > SPAN : A storm in a teacup . </ span >

COMP519 Web Programming Lecture 3 Slide L3 – 12


HTML Elements for the Body Div- and Span-element

Div and Span


< div lang =" en - US " >
<p > Compromise in colors is gray . </p >
<p > Most bad behavior comes from insecurity . </p >
</ div >
< div lang =" en - GB " >
<p > Compromise in colours is grey . </p >
<p > Most bad behaviour comes from insecurity . </p >
</ div >
< div lang =" en - US " > A tempest in a teapot . </ div >
< div lang =" en - GB " > A storm in a teacup . </ div >
< span lang =" en - US " > A tempest in a teapot . </ span >
< span lang =" en - GB " > A storm in a teacup . </ span >

The difference between div and span is that by default:


• span-elements are phrasing content (HTML4: inline content)
; Two consecutive span-elements are placed side-by-side
; span-elements have neither width nor height
• div-elements are floating content (HTML4: block content)
; Each div-element starts on a new line and ends a line
; div-elements have width and height

COMP519 Web Programming Lecture 3 Slide L3 – 13


HTML Elements for the Body Div- and Span-element

Paragraphs, Divs and Lists

• List elements cannot be children of p-elements


Wrong:
<p > The body - element of an HTML document may include
<ul >
<li > headings and
<li > paragraphs
</ ul >
as well as many other things . </p >

Better (maybe only slightly):


<p > The body - element of an HTML document may include </ p >
<ul >
<li > headings , and
<li > paragraphs
</ ul >
<p > as well as many other things . </p >

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

• The address element represents contact information for a person


organization
• It is one of the few elements in which the use of a br element makes
sense though paragraph, span or div could also be used
< address >
Dr Ullrich Hustadt < br >
Department of Computer Science < br >
University of Liverpool < br >
Email : U . Hustadt@liv erpool . ac . uk
</ address >

COMP519 Web Programming Lecture 3 Slide L3 – 15


HTML Elements for the Body Hyperlinks

Hyperlinks

• Hyperlinks are created using


<a href =" url " > text <a >
where text is what the web browser will show to the user and url is
the URL of a web page / resource that the web browser would visit if
the user clicks on text
• The a-element has an optional attribute target
Possible values include
• _blank:
Opens the linked web page in a new window or tab
With HTML5 alone it is not possible to force whether a window or a tab is
opened
• _self:
Opens the linked web page in the same window or tab (default)
<a href =" http :// cgi . csc . liv . ac . uk /" target =" _blank " > CS Website </ a >

COMP519 Web Programming Lecture 3 Slide L3 – 16


HTML Elements for the Body Hyperlinks

Hyperlinks

• Instead of a whole document, a URL can also refer to a particular


element within a document, provided that element has an id
• In HTML5 any element can be given an id via the id attribute:
< tagName id =" ID " > ... </ tagName >
where ID is non-empty sequence of characters without spaces, unique
within the document
• It is then possible to internally link to that element using
<a href ="# ID " > text </ a >
• It is also possible to externally link to that element using
<a href =" url # ID " > text </ a >
assuming url is the URL of the document containing the element with
id ID
COMP519 Web Programming Lecture 3 Slide L3 – 17
HTML Elements for the Body 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

COMP519 Web Programming Lecture 3 Slide L3 – 18


Further Reading

Revision and Further Reading


Read
• Chapter 2: Document Tags
• Chapter 3: Paragraphs and Lines
• Chapter 4: Lists
• Chapter 6: Links
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

COMP519 Web Programming Lecture 3 Slide L3 – 19


COMP519 Web Programming
Lecture 4: HTML (HTLM5 Elements: Part 2)
Handouts

Ullrich Hustadt

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents

9 HTML Elements for the Body


Text-level Elements
Images
Figures
Tables

10 Further Reading

COMP519 Web Programming Lecture 4 Slide L4 – 1


HTML Elements for the Body Text-level Elements

Text-level Elements

• A strong-element represents strong importance, seriousness, or urgency


for its content
Can be used in a heading, caption, or paragraph to distinguish the most
important parts
< strong > Beware of the dog </ strong >

• A b-element highlights its content without marking it as important


Your <b > CV </ b > should contain the following sections ...

• An em-element represents stress emphasis on its content


<em > Cats </ em > are cute animals i.e. Cats , not dogs , are cute

COMP519 Web Programming Lecture 4 Slide L4 – 2


HTML Elements for the Body Text-level Elements

Text-level elements

• A code-element represents a fragment of computer code


The < code > begin </ code > keyword indicates the start of a block

• The pre-element represents a block of preformatted text (structure in


the block is represented by typographic conventions instead of elements)
<pre > < code class =" language - java " >
if ( i > 0) {
i := 1;
}
</ code > </ pre >
• The var-element represents a (mathematical) variable, constant, or
function
• The sup-element represents a superscript and the sub-element
represents a subscript
<var >x < sub > < var >i </ var > </ sub > </ var > =
<var >y < sup > < var >j </ var > </ sup > </ var >

COMP519 Web Programming Lecture 4 Slide L4 – 3


HTML Elements for the Body Images

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" >

<! - - Image " ashton_detail . jpg " scaled to 100 px ,


string " Ashton Building " will be shown if the pointer hovers over
the image ,
string " The Ashton Building at the University of Liverpool " will
be shown if image download has been disabled in the browser
-->

<a href =" index . html " > < img src =" home . png " alt =" Home " > </a >

<! - - A hyperlink containing an image . Clicking on the image will take


the user to " index . html "
-->

COMP519 Web Programming Lecture 4 Slide L4 – 5


HTML Elements for the Body Figures

Figures

• The figure-element represents an image, table, code that


• is self-contained
• is referenced from the main text of the document, and
• can be moved within the document without affecting the document’s
meaning
• The figcaption-element represents a caption or legend for the figure
in which it is included
< figure >
< img src =" warming . png " alt =" A diagram showing that world temperature
has increased significantly since 1900" >
< figcaption > Fig 1. World Temperature since 1900. </ figcaption >
</ figure >
Figure 1 shows that two - thirds of warming has occurred since 1975.
< figure >
<pre > < code > function sort { ... } </ code > </ pre >
< figcaption > Fig 2. Heap sort </ figcaption >
</ figure >
The heap sort algorithm shown in Figure 2 ...

COMP519 Web Programming Lecture 4 Slide L4 – 6


HTML Elements for the Body Tables

Tables

• Tables are a common way of displaying data


• The content of tables is divided into rows (horizontal) and columns
(vertical)
• Each column typically has a header,
one column, typically the left-most one, also has particular significance
• The whole table typically has a title given by a caption
• Lines are often used to make rows and columns more easily
distinguishable

COMP516 COMP517 COMP518 COMP519


2015-16 66.0 66.3 73.0 71.9
2016-17 66.5 75.9 70.9 75.9
2017-18 66.2 69.6 70.9 66.4
Average marks on 1st Semester CSMS Modules
COMP519 Web Programming Lecture 4 Slide L4 – 7
HTML Elements for the Body 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

COMP519 Web Programming Lecture 4 Slide L4 – 8


HTML Elements for the Body Tables

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 >

Note: There are no lines between columns and rows


Cell content is left-aligned
COMP519 Web Programming Lecture 4 Slide L4 – 9
HTML Elements for the Body Tables

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 >

Note: There are no lines between columns and rows


Cell content is left-aligned

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

Table and Cell Attributes

• table-elements have a border attribute


Value can be "" or "1"
(browsers typically draw a border around table cells for both)
• td- and th-elements have attributes rowspan and colspan that specify
how many rows and columns a cell spans
< table border ="1" >
< thead >
<tr > < th > Column 1 </ th > < th > Column 2 </ th > < th > Column 3 </ th > </ tr >
</ thead >
< tbody >
<tr > < td > one (1) </ td > < td > two (2) </ td > < td > three (3) </ td > </ tr >
<tr > < td rowspan ="2" > four (1) </ td >
< td colspan ="2" > five (2+3) </ td > </ tr >
<tr > < td > six (2) </ td > < td > seven (3) </ td > </ tr >
</ tbody >
</ table >

COMP519 Web Programming Lecture 4 Slide L4 – 11


HTML Elements for the Body Tables

Table and Cell Attributes


< table border ="1" >
< thead >
<tr > < th > Column 1 </ th > < th > Column 2 </ th > < th > Column 3 </ th > </ tr >
</ thead >
< tbody >
<tr > < td > one (1) </ td > < td > two (2) </ td > < td > three (3) </ td > </ tr >
<tr > < td rowspan ="2" > four (1) </ td >
< td colspan ="2" > five (2+3) </ td > </ tr >
<tr > < td > six (2) </ td > < td > seven (3) </ td > </ tr >
</ tbody >
</ table >

http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/tables.html

COMP519 Web Programming Lecture 4 Slide L4 – 12


Further Reading

Revision and Further Reading


Read
• Chapter 5: Images
• Chapter 7: Text
• Chapter 8: Tables
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

COMP519 Web Programming Lecture 4 Slide L4 – 13


COMP519 Web Programming
Lecture 5: Cascading Style Sheets: Part 1
Handouts

Ullrich Hustadt

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents

11 Style Sheets
Principle
History
Overview

12 Inline Styles
Overview
Properties and Values

13 Further Reading

COMP519 Web Programming Lecture 5 Slide L5 – 1


Style Sheets Principle

Style Sheets

• HTML5 follows the separation of concerns design principle:


a system should be divided into parts with functionality that overlaps
as little as possible
; in HTML5 semantics and presentation are (mostly) separated
• Concerns of presentation are dealt with using
Cascading Style Sheets (CSS)

COMP519 Web Programming Lecture 5 Slide L5 – 2


Style Sheets History

CSS: History

• 1996, W3C CSS Level 1 (CSS1)


Covers properties of fonts, texts, boxes; colours, pseudo classes
Very limited and buggy support in browsers
• 1998, W3C CSS Level 2 (CSS2)
Covers all of CSS1 plus selectors, media types, box model, tables,
bidirectional text, etc
Browser support still patchy
• 2011, W3C CSS Level 2 Revision 1 (CSS2.1)
Fixes errors, removes features from CSS2 with insufficient browser
supports, adds others
• 2011 onwards, W3C CSS Level 3
Follows a modular specification approach (lots of smaller specifications
instead of one very big one)
Covers all of CSS2.1 plus media queries, name spaces, flexible layout, etc

COMP519 Web Programming Lecture 5 Slide L5 – 3


Style Sheets Overview

Cascading Style Sheet

• 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

Cascading Style Sheet


Cascading Style Sheet cover three aspects of style and layout:
• Styling text
Deals with fonts, text colors, list item style, etc
• Styling boxes
Deals with properties of boxes:
• For the purpose of style and layout, all HTML elements are considered to be
boxes with the following properties:

• 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 >

For a complete list of properties and a description of each see


Mozilla and individual contributors: CSS reference. MDN Web Docs, 13 October 2017.
https://developer.mozilla.org/en-US/docs/Web/CSS/Reference
(accessed 14 October 2017)
COMP519 Web Programming Lecture 5 Slide L5 – 6
Inline Styles Properties and Values

CSS Values: Lengths

• One of the most important types of values in CSS are lengths


• CSS distinguished between absolute lengths, measured in absolute
(length) units, and relative lengths, measured in relative (length) units
• Relative length units specify a length relative to another length property
that is usually under user control
• the size of fonts (controlled by browser settings)
• the size of the viewport (controlled by resizing the browser window)
• Absolute length units are various multiples of a ‘physical measurement’,
for example, the size of a screen pixel

COMP519 Web Programming Lecture 5 Slide L5 – 7


Inline Styles Properties and Values

CSS Values: Lengths


Relative Length Units
em current font-size
ex x-height of the current font
ch width of ”0” (zero) in the current font
rem font-size of the root element (typically 16px)
vw 1% of the width of the viewport
vh 1% of the height of the viewport
vmin 1% of viewport’s smaller dimension
vmax 1% of viewport’s larger dimension
The viewport is the user’s visible area of a web page, typically determined
by the size of the browser window

COMP519 Web Programming Lecture 5 Slide L5 – 8


Inline Styles Properties and Values

CSS Values: Lengths


Absolute Length Units
cm ‘centimeter’ px pixel (1px = 1/96 in)
mm ‘millimeter’ pt point (1pt = 1/72 1in)
in ‘inch’ (1in = 96px = 25.4mm) pc pica (1pc = 12pt)
• A CSS pixel is the visual angle of one
pixel on a device with a pixel density of
96dpi and a distance from the reader of
28in (0.2646mm).
• A web client choosed the number of
physical pixels that best approximates a
CSS pixel
• The multipliers between two absolute
length units are always as indicated above

COMP519 Web Programming Lecture 5 Slide L5 – 9


Inline Styles Properties and Values

Mobile Devices and Lengths

• The interplay of CSS length units and mobile decives is problematic


• On mobile devices in portrait orientation, web clients typically
• render web pages in a viewport that is wider than the physical screen
• then shrink the result to the physical screen

; HTML elements appear to shrink when switching from


landscape to portrait orientation
; Media queries might not work as expected
The viewport meta tag allows to control this behaviour or web clients
< meta name =" viewport " content =" width = device - width , initial - scale =1" >

COMP519 Web Programming Lecture 5 Slide L5 – 10


Inline Styles Properties and Values

CSS Values: Font sizes


CSS allows to specify the size of a font in a number of different ways,
including
• Via a length
• Via a percentage:
Scales the font relative to the size of the current font
• Via one of the following keywords:
Keyword Typical scaling factor
xx-large 200%
x-large 150%
large 110%
mediam 100%
small 80%
x-small 60%
xx-small 55%

COMP519 Web Programming Lecture 5 Slide L5 – 11


Inline Styles Properties and Values

CSS Values: Colours


CSS allows to specify colours in a number of different ways, including:
• Via colour keywords:
CSS has about 140 names for a wide range of colours, for example:
red, green, blue, gold, peachpuff, snow, rebeccapurple
• Via hexadecimal notation: #RRGGBB
defines a colour as a mix of the colours red, green and blue
R (red), G (green), B (blue) are hexadecimal characters (0-9, A-F)
representing three numbers between 0 and 255, which in turn, specify
the intensity of that colour
Example: #FF000 defines the color red
• Via functional notation: rgb(R,G,B)
defines a colour as a mix of the colours red, green and blue
R (red), G (green), B (blue) are either decimal numbers between 0 and
255 or percentages 0% to 100% that again specify the intensity of that
colour
COMP519 Web Programming Lecture 5 Slide L5 – 12
Inline Styles Properties and Values

Inline Styles: Properties and Values


font-family: Courier, monospace
font-style: italic
font-size: 12pt | larger
font-weight: bold
color: AliceBlue | #F0F8FF
background-color: AliceBlue | #F0F8FF
text-decoration: underline | none
text-align: left | right | center | justify
text-indent: 10pt
vertical-align: top | middle | bottom
<p style =" font - family : Arial , sans - serif ; text - align : right " >
This is a right - justified paragraph in a sans serif font
with some < span style =" color : green " > green text </ span >
and <a style =" color : Red ; text - decoration : none ; font - size : larger ;"
href =" page01 . html " > here </ a > is a formatted link . </p >

COMP519 Web Programming Lecture 5 Slide L5 – 13


Inline Styles Properties and Values

Inline Styles: Properties and Values


list-style-type: disc | circle | square | none
list-style-type: decimal | lower-alpha | upper-roman
margin-left: 0.1in padding-top: 0.1in
margin-right: 3em padding-bottom: 3em
margin: 5% padding: 5%

< 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 >

COMP519 Web Programming Lecture 5 Slide L5 – 14


Inline Styles Properties and Values

Inline Styles: Properties and Values


list-style-type: disc | circle | square | none
list-style-type: decimal | lower-alpha | upper-roman
margin-left: 0.1in padding-top: 0.1in
margin-right: 3em padding-bottom: 3em
margin: 5% padding: 5%

< 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 >

COMP519 Web Programming Lecture 5 Slide L5 – 15


Inline Styles Properties and Values

Inline Styles: Properties and Values


border-width thin | thick | 5
border-color Blue | #0000FF
border-style dashed | dotted | double | none

< 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 >

COMP519 Web Programming Lecture 5 Slide L5 – 16


Further Reading

Revision and Further Reading


Read
• Chapter 12: CSS Basics
• Chapter 13: Style Definitions
• Chapter 14: Text
• Chapter 15: Padding, Margins, and Borders
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

COMP519 Web Programming Lecture 5 Slide L5 – 17


COMP519 Web Programming
Lecture 6: Cascading Style Sheets: Part 2
Handouts

Ullrich Hustadt

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents

14 Document Style Sheets


Overview
Selectors: Basic Forms
Inheritance
Specificity
Multiple Classes
Relative Selectors

15 Further Reading

COMP519 Web Programming Lecture 6 Slide L6 – 1


Document Style Sheets Overview

Document Style Sheets

• Inline styles apply to individual elements in an HTML document


• Using inline styles can lead to inconsistencies, as similar elements might
end up formatted differently as this approach is error-prone
• Also, inline styles mix content and presentation, which violates the
(current) general philosophy of HTML and CSS
• As a general rule, inline styles should be used as sparingly as possible
• Alternatively, document style sheets allow for a cleaner separation of
content and presentation
• Style definitions are placed in a style-element within the head-element of
an HTML document
• The style-element contains a list of style directives
• Each style directive consists of a selector together with one ore more
property:value pairs separated by semi-colons and enclosed inside braces
• Selectors allow us to apply style definitions to all elements, a subclass of
elements, or individual elements throughout the document
COMP519 Web Programming Lecture 6 Slide L6 – 2
Document Style Sheets Overview

Document Style Sheets: Example


< html lang =" en - GB " >
< head >
< title > Document Style Sheets </ title >
< style type =" text / css " >
h1 { color : Red ;
The h1 selector means that the style
text - align : center ; will be applied to all h1-elements
font - style : italic ; }
p . indented { text - indent : 2 em ; } The p.indented selector means
</ style > that the style will only be applied to
</ head >
< body >
p-elements of class indented
<h1 > Centred Red Heading </ h1 >
<p class =" indented " > This paragraph
will have the first line indented ,
but subsequent lines will be
left - aligned .
</p >
<p > This paragraph will not be
indented , all lines are
left - aligned as per default .
</p >
</ body >
</ html >
COMP519 Web Programming Lecture 6 Slide L6 – 3
Document Style Sheets Selectors: Basic Forms

Selectors: Basic Forms

• Selectors allow us to apply style definitions to all elements, a subclass of


elements, or individual elements throughout the document
• The basic forms of selectors are:
Selector Example
Selects
* * All elements
element h1 All h1-elements
element, element h1, h2 All h1- and h2-elements
.class .indented All elements with
class="indented"
element.class p.indented All p-elements with
class="indented"
#id #name The element with id="name"

COMP519 Web Programming Lecture 6 Slide L6 – 4


Document Style Sheets Selectors: Basic Forms

Basic Selectors: Example


< style type =" text / css " >
/* Make headings at levels h1 to h3 blue , centred
with an italic font */
h1 , h2 , h3 { color : Blue ;
text - align : center ;
font - style : italic ; }

/* Remove underline from hyperlinks and make them red */


a { text - decoration : none ;
color : Red ; }

/* Any element of class " alert " should be unerlined ,


have a bold font , orange background , and 3 px of extra
bottom padding to make the underlining more visible */
. alert { text - decoration : underline ;
padding - bottom : 3 px ;
background - color : orange ;
font - weight : bold ; }

/* Use a font of 150% normal size for the element


with id " c1 " */
# c1 { font - size : 150%; }
</ style >
COMP519 Web Programming Lecture 6 Slide L6 – 5
Document Style Sheets Selectors: Basic Forms

Selectors, Classes and Inheritance


The style directive
. alert { text - decoration : underline ; padding - bottom : 10 px ;
background - color : orange ; font - weight : bold ; }
creates a style for the class “alert” that can (in principle) be applied to
any HTML element by associating it with that class.
• Applied to a p-element
<p class =" alert " > Help Me ! I ’ m trapped on a COMP519 slide ! </p >

we obtain the following:

COMP519 Web Programming Lecture 6 Slide L6 – 6


Document Style Sheets Selectors: Basic Forms

Selectors, Classes and Inheritance


The style directive
. alert { text - decoration : underline ; padding - bottom : 10 px ;
background - color : orange ; font - weight : bold ; }
creates a style for the class “alert” that can (in principle) be applied to
any HTML element by associating it with that class.
• Applied to an li-element
<ol >
< li class =" alert " > Help Me ! </ li >
<li >I ’ m trapped on a COMP519 slide ! </ li >
</ ol >
we obtain the following:

• 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

Selectors, Classes, and Inheritance


The style directive
. alert { text - decoration : underline ; padding - bottom : 10 px ;
background - color : orange ; font - weight : bold ; }
creates a style for the class “alert” that can (in principle) be applied to
any HTML element by associating it with that class.
• Applied to an ol-element
< ol class =" alert " >
<li > Help Me ! </ li >
<li >I ’ m trapped on a COMP519 slide ! </ li >
</ ol >

we obtain the following: in contrast to:

• 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

COMP519 Web Programming Lecture 6 Slide L6 – 9


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 a non-inherited property has been specified for an
element, the property is given the initial, default value for that property

COMP519 Web Programming Lecture 6 Slide L6 – 10


Document Style Sheets 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

COMP519 Web Programming Lecture 6 Slide L6 – 11


Document Style Sheets Inheritance

Inheritance
Consider the style directive
table { background - color : yellow ;
border : 1 px solid black ; padding : 10 px ; margin : 10 px ; }

together with that will be rendered as


< table >
<tr > < td > Cell </ td > < td > Cell </ td > </ tr >
<tr > < td > Cell </ td > < td > Cell </ td > </ tr >
</ table >

• background-color will be inherited by the table cells (td-elements)


from the table element
• border and padding are not inherited by the table cells (td-elements)
from the table element
; table cells do not have individual borders and padding
• border and padding only apply to the table as a whole

COMP519 Web Programming Lecture 6 Slide L6 – 12


Document Style Sheets Inheritance

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 ; }

together with that will now be rendered as


< table >
<tr > < td > Cell </ td > < td > Cell </ td > </ tr >
<tr > < td > Cell </ td > < td > Cell </ td > </ tr >
</ table >

• 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

COMP519 Web Programming Lecture 6 Slide L6 – 14


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
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 >

that will be rendered as

• 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:

COMP519 Web Programming Lecture 6 Slide L6 – 16


Document Style Sheets Multiple Classes

Multiple Classes

• It is possible to declare that an HTML element belongs to more than


one class:
< tagName class =" class1 class2 ..." >

Example: Consider the style directives


p . alert { text - decoration : underline ; padding - bottom : 10 px ;
background - color : orange ; font - weight : bold ; }
p . blue { color : blue ; }
together with the HTML markup
<p class =" alert blue " > What colours do I have ?" </ p >
that will be rendered as

The properties of the paragraph come both from p.alert and


from p.blue

COMP519 Web Programming Lecture 6 Slide L6 – 17


Document Style Sheets 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

Multiple Classes: Resolving ‘conflicts’


• ‘Conflicts’ between multiple classes can be resolved in advance by
defining a directive that specifically applies to their combination
Consider the style directives
. red1 . blue { color : white ; background - color : orange ; }
. 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

• .red1.blue has higher specificity than both .red1 and .blue


• margin is still determined by .blue
COMP519 Web Programming Lecture 6 Slide L6 – 19
Document Style Sheets Relative Selectors

Relative Selectors

• It is possible to specify selectors that take into account the context in


which a matching HTML element occurs:
Selector Example
Selects
element element ol a All a elements inside ol elements
element>element ol>li All li elements where the parent
is an ol element
element+element p+ol All ol elements placed immedi-
ately after a p element
element∼element p∼ol All ol elements preceded by a
p element

COMP519 Web Programming Lecture 6 Slide L6 – 20


Document Style Sheets Relative Selectors

Relative Selectors: Example


Consider the style directives
ol a { color : red ; text - decoration : none } /* Hyperlink in ol */
ol > li { font - style : italic ; } /* li children of ol */
p + ol { font - weight : bold ; } /* ol immediately after p */
p ∼ ol { background - color : yellow ; } /* ol after p */
together with the HTML markup
<p > A paragraph with a <a href ="/ ∼ ullrich /" > hyperlink </ a > </p >
<ol > < li > A list item in an ordered list with
a <a href ="/ ∼ ullrich /" > hyperlink </ a > </ li > </ ol >
<ul > < li > A list item in an unsorted list with
a <a href ="/ ∼ ullrich /" > hyperlink </ a > </ li > </ ul >
<ol > < li > A list item in an ordered list with
a <a href ="/ ∼ ullrich /" > hyperlink </ a > </ li > </ ol >
that will be rendered as

COMP519 Web Programming Lecture 6 Slide L6 – 21


Document Style Sheets Relative Selectors

Why Do We Need All These Selectors?

• All ‘styling’ could be done by #id selectors, but should not be


(just assign a unique id to every element and define its style)
; just emulating inline style directives
; enourmous duplication of style directives
; error-prone (difficult to get uniform style)
• All ‘styling’ could be done by .class selectors, but should not be
(just assign a (unique) class to every element and define its style)
; in extremis just emulating inline style directives
; classes should be based on semantics not style
(e.g., shopping lists versus shopping baskets versus playlist)
; still error-prone
(you could miss an element or assign the wrong class)
If possible we should use existing properties of elements to determine
what style to apply, e.g., relative selectors and attribute selectors

COMP519 Web Programming Lecture 6 Slide L6 – 22


Further Reading

Revision and Further Reading


Read
• Chapter 16: Colors and Backgrounds
• Chapter 17: Tables
• Chapter 18: Element Positioning
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

COMP519 Web Programming Lecture 6 Slide L6 – 23


COMP519 Web Programming
Lecture 7: Cascading Style Sheets: Part 3
Handouts

Ullrich Hustadt

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents

16 Document Style Sheets


Attribute Selectors
Pseudo Classes
Pseudo Elements

17 External Style Sheets


Overview
Media Attribute and Adaptive Design

18 Further Reading

COMP519 Web Programming Lecture 7 Slide L7 – 1


Document Style Sheets Attribute Selectors

Attribute Selectors

• It is possible to specify selectors based on the presence or value of an


attribute in HTML elements:
Selector Example Selects
[attr] [title] All elements with
a title attribute
[attr=val] [target=_blank] All elements with
target="_blank"

COMP519 Web Programming Lecture 7 Slide L7 – 2


Document Style Sheets Attribute Selectors

Attribute Selectors

• It is possible to specify selectors based on the presence or value of an


attribute in HTML elements:
Selector Example Selects
[attr|=val] [lang|=en] All elements whose lang
attribute value begins with
the word "en" (delim " and -)
[attr^=val] [href^="https"] All elements whose href
attribute value begins with
the string "https"
Examples: p[class|=red] matches <p class="red">
and <p class="red-bold">
but not <p href="red.bold">
p[class^=red] matches <p class="red">
and <p class="red-bold">
and <p class="red.bold">
COMP519 Web Programming Lecture 7 Slide L7 – 3
Document Style Sheets Attribute Selectors

Attribute Selectors

• It is possible to specify selectors based on the presence or value of an


attribute in HTML elements:
Selector Example Selects
[attr$=val] [href$=".pdf"] All elements whose href
attribute value ends with
the string ".pdf"
[attr*=val] [href*="csc"] All elements whose href
attribute value contains
the substring "csc"
[attr∼=val] [class∼=alert] All elements whose class
attribute value contains
the word "alert"

COMP519 Web Programming Lecture 7 Slide L7 – 4


Document Style Sheets 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 >

COMP519 Web Programming Lecture 7 Slide L7 – 5


Document Style Sheets Pseudo Classes

Pseudo Classes

• A CSS pseudo class is a keyword added to a selector that


indicates a particular state of the selected element
• Depending on the type of element, its state could include
• the navigation history (e.g., whether a link has been visited)
• the status of its content (e.g., whether a checkbox has been checked)
• the position of the mouse pointer (e.g., over the element)
• Style directives involving a pseudo class take the form
selector : pseudo-class { property : value ; ... }

COMP519 Web Programming Lecture 7 Slide L7 – 6


Document Style Sheets Pseudo Classes

Pseudo Classes

• A CSS pseudo class is a keyword added to a selector that


indicates a particular state of the selected element
• Pseudo classes include
Pseudo Class / Example Selects
:hover
a:hover Links on mouse over
:visited
a:visited All visited links
:link
a:link All unvisited links

COMP519 Web Programming Lecture 7 Slide L7 – 7


Document Style Sheets Pseudo Classes

Pseudo Classes

• A CSS pseudo class is a keyword added to a selector that


indicates a particular state of the selected element
• Pseudo classes include
Pseudo Class / Example Selects
:nth-child(n) Every p element that is the
p:nth-child(1) first child of its parent
:nth-last-child(n) Every p element that is the
p:nth-last-child(2) second last child of its parent
:nth-of-type(n) Every p element that is the
p:nth-of-type(1) first p element of its parent
:nth-last-of-type(n) Every p-element that is the
p:nth-last-of-type(2) second last p element of its parent
• There are a number of additional pseudo classes that relate to the state
of form elements
COMP519 Web Programming Lecture 7 Slide L7 – 8
Document Style Sheets Pseudo Classes

Pseudo Classes: Example


<! DOCTYPE html >
< html lang =" en - GB " >
< head >
< title > Pseudo Classes </ title >
< style >
p . help { display : none ; background - color : yellow ;
padding : 20 px ; }
div : hover p . class {
display : block ; }
</ style >
</ head >
< body >
<div > Hover over me to get help
<p class =" help " > Here is some help </ p >
</ div >
</ body >
</ html >

turns into
COMP519 Web Programming when the mouse
Lecture 7 Slide L7 – 9
Document Style Sheets Pseudo Elements

Pseudo Elements

• A CSS pseudo element is a keyword added to a selector that


lets you style a specific part of the selected element(s)
• Style directives involving a pseudo element take the form
selector :: pseudo-element { property : value ; ... }
• Pseudo elements include
Pseudo Element Example Effect
::first-letter p::first-letter Selects the first letter of
every p element
::first-line p::first-line Selects the first line of
every p element
::selection ::selection Selects the portion of an
element that is selected by
the user

COMP519 Web Programming Lecture 7 Slide L7 – 10


Document Style Sheets Pseudo Elements

Pseudo Elements

• A CSS pseudo element is a keyword added to a selector that


lets you style a specific part of the selected element(s)
• Style directives involving a pseudo element take the form
selector :: pseudo-element { property : value ; ... }
• Pseudo elements include
Pseudo Element Example Effect
::marker ul::marker Select every marker of every
ul element (experimental)
::before h1::before Creates a pseudo element as first
child of every h1 element
::after h1::after Creates a pseudo element as last
child of every h1 element

COMP519 Web Programming Lecture 7 Slide L7 – 11


Document Style Sheets Pseudo Elements

Pseudo Elements: Example


<! DOCTYPE html >
< html lang =" en - GB " >
< head >
< title > Pseudo Elements </ title >
< style >
. custom - counter { list - style - type : none ;
padding - right : 0 px ;
margin - left : 0 px ; }
. custom - counter li { counter - increment : step - counter ;
padding - bottom : 10 px ; }
. custom - counter li :: before {
content : counter ( step - counter ); margin - right : 5 px ;
background - color : gold ; color : white ;
font - weight : bold ; padding : 3 px 8 px ;
border - radius : 17 px ;
}
</ style >
</ head >
< body >
< ol class =" custom - counter " >
<li > This is the first item </ li >
<li > This is the second item </ li >
<li > This is the third item </ li >
</ ol >
</ body >
</ html >
COMP519 Web Programming Lecture 7 Slide L7 – 12
External Style Sheets Overview

External Style Sheets

• External style sheets place style directives in a separate file or files


• Multiple HTML documents can link to the same style sheet
• Allows for a consistent look across multiple HTML documents on a website
• Makes it possible change a style in a single place which then propagates
automatically to all HTML documents that use that style sheet
• External style sheets represent the best separation of content and
presentation

COMP519 Web Programming Lecture 7 Slide L7 – 13


External Style Sheets Overview

External Style Sheets: Example


< html lang =" en - GB " >
< head >
< title > External Style Sheets </ title >
< link rel =" stylesheet " type =" text / css "
href =" myStyle . css " title =" myStyle " >
</ head >
< body >
<h1 > Centred Red Heading </ h1 >
<p class =" indented " > This paragraph will have the first line indented ,
but subsequent lines will be left - aligned .
</p >
<p > This paragraph will not be indented , all lines are left - aligned
as per default .
</p >
</ body >
</ html >

/* myStyle . css COMP519 2017 -10 -12 */

h1 { color : Red ; text - align : center ; font - style : italic ; }


p . indented { text - indent : 2 em ; }

COMP519 Web Programming Lecture 7 Slide L7 – 14


External Style Sheets Overview

External Style Sheets

• 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

COMP519 Web Programming Lecture 7 Slide L7 – 15


External Style Sheets Media Attribute and Adaptive Design

Multiple Style Sheets and Adaptive Design

• It is possible to use several external style sheets, and it is quite common


to use one that specifies styles for a web browser and another for
printing
• The media attribute of the link element allows to select
which external style sheets to use for which medium
Example:
< link rel =" stylesheet " type =" text / css " media =" screen "
href =" browser . css " >
< link rel =" stylesheet " type =" text / css " media =" print "
href =" print . css " >

• Different style sheets based on media features, e.g. screen resolution,


are often used in adaptive design
• Adaptive design uses different web pages or different layouts/styles
depending on media features

COMP519 Web Programming Lecture 7 Slide L7 – 16


External Style Sheets Media Attribute and Adaptive Design

The Media Attribute


• The value of the media-attribute is a string that specificies a boolean
combination of criteria based on media types and media features
• Boolean operators are:
and (conjunction), not (negation), , (disjunction)
• Media types are:
print, screen, speech, all
• Media features include:
Feature Value
orientation portrait or landscape
resolution | min-resolution | resolution in dpi
max-resolution
width | min-width | max-width width in px
height | min-height | max-height height in px
Example: screen and (min-width:1920px)
COMP519 Web Programming Lecture 7 Slide L7 – 17
External Style Sheets Media Attribute and Adaptive Design

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

Revision and Further Reading


Read
• Chapter 16: Colors and Backgrounds
• Chapter 17: Tables
• Chapter 18: Element Positioning
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

COMP519 Web Programming Lecture 7 Slide L7 – 19


COMP519 Web Programming
Lecture 8: Cascading Style Sheets: Part 4
Handouts

Ullrich Hustadt

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
19 Layout Via Divisions
Relevant Properties
20 CSS Grid Layout
Overview
Defining a Grid Layout
Placing Elements on a Grid
Example
21 CSS Flexbox Layout
Overview
Defining a Flexbox Layout
Example
22 Adaptive versus Responsive Design
23 Further Reading

COMP519 Web Programming Lecture 8 Slide L8 – 1


Layout Via Divisions

Layout Via Divisions: Overview

• 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)

COMP519 Web Programming Lecture 8 Slide L8 – 2


Layout Via Divisions Relevant Properties

Divisions and Properties (1)

• By default, a div element takes up the whole width of a browser


window and there is a line break before and after it
; Changes almost always need to be made to achieve
the desired layout
• CSS properties that we can use to make those changes include

Property Explanation / Example values


width Width of an element
1000px
90% 90% of the width of the containing element
height Height of an element
200px
10% 10% of the height of the containing element
margin All four margins of an element
auto centre horizontally within containing element

COMP519 Web Programming Lecture 8 Slide L8 – 3


Layout Via Divisions Relevant Properties

Divisions and Properties (1)

• By default, a div element takes up the whole width of a browser


window and there is a line break before and after it
; Changes almost always need to be made to achieve
the desired layout
• CSS properties that we can use to make those changes include

Property Explanation / Example values


float Whether and in which direction an element should float
left element floats to the left of its container
right element floats to the right of its container
clear Whether and how an element must be (cleared)
below floating elemnts
left element moves down to clear past left floats
right element moves down to clear past right floats
both element moves down to clear past all floats

COMP519 Web Programming Lecture 8 Slide L8 – 4


Layout Via Divisions Relevant Properties

Layout Via Divisions: Example (1)


A common layout of the top-level < body >
< div id =" header " >
div elements is the following header
</ div >
< div id =" nav " >
nav
</ div >
< div id =" main " >
< div id =" content " >
content
</ div >
< div id =" ads " >
ads
with the width of header, nav, </ div >
main, footer fixed to a value </ div >
< div id =" footer " >
between 900px and 1000px footer
</ div >
</ body >

COMP519 Web Programming Lecture 8 Slide L8 – 5


Layout Via Divisions Relevant Properties

Layout Via Divisions: Example (1)


A common layout of the top-level # header { width : 1000 px ;
height : 100 px ;
div elements is the following background - color : blue ;
margin : auto ; }
# nav { width : 1000 px ;
height : 50 px ;
background - color : green ;
margin : auto ; }
# main { width : 1000 px ;
margin : auto ; }
# content { width : 800 px ;
height : 400 px ;
background - color : yellow ;
with the width of header, nav, float : left ; }
main, footer fixed to a value # ads { width : 200 px ;
height : 400 px ;
between 900px and 1000px background - color : orange ;
float : right ; }
# footer { width : 1000 px ;
height : 50 px ;
clear : both ; margin : auto ;
background - color : blue ;}
http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/layout1.html
COMP519 Web Programming Lecture 8 Slide L8 – 6
Layout Via Divisions Relevant Properties

Layout Via HTML5 Elements

• In the example, we assigned unique a id to each div element and


associated a style directive with each of those ids
• Alternatively, we could have assigned a unique class to each div
element and associated a style directive with each of those classes
• In HTML5, we would use the appropriate elements < body >
< article >
like header, nav, etc instead of div elements < header >
• We would then associate a style directive with each </ header >
<nav >
of those elements </ nav >
header { width : 1000 px ; < section >
height : 100 px ; </ section >
background - color : blue ; < aside >
margin : auto ; } </ aside >
nav { width : 1000 px ; < footer >
height : 50 px ; </ footer >
background - color : green ; </ article >
margin : auto ; } </ body >

COMP519 Web Programming Lecture 8 Slide L8 – 7


Layout Via Divisions Relevant Properties

Fixed Positioning (1)

• So far, we have positioned elements relative to each other


• This means the arrangements of elements as a whole can move and can
move out of view if the user scrolls up or down in a browser window
• CSS properties that we can use to change that include

Property Explanation / Example values


position Specifies how an element is positioned in a document
fixed The element is removed from the
normal document flow;
no space is created for the element in the
page layout;
it is positioned relative to the screen’s
viewport using properties top, bottom left,
right and does not move when scrolled

COMP519 Web Programming Lecture 8 Slide L8 – 8


Layout Via Divisions Relevant Properties

Fixed Positioning (2)


• CSS properties required for position include

Property Explanation / Example values


top When position is set to absolute or fixed, specifies
the distance between the element’s top edge and the top
edge of its containing block
10px 10px off top edge
bottom Analogous to top for the element’s bottom edge and the
bottom edge of its containing block
20% 20% of the width of the containing block
left Analogous to top for the element’s left edge and the left
edge of its containing block
auto
right Analogous to right for the element’s left edge and the
left edge of its containing block
inherit inherit from parent element
COMP519 Web Programming Lecture 8 Slide L8 – 9
Layout Via Divisions Relevant Properties

Fixed Positioning: Example


We want to achieve the same lay- header { width : 1000 px ;
height : 100 px ;
out as before but with header, nav background - color : blue ;
and footer fixed in position position : fixed ;
top : 0 px ;
left : 50%;
margin - left : -500 px ; }
nav { width : 1000 px ;
height : 50 px ;
background - color : green ;
position : fixed ;
top : 100 px ;
left : 0 px ;
right : 0 px ;
Wo do so with slightly different margin : auto ; }
article { width : 1000 px ;
approaches used in the style direc- padding - top : 142 px ;
tives for each of these three ele- margin : 0 auto ; }
ments

http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/layout2.html
COMP519 Web Programming Lecture 8 Slide L8 – 10
Layout Via Divisions Relevant Properties

Fixed Positioning: Example


We want to achieve the same lay- section { width : 800 px ;
height : 1000 px ;
out as before but with header, nav background - color : yellow ;
and footer fixed in position float : left ;
}
aside { width : 200 px ;
height : 1000 px ;
background - color : orange ;
float : right ;
}
footer { width : 1000 px ;
height : 50 px ;
background - color : blue ;
position : fixed ;
Wo do so with slightly different bottom : 0 px ;
left : 50%;
approaches used in the style direc- transform : translate ( -50% ,0%);
tives for each of these three ele- }
ments

http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/layout2.html
COMP519 Web Programming Lecture 8 Slide L8 – 11
Layout Via Divisions Relevant Properties

Adaptive Design Revisited


• One fixed, rigid layout is unlikely to be suitable for every medium that a
user might use to access an HTML document
• We have seen that the media-attribute of the link element allows us to
select which external style sheets to use for which medium, e.g.
< link rel =" stylesheet " type =" text / css " media =" screen "
href =" browser . css " >
< link rel =" stylesheet " type =" text / css " media =" print "
href =" print . css " >

• 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

Importing CSS style files


• The @import CSS at-rule is used to import style directives
from other style sheets
@import url ;
@import url l ist - o f - m e d i a - q u e r i e s ;
Examples:
@import url (" http :// cgi . csc . liv . ac . uk / styles / common . css ");
@import " screen-specific . css " screen ;
@import ’ print-specific . css ’ print ;
• These rules must precede all other types of rules and directives
except @charset rules
• A @charset CSS at-rule specifies the character encoding
used in a style sheet, for example:
@charset " utf-8 ";

• The default character encoding is UTF-8


• Useful / used when attributes like content are given values involving
non-ASCII characters
COMP519 Web Programming Lecture 8 Slide L8 – 13
Layout Via Divisions Relevant Properties

Media Rules and Media Queries

• Within a style sheet, @media at-rules can used to conditionally apply


styles to a document depending on the result of media queries
@media lis t-of -m e d i a - q u e r i e s { group-rule-body }
where group-rule-body is either another @media at-rule,
@supports at-rule, or list of style directives
Examples:
@media print {
body { font-size : 10 pt ; }
}
@media screen and ( resolution > 150 dpi ) {
body { font-size : 13 px ; }
}

• The language for media queries is an extension of the one we have seen
for the media attribute

COMP519 Web Programming Lecture 8 Slide L8 – 14


Layout Via Divisions Relevant Properties

Feature Queries

• Within a style sheet, @support at-rules can be used to conditionall


apply styles to a document depending on the result of feature queries
@supports feature-query { group-rule-body }
• A feature query is basically a boolean combination (using and, or, not)
of property:value pairs
• For each property:value it will be evaluated whether the browser
used to process the style sheet supports this specific CSS feature
and then works out the truth value for the feature query overall
Examples:
@supports ( display : flex ) {
div { display : flex ; }
}
@supports not ( display : flex ) {
div { float : left ; }
}

COMP519 Web Programming Lecture 8 Slide L8 – 15


CSS Grid Layout Overview

CSS Grid Layout

• CSS Grid Layout is a two-dimensional grid-based layout system


• Such layout systems are motivated by the observation that most
web layouts can be seen as grids where elements are placed on one or
more grid cells
• Height and width of grid columns and grid rows will in general vary
Sample page layout Underlying grid and
allocation of elements to grid cells
col 1 col 2 col 3 col 4
row 1 header
row 2 nav
row 3 content ads

row 4 footer

COMP519 Web Programming Lecture 8 Slide L8 – 16


CSS Grid Layout Defining a Grid Layout

Defining a Grid Layout


CSS properties of Grid include
• display: grid
defines an element as grid container
• grid-template-columns: track-size |
[col-name] track-size ...
specifies the size and names of columns
• grid-template-rows: track-size |
[row-name] track-size ...
specifies the size and names of rows
• track-size can be auto, a length, a percentage, or a fraction of the
free space
These properties allow to specify a grid, including the size of each column
and each row

COMP519 Web Programming Lecture 8 Slide L8 – 17


CSS Grid Layout Placing Elements on a Grid

Placing Elements on a Grid


One way to place an element on the grid is to specify
– in which column/row it starts (top, left corner) and
– in which column/row it ends (bottom, right corner)
using the following properties
• grid-column-start: cell
• grid-column-end: cell
• grid-row-start: cell
• grid-row-end: cell
• cell can take the following values:
number column number / row number
name name of a column / row
span number number of tracks covered
span name span until name is reached
auto automatic

COMP519 Web Programming Lecture 8 Slide L8 – 18


CSS Grid Layout Placing Elements on a Grid

Placing Elements on a Grid


An alternative way to place elements on the grid is to assign grid names to
the elements and to use a grid template that references those names:
• grid-area: area-name
assign a grid area name to an element
• grid-template-areas: "area-name | . | none | ..."
"..."
associates grid area names with grid cells

This is only a glimpse of the possibilities of the CSS Grid Layout System

COMP519 Web Programming Lecture 8 Slide L8 – 19


CSS Grid Layout Example

CSS Grid Layout: Example


We want to replicate the same
< body >
layout as before:
< article >
< header > </ header >
<nav > </ nav >
< section > </ section >
< aside > </ aside >
< footer > </ footer >
</ article >
</ body >
article { display : grid ;
grid - template - rows : 100 px 50 px auto 50 px ;
grid - template - columns : auto 800 px 200 px auto ;
grid - template - areas : ". header header ."
". nav nav ."
". content ads ."
". footer footer .";
}
header { grid - area : header ; background - color : blue ; }
nav { grid - area : nav ; background - color : green ; }
section { grid - area : content ; background - color : yellow ; }
aside { grid - area : ads ; background - color : orange ; }
footer { grid - area : footer ; background - color : blue ; }
http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/layout3.html
COMP519 Web Programming Lecture 8 Slide L8 – 20
CSS Flexbox Layout Overview

CSS Flexbox Layout

• 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

• The main axis is not necessarily horizontal, its direction is determined


by flex-direction
COMP519 Web Programming Lecture 8 Slide L8 – 21
CSS Flexbox Layout Defining a Flexbox Layout

Defining a Flexbox Layout


CSS properties of Flexbox include
• display: flex
defines an element as a flexbox container
• flex-direction: row | row-reverse |
column | column-reverse
defines the direction of the main axis,
for example, with row the direction is left to right (horizontally)
• flex-wrap: nowrap | wrap | wrap-reverse
whether and how flex items wrap when the main axis is ‘full’,
for example, with wrap-reverse, flex items will wrap onto multiple
‘lines’ from bottom to top along the cross axis
• flex-flow: direction-option || wrap-option
combines flex-direction and flex-wrap

COMP519 Web Programming Lecture 8 Slide L8 – 22


CSS Flexbox Layout Defining a Flexbox Layout

Flexbox Layout Properties


CSS properties of Flexbox include
• justify-content: justify-option
defines the alignment along the main axis
justify-option can take the following values:

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

Flexbox Layout Properties


CSS properties of Flexbox include
• align-content: align-option
defines the use of extra space along the cross axis
align-option can take the following values:

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

CSS Flexbox Layout: Example


HTML
<nav >
<a href ="#" > Computer Science </ a >
<a href ="#" > Electrical Engineering and Electronics </ a >
<a href ="#" > Physics </ a >
</ nav >
CSS
a { text - align : center } /* Narrow screen width */
nav { @media all and ( max - width : 900 px ) {
background - color : LightGreen ; nav {
display : flex ; flex - direction : column ;
flex - direction : row ; }
justify - content : space - around ; }
}

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 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

COMP519 Web Programming Lecture 8 Slide L8 – 26


Adaptive versus Responsive Design

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

• There are no generally agreed definitions of adaptive design and


responsive design
• It is often debatable whether a website uses adaptive design or
responsive design (or neither)
• There is even more debate which one is better
• Most/all of the examples we have seen use adaptive design,
but this was done for effect
COMP519 Web Programming Lecture 8 Slide L8 – 27
Adaptive versus Responsive Design

Style Guide

• HTML and CSS provide a lot of features,


but these must be used sensibly
; just because a feature exists does not mean it be used
• Do not use features that distract from the content of your web page
• Use (non-default) colours and fonts carefully
; no purple text on pink background
; no “weird” fonts (that includes Comic Sans)
; mainly use a dark font on a light background
• Remember that an estimated 8-10% of people have some type of
colour-blindness
; avoid red/green colour combinations
• Remember that some people use screen readers to read the content of
web pages
; always include alt properties for images
COMP519 Web Programming Lecture 8 Slide L8 – 28
Adaptive versus Responsive Design

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

Revision and Further Reading


Read
1 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).
2 Chris House: A Complete Guide to Grid.
CSS-Tricks. 13 September 2017.
https:
//css-tricks.com/snippets/css/complete-guide-grid/
(accessed 18 October 2017).
3 Mozilla and individual contributors: CSS Grid Layout.
MDN Web Docs, 5 October 2017.
https://developer.mozilla.org/en-US/docs/Web/CSS/
CSS_Grid_Layout (accessed 19 October 2017).
COMP519 Web Programming Lecture 8 Slide L8 – 30
COMP519 Web Programming
Lecture 9: HTML (HTML5 Elements: Part 3)
Handouts

Ullrich Hustadt

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents

24 HTML Elements for the Body


Forms
Form Controls

25 Further Reading

COMP519 Web Programming Lecture 9 Slide L9 – 1


HTML Elements for the Body Forms

Forms

• A form is an element that contains form controls, such as


text fields, buttons, checkboxes, range controls, or color pickers
• Forms allow users to enter data which can then be sent to a web server
for processing
• A form element has several (optional) attributes, including
• action: URL to use for form submission
• method: HTTP method to use for form submission (get or post)
• enctype: encoding type to use for form submission
• novalidate: form is not validated during submission
< form action =" https :// sam . csc . liv . ac . uk / COMP / Calendar . pl "
method =" post " enctype =" text / plain " >
</ form >
• A form can be submitted and on submission the data entered via the
form controls will be send to the URL in action using the HTTP
request method in method with encoding type enctype
COMP519 Web Programming Lecture 9 Slide L9 – 2
HTML Elements for the Body Forms

Forms

• A form is an element that contains form controls, such as


text fields, buttons, checkboxes, range controls, or color pickers
• HTML5 introduced a number of additional form controls and attributes
for all form controls, but browser support is partial
; Always test your forms with a range of browsers
(Apple Safari, Google Chrome, Mozilla Firefox, MS IE, MS Edge)

COMP519 Web Programming Lecture 9 Slide L9 – 3


HTML Elements for the Body Forms

Label

• In order for a form to be usable, each form control needs be be


accompanied by an indication of what it is for or how it should be used
Example: ‘Surname’ or ‘Enter your surname’ next to a field into which
you are meant to enter your surname
• A label element represents such an indication (a caption)
• A label element can be associated with a specific form control either
using its for attribute or by putting the form control inside the label
element itself
< label for =" s1 " > Surname : </ label >
< input name =" surname " id =" s1 " type =" text " >

< label > First name ( s ): < input name =" first " id =" f1 " type =" text " > </ label >

COMP519 Web Programming Lecture 9 Slide L9 – 4


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
• 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

COMP519 Web Programming Lecture 9 Slide L9 – 5


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
• 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 " >

COMP519 Web Programming Lecture 9 Slide L9 – 7


HTML Elements for the Body Form Controls

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 >

• On submission, the web browser will construct pairs name=value where


name is the value of the name attribute of one of the form controls and
value is the input by the user for that form control
• A string composed of those pairs will be send to process.php
Example:
Peters, Amy Lee, and 201612345 are entered into the three fields
; surname=Peters, first=Amy+Lee, and studentid=201612345
are sent to process.php
COMP519 Web Programming Lecture 9 Slide L9 – 8
HTML Elements for the Body Form Controls

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 >

• This form can be submitted by either activating the ‘Submit’ button or


by pressing the return key within one of the three input fields
• Form submission is possible even with all input fields being empty,
even the one for the StudentID
; we need to add the required attribute to prevent empty inputs
• The StudentID field accepts floating point numbers between the
specified min and max values
; 1.9e8 is accepted and studentid=1.9e8 send to process.php
COMP519 Web Programming Lecture 9 Slide L9 – 9
HTML Elements for the Body Form Controls

Names versus IDs


<p > Please complete the following form if you are an undergrad : </p >
< form id =" formUG " action =" process - comments . php " >
< input type =" hidden " name =" level " value =" UG " >
< label for =" c1 " > Describe your problem : </ label >
< input type =" text " name =" comment " id =" c1 " maxlength ="250" required >
< br / > < input type =" submit " >
< form >
<p > Please complete the following form if you are a postgrad : </p >
< form id =" formPG " action =" process - comments . php " >
< input type =" hidden " name =" level " value =" PG " >
< label for =" c2 " > Describe your problem : </ label >
< input type =" text " name =" comment " id =" c2 " maxlength ="250" required >
< br / > < input type =" submit " >
</ form >
<p >
Help : < br / >
If you are an undergraduate student ,
complete <a href ="# c1 " > the first form </ a >. < br / >
If you are a postgraduate student ,
complete <a href ="# c2 " > the second form </ a >.
</p >

COMP519 Web Programming Lecture 9 Slide L9 – 10


HTML Elements for the Body Form Controls

Names versus IDs


<p > Please complete the following form if you are an undergrad : </p >
< form id =" formUG " action =" process - comments . php " >
< input type =" hidden " name =" level " value =" UG " >
< label for =" c1 " > Describe your problem : </ label >
< input type =" text " name =" comment " id =" c1 " maxlength ="250" required >
< br / > < input type =" submit " >
< form >
<p > Please complete the following form if you are a postgrad : </p >
< form id =" formPG " action =" process - comments . php " >
< input type =" hidden " name =" level " value =" PG " >
< label for =" c2 " > Describe your problem : </ label >
< input type =" text " name =" comment " id =" c2 " maxlength ="250" required >
< br / > < input type =" submit " >
</ form >
<p >
Help : < br / >
If you are an undergraduate student ,
complete <a href ="# c1 " > the first form </ a >. < br / >
If you are a postgraduate student ,
complete <a href ="# c2 " > the second form </ a >.
</p >

• 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 " >

COMP519 Web Programming Lecture 9 Slide L9 – 12


HTML Elements for the Body Form Controls

Input: Submit (Example 1)


< form action =" process . php " method =" post " >
< label > Name : < input name =" fn " required > </ label >
< label > Essay : < textarea name =" essay " required > </ textarea > </ label >
< input type = submit name =" action " value =" Submit essay " >
< input type = submit name =" action " value =" Save essay " formnovalidate >
</ form >

• On activating the ‘Submit essay’ button it will be checked that both


Name and Essay have been filled in; if so, the text entered will be send
to process.php together with action=Submit+essay
• On activating the ‘Save essay’ button no check will take place;
any text entered for Name and Essay will be send to process.php
together with action=Save+essay
• The script process.php can perform the appropriate operations
depending on the value of action
COMP519 Web Programming Lecture 9 Slide L9 – 13
HTML Elements for the Body Form Controls

Input: Submit (Example 2)


< form >
< label > Name : < input name =" fn " required > </ label >
< label > Essay : < textarea name =" essay " required > </ textarea > </ label >
< input type = submit formaction =" submit . php " value =" Submit essay " >
< input type = submit formaction =" save . php " value =" Save essay "
formnovalidate >
</ form >

• On activating the ‘Submit essay’ button it will be checked that both


Name and Essay have bene filled in; if so, the text entered will be send
to submit.php
• On activating the ‘Save essay’ button no check will take place;
any text entered for Name and Essay will be send to save.php
• The scripts submit.php and save.php have been written specifically
to perform the respective function
COMP519 Web Programming Lecture 9 Slide L9 – 14
HTML Elements for the Body Form Controls

Input: Number

• An input element with type=number 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
• min: minimum value allowed to be entered
• max: maximum value allowed to be entered
• step: granularity that is expected (and required) of the value
• placeholder: a short hint describing the expected value of a text area
(disappears as soon as the user enters a value)
<! - - The only allowed values below are 10 , 12 , 14 -->
< input type = number name =" quantity " min ="10" max ="14" step ="2" required >

<! - - 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" >

COMP519 Web Programming Lecture 9 Slide L9 – 16


HTML Elements for the Body Form Controls

Input: Password

• An input element with type=password represents a one line plain


text field for the element’s value
• Same as an input element with type=text, except that thw web
browser should should obscure the value that is being entered
• Has the same attributes as input element with type=text

COMP519 Web Programming Lecture 9 Slide L9 – 17


HTML Elements for the Body Form Controls

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

• If no radio button within a group is selected when the associated form is


submitted, then no value for the group is send to the server
; if the user must make a selection,
then set the required attribute for at least one element
• If a radio button within a group is selected when the associated form is
submitted, but the value-attribute of that input element is not set,
then the default value on will be returned
; make sure that all input-elements within a radio button group
have a non-empty value-attribute

COMP519 Web Programming Lecture 9 Slide L9 – 20


HTML Elements for the Body Form Controls

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 >

• No radio button is selected and no selection is required, so if we activate


the submit button right away, no values will be send to process.php
; if we want to pre-select a button, then we should
set the checked attribute for one of the elements
• If we select the first button and then activate the button, then
contact=email will be send to process.php
COMP519 Web Programming Lecture 9 Slide L9 – 21
HTML Elements for the Body Form Controls

Textarea

• A textarea element represents a multi-line text input control


• A textarea 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
• cols: the visible width of a text area (number)
• rows: the visible height of a text areas (number)
• maxlength: maximum number of characters that can be entered
entering more is not possible
• placeholder: a short hint describing the expected value of a text area
(disappears as soon as the user enters a value)
• required: specifies that a text area must be filled out
• wrap: specifies whether newlines are preserved
("hard" ; yes / "soft" ; no)
< textarea name =" problem1 " id =" p1 " cols ="10" rows ="4" maxlength ="35"
required wrap =" hard " > Describe your problem </ textarea >
< textarea name =" problem2 " id =" p2 " cols ="10" rows ="4" wrap =" soft "
placeholder =" Describe your problem " > </ textarea >
COMP519 Web Programming Lecture 9 Slide L9 – 22
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
• 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 >

COMP519 Web Programming Lecture 9 Slide L9 – 24


HTML Elements for the Body Form Controls

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 >

• By default, the first option is selected


• If the selection is not changed and the user activates the submit button,
then module=COMP517 is sent to process.php
• In general, the value associated with the selected option will be send

COMP519 Web Programming Lecture 9 Slide L9 – 25


HTML Elements for the Body Form Controls

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 >

• Adding the attribute selected to the second option, makes it the


option that is selected by default
• If the selection is not changed and the user activates the submit button,
then module=COMP518 is sent to process.php

COMP519 Web Programming Lecture 9 Slide L9 – 26


HTML Elements for the Body Form Controls

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

Revision and Further Reading


Read
• Chapter 9: Forms
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

COMP519 Web Programming Lecture 9 Slide L9 – 28


COMP519 Web Programming
Lecture 10: JavaScript (Part 1)
Handouts

Ullrich Hustadt

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents

26 JavaScript
Motivation
Overview
Example
Scripts
Type System

27 Further Reading

COMP519 Web Programming Lecture 10 Slide L10 – 1


JavaScript Motivation

JavaScript: Motivation

• HTML/CSS is sufficient for HTML documents aimed at


disseminating information that does not change too frequently
• Web pages documents that remain the same each time they are
accessed are called static web pages
; HTML/CSS is sufficient for static web pages
• In order to develop interactive/reactive web pages we must integrate
programming in some form or another
• One form is client-side programming/scripting:
• Code is written in a separate programming/scripting language
• Code is embedded in the HTML markup of a web page or
linked to from the page and accessible by the web browser
• Code is executed by the web browers (or external run-time environment)
on the user’s device

COMP519 Web Programming Lecture 10 Slide L10 – 2


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

COMP519 Web Programming Lecture 10 Slide L10 – 3


JavaScript Motivation

Scripting languages: Properties

• Program code is present at run time and starting point of execution


• compilation by programmer/user is not needed
• compilation to bytecode or other low-level representations
may be performed ‘behind the scenes’ as an optimisation
• Presence of a suitable runtime environment is required for the execution
of scripts
• includes an interpreter, or just-in-time compiler, or bytecode compiler plus
virtual machine
• typically also includes a large collection of libraries
• Executation of scripts is typically slower then the execution of code that
has been fully pre-compiled to machine code

COMP519 Web Programming Lecture 10 Slide L10 – 4


JavaScript Motivation

Scripting languages: Properties

• Variables, functions, and methods


typically do not require type declarations
(automatic conversion between types, e.g. strings and numbers)
• Some built-in data structures (more than in C, fewer than in Java)
• Ability to generate, load, and interpret source code at run time
through an eval function
var x = 2;
var y = 6;
var str = " if ( x > 0) { y / x } else { -1 }";
console . log ( eval ( str )); // Output : 3
x = 0;
console . log ( eval ( str )); // Output : -1

COMP519 Web Programming Lecture 10 Slide L10 – 5


JavaScript Motivation

Scripting languages: Properties

• The evolution of a scripting language typically starts


with a limited set of language constructs for a specific purpose
Example: PHP started as set of simple ‘functions’
for tracking visits to a web page
• The language then accumulates more and more language constructs
as it is used for a wider range of purposes
• These additional language constructs may or may not fit well together
with the original core and/or may duplicate existing language constructs
• During this evolution of the language, backward compatibility
may or may not be preserved
; Language design of scripting languages is often sub-optimal

COMP519 Web Programming Lecture 10 Slide L10 – 6


JavaScript Overview

JavaScript

• JavaScript is a language for client-side scripting


• script code is embedded in a web page and
delivered to the client as part of the web page and
executed by the user’s web browser
; code is visible to the user/client
• allows for better interactivity compared to server-side scripting as reaction
time is improved and data exchange with the server can be minimised
• a web browser may not support JavaScript or
the user may have disallowed the execution of JavaScript code
• different JavaScript engines may lead to different results, in particular,
results not anticipated by the developer of JavaScript code
• performance relies on the efficiency of the JavaScript engine and
the client’s computing power

COMP519 Web Programming Lecture 10 Slide L10 – 7


JavaScript Overview

JavaScript

• JavaScript is a language for client-side scripting


• operations that refer to the location of the client are easy:
document . write (" Local time : " + ( new Date ). toString ());

• for security reason, scripts are limited in what they can do,
e.g. scripts cannot access the client’s filestore

COMP519 Web Programming Lecture 10 Slide L10 – 8


JavaScript Overview

JavaScript: History

• originally developed by Brendan Eich at Netscape


under the name Mocha
• first shipped together with Netscape browser in September 1995
under the name LiveScript
• obtained its current name in December 1995 under a deal between
Netscape and Sun Microsystems, the company behind Java,
in December 1995
• does not have a particularly close relationship to Java,
it mixes aspects of Java with aspects of other languages and its own
peculiarities
• is a dialect of ECMAScript, a scripting language standardised in the
ECMA-262 specification and ISO/IEC 16262 standard since June 1997
• other dialects include Microsoft’s JScript and Adobe’s ActionScript

COMP519 Web Programming Lecture 10 Slide L10 – 9


JavaScript Overview

JavaScript: Use

Website Client-Side Server-Side Database


Google JavaScript C, C++, Go, Java, BigTable, MariaDB
Python, PHP
Facebook JavaScript Hack, PHP, Python, MariaDB, MySQL,
C++, Java, . . . HBase Cassandra
YouTube Flash, C, C++, Python, Java, BigTable, MariaDB
JavaScript Go
Yahoo JavaScript PHP MySQL, PostgreSQL
Amazon JavaScript Java, C++, Perl Oracle Database
Wikipedia JavaScript PHP, Hack MySQL, MariaDB
Twitter JavaScript C++, Java, Scala MySQL
Bing JavaScript C++, C# MS SQL Server
Wikipedia Contributors: Programming languages used in most popular websites. Wikipedia, The Free Encyclopedia,
10 October 2018, at 19:05. http://en.wikipedia.org/wiki/Programming_languages_used_in_most_popular_websites
[accessed 21 October 2018]

COMP519 Web Programming Lecture 10 Slide L10 – 10


JavaScript Example

JavaScript: Hello World!


1 <! DOCTYPE html >
2 < html > < head > < title > Hello World </ title > </ head >
3 < body >
4 <p > Our first JavaScript script </ p >
5 < script >
6 document . writeln (" <p > <b > Hello World ! </b > </p >")
7 </ script >
8 < noscript >
9 JavaScript not supported or disabled
10 </ noscript >
11 </ body > </ html >

• JavaScript code is enclosed in a script-element


• Alternative HTML markup that is to be used in case JavaScript is not
enabled or supported by the web browser, can be specified in a
noscript-element
• File must be stored in a directory accessible by the web server, for
example $HOME/public_html, and be readable by the web server
COMP519 Web Programming Lecture 10 Slide L10 – 11
JavaScript Scripts

JavaScript scripts

• JavaScript scripts are embedded into HTML documents and are


enclosed in a script-element
• A JavaScript script consists of one or more statements and comments
; there is no need for a main function (or classes)
• Statements do not have to end in a semicolon but they can
; stick to one convention in your code
• Whitespace before and in-between statements is irrelevant
(This does not mean it is irrelevant to someone reading your code)
• One-line comments start with // and run to the end of the line
// This is a single - line comment .
• Multi-line comments are enclosed in /* and */
/* This is a multi - line comment . The syntax could also
be used for a comment that is only one line long . */

• Comments should precede the code they are referring to


COMP519 Web Programming Lecture 10 Slide L10 – 12
JavaScript Type System

JavaScript: Type System

• JavaScript is a dynamically and loosely typed language

Data Type / Datatype / Type


A set of computer represented values together with a set of operations
that can be performed on those values
Value Type

• Most programming languages provide


• variables to store values in
• parameters as special kind of variables used in the definition of an operation
to refer to an argument of the operation

COMP519 Web Programming Lecture 10 Slide L10 – 13


JavaScript Type System

JavaScript: Type System

• JavaScript is a dynamically and loosely typed language


• Statically typed programming language:
• Each variable is bound to a particular type
• Each variable can only store a value of matching type

must matc
Type h

Variable Value Type


• Dynamically typed programming language:
• Each variable can store a value of arbitrary type
• Each variable can stored values of different types at different times

Variable Value Type

COMP519 Web Programming Lecture 10 Slide L10 – 14


JavaScript Type System

JavaScript: Type System

• JavaScript is a dynamically and loosely typed language


• Strongly typed programming language:
• In the application of an operation each argument value must
be of matching type
• Values must be explicity converted to the matching type
(unless types are related)

2.1 + 5 + Integer . parseInt ("7") // Java

• Loosely typed programming language:


• In the application of an operation each argument value will
be implicitly converted to the matching type

2.1 + 5 + "7" // JavaScript

COMP519 Web Programming Lecture 10 Slide L10 – 15


JavaScript Type System

JavaScript: Type System

• JavaScript is a dynamically and loosely typed language


• There are types and each value is of a particular type (or none)
519 and 1.9e3 are of type number (and only of that type)
’519’ and "1.9e3" are of type string (and only of that type)
• But the type of a variable does not need to be declared
var x ; // declares the variable x

• The type of a variable depends on the value it currently stores qnd


the type can change if it is assigned a value of a different type
x = 519; // x is of type number
x = ’519 ’; // x is of type string

• Function declarations do not specify the type of their parameters


• In function applications the types of arguments will be adjusted
automatically (if possible)

COMP519 Web Programming Lecture 10 Slide L10 – 16


JavaScript Type System

JavaScript: Type System

• JavaScript is a dynamically and loosely typed language


• There are types and each value is of a particular type (or none)
• But the type of a variable does not need to be declared
• The type of a variable depends on the value it currently stores and
the type can change if it is assigned a value of a different type
• Function declarations do not specify the type of their parameters
function add (x , y ) { return x + y ; }
• In function applications the types of arguments will be adjusted
automatically (if possible)
add (519 , 1.9 e3 ) // returns the number 2419 = 519+1900
add ( ’519 ’ ,"1.9 e3 ") // returns the string ’5191.9 e3 ’
add (519 , ’1.9 e3 ’) // returns the string ’5191.9 e3 ’
add ( true , 1.9 e3 ) // returns the number 1901

; makes programming easier


; potentially leads to more bugs
COMP519 Web Programming Lecture 10 Slide L10 – 17
Further Reading

Revision and Further Reading


• Read
• Chapter 19: JavaScript Basics
• Chapter 20: The JavaScript Language: Basic JavaScript Syntax
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 1: What is JavaScript?
• Chapter 2: JavaScript in HTML
• Chapter 3: Language Basics: Syntax
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 10 Slide L10 – 18


COMP519 Web Programming
Lecture 11: JavaScript (Part 2)
Handouts

Ullrich Hustadt

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents

28 Primitive Data Types


Booleans
Numbers
Strings

29 Arrays Literals

30 Storing Values
Variables
Assignments
Constants

31 Determining the Type of a Value

32 Further Reading

COMP519 Web Programming Lecture 11 Slide L11 – 1


Types

Data Type / Datatype / Type


A set of computer represented values together with a set of operations
that can be performed on those values

• JavaScript distinguished four main types:


• boolean – booleans
• number – integers and floating-point numbers
• string – strings
• object – objects (including functions and arrays)
• Every value is of a particular type

COMP519 Web Programming Lecture 11 Slide L11 – 2


Primitive Data Types Booleans

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

• As in almost every programming language the operators


&& (conjunction) || (disjunction) ! (negation)
are so-called short-circuit boolean operators:
A boolean expression is evaluated (using inorder traversal) only
as far as is necessary to determine the overall truth value of the
expression
( true || ( false && ! (! ( true && ( false || true )))))
( true && ( false && ! (! ( true && ( false || true )))))

• 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)

COMP519 Web Programming Lecture 11 Slide L11 – 4


Primitive Data Types Numbers

Integers and Floating-point Numbers

• The JavaScript datatype number covers both


• integer numbers 0 2012 -40 1263978
• floating-point numbers 1.25 256.0 -12e19 2.4e-10
; all numbers are stored as 64-bit floating-point numbers
• There are also some pre-defined number constants including
Math.PI (case sensitive) 3.14159265358979323846
NaN (case sensitive) ‘not a number’
Infinity (case sensitive) ‘infinity’

COMP519 Web Programming Lecture 11 Slide L11 – 5


Primitive Data Types Numbers

Operators on Integers and Floating-point Numbers

• Arithmetic operators supported by JavaScript include


+, -, * Addition, Subtraction, Multiplication
/ Division
** Exponentiation
++ Increment (+1)
-- Decrement (−1)
• The Math object provides a wide range of additional
mathematical functions
Math.abs(number) absolute value
Math.ceil(number) round fractions up
Math.floor(number) round fractions down
Math.round(number) round fractions
Math.log(number) natural logarithm
Math.random() random number between 0 and 1
Math.sqrt(number) square root
COMP519 Web Programming Lecture 11 Slide L11 – 6
Primitive Data Types Numbers

Beware of Rounding

• Rounding is an arithmetic operation commonly included in


programming languages, but with different implementations:

JavaScript Java PHP


Math.round(2.4) 2 Math.round(2.4) 2 round(2.4) 2
Math.round(2.5) 3 Math.round(2.5) 3 round(2.5) 3
Math.round(2.6) 3 Math.round(2.6) 3 round(2.6) 3
Math.round(-2.4) -2 Math.round(-2.4) -2 round(-2.4) -2
Math.round(-2.5) -2 Math.round(-2.5) -2 round(-2.5) -3
Math.round(-2.6) -3 Math.round(-2.6) -3 round(-2.6) -3

• 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)

COMP519 Web Programming Lecture 11 Slide L11 – 7


Primitive Data Types Strings

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

• JavaScript uses + for string concatenation


"519" + ’123 ’ // returns "519123"
’the ’ + ’end ’ // returns " theend "

• JavaScript supports multi-line strings


document . writeln ("\
Your name is " + name + "\
and you are studying " + degree + "\
at " + university \
");

COMP519 Web Programming Lecture 11 Slide L11 – 9


Primitive Data Types Strings

String Operators

• There are a range of additional string operators, for example:

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"

COMP519 Web Programming Lecture 11 Slide L11 – 10


Arrays Literals

Array Literals

• An array literal is a comma-separated list of values enclosed in


square brackets
[2 ,3 ,5 ,7 ,11]
Each element of that list has an index position
given by the number of other elements preceding it
; the first index position is 0
[2 ,3 ,5 ,7 ,11]
| | | | |
0 1 2 3 4
• The values in an array literal do not need to be of the same type
[2 , ’ two ’ ,3 ," three " ,1.1 e1 , true ]

• The values in an array literal can include other array literals


(nested array literal)
[2 ,[3 ,5] ,[7 ,[11]]]

COMP519 Web Programming Lecture 11 Slide L11 – 11


Arrays Literals

Operators on Array Literals

• It is possible to access an element of an array literal via its index


position: arrayLiteral[index]
[2 ,3 ,5 ,7 ,11][1] // returns 3

• For a nested array literal, it is possible to iterate this access operation


[2 ,[3 ,5] ,[7 ,[11]]][1] // returns [3 ,5]
| | |
0 1 2

[2 ,[3 ,5] ,[7 ,[11]]][1][0] // returns 3

• The length operation returns the number of elements in an array


literal: arrayLiteral.length
[2 ,3 ,5 ,7 ,11]. length // returns 5

• We will discuss more operators in the context of array variables

COMP519 Web Programming Lecture 11 Slide L11 – 12


Storing Values Variables

Variables

• A JavaScript identifier may consist of


letters, digits, the $ symbol, and underscore,
but cannot start with a digit
• JavaScript variable names are JavaScript identifiers
• JavaScript variable names are case sensitive
weightInKilos $heightInMetres good choice of variable names

_62M _M62 _m62 valid variable names,


all distinct, but poor choice
_ $ valid variable names,
worst possible choice

COMP519 Web Programming Lecture 11 Slide L11 – 13


Storing Values Variables

Variables

• Variables can be declared using one of the following statements:


var variable1 , variable2 , ...
var variable1 = value1 , variable2 = value2 , ...
• The second statement also initialises the variables
• Used inside a function definition, a declaration creates a local variable
(only accessible within the function)
• Used outside a function definition, a declaration creates a global variable
• A variable can be initialised without a declaration
by assigning a value to it:
variable = value
• Both inside and outside a function definition,
initialising an undeclared variable creates a global variable
• Note: A declaration does not specify the type of a variable
only assigning a value of a certain type gives a variable a type
COMP519 Web Programming Lecture 11 Slide L11 – 14
Storing Values Variables

Variables

• In JavaScript, the use of the value of a variable that is neither declared


nor initialised will result in a reference error
• A declared but uninitialised variable has the default value undefined
and has type undefined

myVar1 // reference error


var myVar2 // myVar2 has value undefined
var myVar3 = 5 // myVar3 has value 5

COMP519 Web Programming Lecture 11 Slide L11 – 15


Storing Values Assignments

Assignments

• JavaScript uses the equality sign = for assignments


student_id = 200846369;

As in Java, this is an assignment expression


• The value of an assignment expression is the value assigned
b = ( a = 0) + 1; // a has value 0 , b has value 1

• JavaScript supports most of the standard binary assignment operators:


Binary assignment Equivalent assignment
var += expr var = var + expr
var -= expr var = var - expr
var *= expr var = var * expr
var /= expr var = var / expr
var %= expr var = var % expr
var **= expr var = var ** expr (not in MS IE)

COMP519 Web Programming Lecture 11 Slide L11 – 16


Storing Values Constants

Constants

• Some JavaScript dialects allow the definition of constants using


const variable1 = value1 , variable2 = value2 , ...

• defines one or more constants


• constants follow the same scope rules as variables

• Attempts to change the value of a constant should result in a type error


const columns = 10;
columns ++; // type error

• However, this construct is not supported by MS Internet Explorer 6–10


and does not have the desired effect in Safari before version 5.1.7
nor Opera before version 12

COMP519 Web Programming Lecture 11 Slide L11 – 17


Determining the Type of a Value

Determining the Type of a Value

• string typeof value


returns a string representation of the type of value
Boolean "boolean" Number "number"
String "string" Object "object"
undefined "undefined" null "object"
NaN "number" Infinity "number"
Future versions of JavaScript may have an option to change
typeof null to "null" (as in PHP)

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 >

COMP519 Web Programming Lecture 11 Slide L11 – 18


Further Reading

Revision and Further Reading

• 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

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents

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

COMP519 Web Programming Lecture 12 Slide L12 – 1


Type Conversion Type Coercion

Type Coercion

• JavaScript automatically converts a value to the appropriate type as


required by the operation applied to the value (type coercion)
5 * "3" // result is 15
5 + "3" // result is "53"
5 && "3" // result is "3"

• The value undefined is converted as follows:

Type Default Type Default Type Default


bool false string ’undefined’ number NaN

undefined || true // result is true


undefined + " -!" // result is " undefined -!"
undefined + 1 // result is NaN

COMP519 Web Programming Lecture 12 Slide L12 – 2


Type Conversion 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

Every other value is converted to true including


• Infinity
• ’0’
• functions
• objects, in particular, arrays with zero elements

COMP519 Web Programming Lecture 12 Slide L12 – 3


Type Conversion Type Casting

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

COMP519 Web Programming Lecture 12 Slide L12 – 4


Type Conversion Type Casting

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

COMP519 Web Programming Lecture 12 Slide L12 – 5


Comparison Operators Equality

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

• When comparing a number and a string, the string is converted to a


number
• When comparing with a boolean,
the boolean is converted to 1 if true and to 0 if false
• If an object is compared with a number or string, JavaScript uses the
valueOf and toString methods of the objects to produce a primitive
value for the object
• If two objects are compared, then the equality test is true only if both
refer to the same object
COMP519 Web Programming Lecture 12 Slide L12 – 6
Comparison Operators Equality

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

"123" == 123 ; true "123" === 123 ; false


"123" != 123 ; false "123" !== 123 ; true
"1.23e2" == 123 ; true 1.23e2 === 123 ; false
"1.23e2" == "12.3e1" ; false "1.23e2" === "12.3e1" ; false
5 == true ; false 5 === true ; false

COMP519 Web Programming Lecture 12 Slide L12 – 7


Comparison Operators Less and Greater Than

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

’35.5’ > 35 ; true ’35.5’ >= 35 ; true


’ABD’ > ’ABC’ ; true ’ABD’ >= ’ABC’ ; true
’1.23e2’ > ’12.3e1’ ; false ’1.23e2’ >= ’12.3e1’ ; false
"F1" < "G0" ; true "F1" <= "G0" ; true
true > false ; true true >= false ; true
5 > true ; true 5 >= true ; true

COMP519 Web Programming Lecture 12 Slide L12 – 8


Comparison Operators Numbers Revisited: NaN and Infinity

Numbers Revisited: NaN and Infinity

• JavaScript’s number type includes constants


NaN (case sensitive) ‘not a number’
Infinity (case sensitive) ‘infinity’
• The constants NaN and Infinity are used as return values for
applications of mathematical functions that do not return a number
• Math.log(0) returns -Infinity (negative ‘infinity’)
• Math.sqrt(-1) returns NaN (‘not a number’)
• 1/0 returns Infinity (positive ‘infinity’)
• 0/0 returns NaN (‘not a number’)

COMP519 Web Programming Lecture 12 Slide L12 – 9


Comparison Operators Numbers Revisited: NaN and Infinity

Numbers Revisited: NaN and Infinity

• Equality and comparison operators need to be extended to cover


NaN and Infinity:
NaN == NaN ; false NaN === NaN ; false
Infinity == Infinity ; true Infinity === Infinity ; true
NaN == 1 ; false Infinity == 1 ; false
NaN < NaN ; false Infinity < Infinity ; false
1 < Infinity ; true 1 < NaN ; false
Infinity < 1 ; false NaN < 1 ; false
NaN < Infinity ; false Infinity < NaN ; false

; A lot of standard mathematical properties for numbers


do not apply to the number type, e.g.

∀x, y ∈ R : (x < y ) ∨ (x = y ) ∨ (x > y )

; equality cannot be used to check for NaN

COMP519 Web Programming Lecture 12 Slide L12 – 10


Comparison Operators Numbers Revisited: NaN and Infinity

Integers and Floating-point numbers: NaN and Infinity

• JavaScript provides two functions to test whether a value is or is not


NaN, Infinity or -Infinity:
• bool isNaN(value)
returns TRUE iff value is NaN
• bool isFinite(value)
returns TRUE iff value is neither NaN nor Infinity/-Infinity
There is no isInfinite function
• In conversion to a boolean value,
• NaN converts to false
• Infinity converts to true
• In conversion to a string,
• NaN converts to ’NaN’
• Infinity converts to ’Infinity’

COMP519 Web Programming Lecture 12 Slide L12 – 11


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:
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

• An array is created by assigning an array literal to a variable


var arrayVar = []
var arrayVar = [ elem0 , elem1 , ... ]

• All operations that can be performed on array literals can be performed


on arrays:
arrayVar[index] returns the element at position index
arrayVar.length returns the length of the array
• Arrays have no fixed length and it is always possible to add more
elements to an array
• Accessing an element of an array that has not been assigned a value yet
returns undefined

COMP519 Web Programming Lecture 12 Slide L12 – 15


Arrays Definition

Arrays

• It is possible to assign a value to arrayVar.length


• if the assigned value is greater than the previous value of arrayVar.length,
then the array is ‘extended’ by additional undefined elements
• if the assigned value is smaller than the previous value of arrayVar.length,
then array elements with greater or equal index will be deleted

• Assigning an array to a new variable creates a reference to the


original array
; changes to the new variable affect the original array
• Arrays are also passed to functions by reference
• The slice function can be used to create a proper copy of an array:
object arrayVar.slice(start, end)
returns a copy of those elements of array variable that have indices
between start and end

COMP519 Web Programming Lecture 12 Slide L12 – 16


Arrays Definition

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 >

COMP519 Web Programming Lecture 12 Slide L12 – 17


Arrays Definition

Array functions

JavaScript has no stack or queue data structures,


but has stack and queue functions for arrays:
• number array.push(value1, value2,...)
appends one or more elements at the end of an array;
returns the number of elements in the resulting array
• mixed array.pop()
extracts the last element from an array and returns it
• mixed array.shift()
shift extracts the first element of an array and returns it
• number array.unshift(value1, value2,...)
inserts one or more elements at the start of an array variable;
returns the number of elements in the resulting array

COMP519 Web Programming Lecture 12 Slide L12 – 18


Arrays forEach-method

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 ] ...
}

• An alternative is the use of the forEach method:


var callback = function ( elem , index , arrayArg ) {
statements
}
array . forEach ( callback );

• The forEach method takes a function as an argument


• It iterates over all indices/elements of an array
• It passes the current array element (elem), the current index (index) and
a pointer to the array (arrayArg) to the function
• Return values of that function are ignored,
but the function may have side effecs
COMP519 Web Programming Lecture 12 Slide L12 – 19
Arrays forEach-method

forEach-method

var rewriteNames = function ( elem , index , arr ) {


arr [ index ] = elem . replace (/(\ w +)\ s (\ w +)/ , " $2 , $1 ");
}

var myArray = [ ’ Dave Jackson ’ , ’ Ullrich Hustadt ’];

myArray . forEach ( rewriteNames );

for ( i =0; i < myArray . length ; i ++) {


document . write ( ’[ ’+ i + ’] = ’+ myArray [ i ]+" ");
}
document . writeln (" < br >");

[0] = Jackson , Dave [1] = Hustadt , Ullrich <br >

COMP519 Web Programming Lecture 12 Slide L12 – 20


Arrays Array functions

Array operators: push, pop, shift, unshift


1 planets = [" earth "]
2 planets . unshift (" mercury " ," venus ")
3 planets . push (" mars " ," jupiter " ," saturn ");
4 document . writeln (" planets \ @1 : "+ planets . join (" ")+" < br >")
5 last = planets . pop ()
6 document . writeln (" planets \ @2 : "+ planets . join (" ")+" < br >")
7 first = planets . shift ()
8 document . writeln (" planets \ @3 : "+ planets . join (" ")+" < br >")
9 document . writeln (" \ @4 : "+ first +" "+ last +" < br >")
10 home = [" mercury " ," venus " ," earth "]. pop ()
11 document . writeln (" \ @5 : " + home + " < br >")
12 number = [" earth "]. push (" mars ");
13 document . writeln (" \ @6 : " + number + " < br >")
planets@1 : mercury venus earth mars jupiter saturn < br >
planets@2 : mercury venus earth mars jupiter < br >
planets@3 : venus earth mars jupiter < br >
@4 : mercury saturn < br >
@5 : earth < br >
@6 : 2 < br >
COMP519 Web Programming Lecture 12 Slide L12 – 21
Arrays Array functions

Revision and Further Reading

• 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

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents

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

COMP519 Web Programming Lecture 13 Slide L13 – 1


Control Structures

Control Structures

JavaScript control structures


• conditional statements
• switch statements
• while- and do while-loops
• for-loops
• break and continue
are syntactically identical to those of Java

COMP519 Web Programming Lecture 13 Slide L13 – 2


Control Structures Conditional statements

Control structures: conditional statements


JavaScript conditional statements do not allow for elsif- or
elseif-clauses, but conditional statements can be nested:
if ( condition ) {
statements
} else if ( condition ) {
statements
} else {
statements
}

• The else-clause is optional but there can be at most one


• Curly brackets can be omitted if there is only
a single statement in a clause

JavaScript also supports conditional expressions


condition ? if_true_expr : if_false_expr

COMP519 Web Programming Lecture 13 Slide L13 – 3


Control Structures Switch statements

Control structures: switch statement


Switch statements in JavaScript take the same form as in Java:

switch ( expr ) { • there can be arbitrarily many case-clauses


case expr1 : • the default-clause is optional but there can be
statements
break ; at most one
case expr2 : • expr is evaluated only once and then compared
statements
to expr1, expr2, etc using (loose) equality ==
break ;
default : • once two expressions are found to be equal the
statements corresponing clause is executed
break ;
}
• if none of expr1, expr2, etc are equal to expr,
then the default-clause will be executed
• break ‘breaks out’ of the switch statement
• if a clause does not contain a break command,
then execution moves to the next clause

COMP519 Web Programming Lecture 13 Slide L13 – 4


Control Structures Switch statements

Control structures: switch statement


Not every case-clause needs to have associated statements
Example:
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 ;
}

COMP519 Web Programming Lecture 13 Slide L13 – 5


Control Structures While- and Do While-loops

Control Structures: while- and do while-loops

• JavaScript offers while-loops and do while-loops


while ( condition ) {
statements
}

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);

COMP519 Web Programming Lecture 13 Slide L13 – 6


Control Structures For-loops

Control structures: for-loops


• for-loops in JavaScript take the form
for ( initialisation ; test ; increment ) {
statements
}
Again, the curly brackets are not required if the body of the loop only
consists of a single statement
• A for-loop is equivalent to the following while-loop:
initialisation ;
while ( test ) {
statements ;
increment
}

COMP519 Web Programming Lecture 13 Slide L13 – 7


Control Structures For-loops

Control structures: for-loops


• In JavaScript, initialisation and increment can consist of more
than one statement, separated by commas instead of semicolons
for ( i = 1 , j = 1; j >= 0; i ++ , j - -)
document . writeln ( i + " * " + j + " = " + i * j )
// Indentation has no ‘ meaning ’ in JavaScript ,
// the next line is not part of the loop !! BAD STYLE !!
document . writeln (" Outside loop : i = " + i + " j = " + j )
1 * 1 = 1
2 * 0 = 0
Outside loop : i = 3 | j = -1
• Note: Variables introduced in a for-loop are still global even if declared
using var
for ( var i = 0; i < 1; i ++)
document . writeln (" Inside loop : i = " + i )
document . writeln (" Outside loop : i = " + i )
Inside loop : i = 0
Outside loop : i = 1
COMP519 Web Programming Lecture 13 Slide L13 – 8
Control Structures For-loops

Control Structures: break and continue

• 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 ++
}

• The continue command stops the execution of the current iteration of a


loop and moves the execution to the next iteration
for ( x = -2; x <= 2; x ++) {
if ( x == 0) continue ;
document . writeln ("10 / " + x + " = " + (10/ x ));
}
10 / -2 = -5
10 / -1 = -10
10 / 1 = 10
10 / 2 = 5

COMP519 Web Programming Lecture 13 Slide L13 – 9


Functions Defining a Function

Functions
Function definitions can take several different forms in JavaScript
including:
function identifier ( param1 , param2 , ...) {
statements }

var identifier = function ( param1 , param2 , ...) {


statements }

• Such function definitions are best placed in the head section


of an HTML page or in a library that is then imported
• Function names are case-sensitive
• The function name must be followed by parentheses
• A function has zero, one, or more parameters that are variables
• Parameters are not typed
• identifier.length can be used inside the body of the function to
determine the number of parameters
COMP519 Web Programming Lecture 13 Slide L13 – 10
Functions Defining a Function

Functions
Function definitions can take several different forms in JavaScript
including:
function identifier ( param1 , param2 , ...) {
statements }

var identifier = function ( param1 , param2 , ...) {


statements }

• The return statement


return value
can be used to terminate the execution of a function and to make
value the return value of the function
• The return value does not have to be of a primitive type
• A function can contain more than one return statement
• Different return statements can return values of different types
; there is no return type for a function
COMP519 Web Programming Lecture 13 Slide L13 – 11
Functions Calling a function

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

• The list of arguments can be shorter as well as longer as


the list of parameters
• If it is shorter, then any parameter without corresponding argument
will have value undefined

function sum ( num1 , num2 ) { return num1 + num2 }

sum1 = sum (5 ,4) // sum1 = 9


sum2 = sum (5 ,4 ,3) // sum2 = 9
sum3 = sum (5) // sum3 = NaN

COMP519 Web Programming Lecture 13 Slide L13 – 12


Functions Calling a function

‘Default Values’ for Parameters

• JavaScript does not allow to specify default values for


function parameters
• Instead a function has to check whether an argument has
the value undefined and take appropriate action

function sum ( num1 , num2 ) {


if ( num1 == undefined ) num1 = 0
if ( num2 == undefined ) num2 = 0
return num1 + num2
}

sum3 = sum (5) // sum3 = 5


sum4 = sum () // sum4 = 0

COMP519 Web Programming Lecture 13 Slide L13 – 13


Functions Variable-length Argument Lists

Variable-length Argument Lists

• Every JavaScript function has a property called arguments


• The arguments property consists of an array of all the arguments
passed to a function
• As for any JavaScript array, arguments.length can be used to
determine the number of arguments
// Function that returns the sum of all its arguments
function sumAll () {
var sum = 0
for ( var i =0; i < arguments . length ; i ++)
sum = sum + arguments [ i ]
return sum
}

sum0 = sumAll () // sum0 = 0


sum1 = sumAll (5) // sum1 = 5
sum2 = sumAll (5 ,4) // sum2 = 9
sum3 = sumAll (5 ,4 ,3) // sum3 = 12
COMP519 Web Programming Lecture 13 Slide L13 – 14
Functions Variable-length Argument Lists

Functions and Scope (1)

$x = " Hello " • A variable defined outside any


function func1 () { function is global
document . writeln ("1: "+ $x )
} • A global variable can be accessed
function func2 () { from any part of the script,
document . writeln ("2: "+ $x ) including inside a function
$x = " Bye "
document . writeln ("3: "+ $x )
}
func1 ()
func2 ()
document . writeln ("4: "+ $x )
1: Hello
2: Hello
3: Bye
4: Bye

COMP519 Web Programming Lecture 13 Slide L13 – 15


Functions Variable-length Argument Lists

Functions and Scope (2)

$x = " Hello " • A variable defined outside any


function func1 () { function is global
document . writeln ("1: "+ $x )
} • A global variable can be accessed
function func2 () { from any part of the script,
document . writeln ("2: "+ $x ) including inside a function
var $x = " Bye "
document . writeln ("3: "+ $x ) • To create a local variable inside a
} function we need to declare it
func1 () (and optionally initialise it)
func2 ()
document . writeln ("4: "+ $x )
1: Hello
2: undefined
3: Bye
4: Hello

COMP519 Web Programming Lecture 13 Slide L13 – 16


Functions Static Variables

JavaScript Functions and Static Variables

• JavaScript does not have a static keyword to declare a variable to be


static and preserve its value between different calls of a function
• A solution is to use a function property instead
function counter () {
counter . count = counter . count || 0 // function property
counter . count ++
return counter . count
}
document . writeln ("1: static count = "+ counter ())
document . writeln ("2: static count = "+ counter ())
document . writeln ("3: global counter . count = "+ counter . count )
1: static count = 1
2: static count = 2
3: global counter . count = 2

• As the example shows the function property is global/public


• Private static variables require more coding effort
COMP519 Web Programming Lecture 13 Slide L13 – 17
Functions Example

JavaScript Functions: Example

function bubble_sort ( array ) {


if (!( array && array . constructor == Array ))
throw (" Argument not an array ")
for ( var i =0; i < array . length ; i ++) {
for ( var j =0; j < array . length - i ; j ++) {
if ( array [ j +1] < array [ j ]) {
// swap can change array because array is
// passed by reference
swap ( array , j , j +1)
} } }
return array
}

function swap ( array , i , j ) {


var tmp = array [ i ]
array [ i ] = array [ j ]
array [ j ] = tmp
}

COMP519 Web Programming Lecture 13 Slide L13 – 18


Functions Example

JavaScript Functions: Example

function bubble_sort ( array ) { ... }


function swap ( array , i , j ) { ... }

array = [20 ,4 ,3 ,9 ,6 ,8 ,5 ,10]


document . writeln (" array before sorting " +
array . join (" , ")+" < br >")
sorted = bubble_sort ( array . slice (0)) // slice creates copy
document . writeln (" array after sorting of copy " +
array . join (" , ")+" < br >")
sorted = bubble_sort ( array )
document . writeln (" array after sorting of itself " +
array . join (" , ")+" < br >")
document . writeln (" sorted array " +
sorted . join (" , ")+" < br >")
array before sorting 20 , 4 , 3 , 9 , 6 , 8 , 5 , 10 < br >
array after sorting of copy 20 , 4 , 3 , 9 , 6 , 8 , 5 , 10 < br >
array after sorting of itself 3 , 4 , 5 , 6 , 8 , 9 , 10 , 20 < br >
sorted array 3 , 4 , 5 , 6 , 8 , 9 , 10 , 20 < br >

COMP519 Web Programming Lecture 13 Slide L13 – 19


Functions Nested Function Definitions

Nested Function Definitions

• Function definitions can be nested in JavaScript


• Inner functions have access to the variables of outer functions
• By default, inner functions can not be invoked from outside
the function they are defined in
function bubble_sort ( array ) {
function swap (i , j ) {
// swap can change array because array is
// a local variable of the outer function bubble_sort
var tmp = array [ i ]; array [ i ] = array [ j ]; array [ j ] = tmp ;
}
if (!( array && array . constructor == Array ))
throw (" Argument not an array ")
for ( var i =0; i < array . length ; i ++) {
for ( var j =0; j < array . length - i ; j ++) {
if ( array [ j +1] < array [ j ]) swap (j , j +1)
} }
return array }
COMP519 Web Programming Lecture 13 Slide L13 – 20
JavaScript Libraries

JavaScript libraries

• Collections of JavaScript functions (and other code), libraries,


can be stored in one or more files and then be reused
• By convention, files containing a JavaScript library are given
the file name extension .js
• <script>-tags are not allowed to occur in the file
• A JavaScript library is imported using
< script src =" url " > </ script >
where url is the (relative or absolute) URL for library
< script src =" http :// cgi . csc . liv . ac . uk / ∼ ullrich / jsLib . js " >
</ script >

• One such import statement is required for each library


• Import statements are typically placed in the head section of a page or
at the end of the body section (see next slide)
• Web browers typically cache libraries
COMP519 Web Programming Lecture 13 Slide L13 – 21
JavaScript Libraries

JavaScript Libraries: Import Statements


• JavaScript code may change the HTML markup of an HTML document
• Consequently, whenever a browers encounters a script element,
by default, it stops parsing the remaining HTML markup of the page
until that script element has been processed
; poor user experience
• ‘Safe solution’: Put script elements at the end of the body element
• ‘Better solution’: Use the async or defer attribute of the script
element to change the default behaviour
< script src =" jsLib1 . js " async > </ script >
< script src =" jsLib2 . js " async > </ script >
Do not wait for the processing of the script elements, fetch and
execute jsLib1.js and jsLib2.js (in parallel) in any order
< script src =" jsLib1 . js " defer > </ script >
< script src =" jsLib2 . js " defer > </ script >
Do not wait, fetch jsLib1.js and jsLib2.js (in parallel), execute in
order after parsing is finished
COMP519 Web Programming Lecture 13 Slide L13 – 22
JavaScript Libraries

JavaScript Libraries: Example


~ullrich/public_html/sort.js
function bubble_sort ( array ) {
function swap (i , j ) { ... }
... swap (j , j +1) ...
return array
}
example.html
< html lang =" en - GB " >
< head > < title > Sorting example </ title >
< script src =" http :// cgi . csc . liv . ac . uk / ∼ ullrich / sort . js " >
</ script >
</ head >
< body >
< script >
array = [20 ,4 ,3 ,9 ,6 ,8 ,5 ,10];
sorted = bubble_sort ( array . slice (0))
</ script >
</ body >
</ html >
COMP519 Web Programming Lecture 13 Slide L13 – 23
JavaScript Libraries

Revision and Further Reading

• 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

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents

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

COMP519 Web Programming Lecture 14 Slide L14 – 1


(User-defined) Objects Object Literals

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 ."

• Every part of a JavaScript program is executed in a particular


execution context
• Every execution context offers a keyword this
as a way of referring to itself
• In person1.hello() the execution context of hello() is person1
; this.name.first is person1.name.first

COMP519 Web Programming Lecture 14 Slide L14 – 3


(User-defined) Objects Object Literals

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

COMP519 Web Programming Lecture 14 Slide L14 – 4


(User-defined) Objects Object Constructors

Object Constructors

• JavaScript is an object-oriented language, but one without classes


• Instead of defining a class,
we can define a function that acts as object constructor
• variables declared inside the function will be properties of the object
; each object will have its own copy of these variables
• it is possible to make such properties private or public
• inner functions will be methods of the object
• it is possible to make such functions/methods private or public
• private properties/methods can only be accessed by the object itself
• public properties/methods can be accessed from outside the object

• Whenever an object constructor is called,


prefixed with the keyword new, then
• a new object is created
• the function is executed with the keyword this bound to that object
COMP519 Web Programming Lecture 14 Slide L14 – 5
(User-defined) Objects Object Constructors

Objects: Definition and Use


function SomeObj () {
instVar2 = ’B ’ // private property
var instVar3 = ’C ’ // private property

this . instVar1 = ’A ’ // public property

this . method1 = function () { // public method


// use of a public variable , e . g . ‘ instVar1 ’ , must be preceded by ‘ this ’
return ’ m1 [ ’ + this . instVar1 + ’] ’ + method3 () }

this . method2 = function () { // public method


// calls of a public method , e . g . ‘ method1 ’ , must be preceded by ‘ this ’
return ’ m2 [ ’ + this . method1 () + ’] ’ }

method3 = function () { // private method


return ’ m3 [ ’ + instVar2 + ’] ’ + method4 () }

var method4 = function () { // private method


return ’ m4 [ ’ + instVar3 + ’] ’ }
}
obj = new SomeObj () // creates a new object
obj . instVar1 --> "A"
obj . instVar2 --> undefined
obj . instVar3 --> undefined
obj . method1 () --> " m1 [ A ] m3 [ B ] m4 [ C ]"
obj . method2 () --> " m2 [ m1 [ A ] m3 [ B ] m4 [ C ]]"
obj . method3 () --> error
obj . method4 () --> error

COMP519 Web Programming Lecture 14 Slide L14 – 6


(User-defined) Objects Object Constructors

Objects: Definition and Use


function SomeObj () {
this . instVar1 = ’A ’ // public property

instVar2 = ’B ’ // private property


var instVar3 = ’C ’ // private property

this . method1 = function () { ... } // public method


this . method2 = function () { ... } // public method

method3 = function () { ... } // private method


var method4 = function () { ... } // private method
}

• Note that all of instVar1 to instVar3, method1 to method4 are


properties (instance variables, members) of SomeObj
• The only difference is that instVar1 to instVar3 store strings while
method1 to method4 store functions
; every object stores its own copy of the methods
COMP519 Web Programming Lecture 14 Slide L14 – 7
(User-defined) Objects Prototype Property

Objects: Prototype Property

• All functions have a prototype property that can hold


shared object properties and methods
; objects do not store their own copies of these properties and
methods but only store references to a single copy
function SomeObj () {
this . instVar1 = ’A ’ // public property

instVar2 = ’B ’ // private property


var instVar3 = ’C ’ // private property

SomeObj . prototype . method1 = function () { ... } // public


SomeObj . prototype . method2 = function () { ... } // public

method3 = function () { ... } // private method


var method4 = function () { ... } // private method
}
Note: prototype properties and methods are always public!
COMP519 Web Programming Lecture 14 Slide L14 – 8
(User-defined) Objects Prototype Property

Objects: Prototype Property


• The prototype property can be modified ‘on-the-fly’
; all already existing objects gain new properties / methods
; manipulation of properties / methods associated with the
prototype property needs to be done with care
function SomeObj () { ... }
obj1 = new SomeObj ()
obj2 = new SomeObj ()
document . writeln ( obj1 . instVar4 ) // undefined
document . writeln ( obj2 . instVar4 ) // undefined

SomeObj . prototype . instVar4 = ’A ’


document . writeln ( obj1 . instVar4 ) // ’A ’
document . writeln ( obj2 . instVar4 ) // ’A ’

SomeObj . prototype . instVar4 = ’B ’


document . writeln ( obj1 . instVar4 ) // ’B ’
document . writeln ( obj2 . instVar4 ) // ’B ’

obj1 . instVar4 = ’C ’ // creates a new property for obj1


SomeObj . prototype . instVar4 = ’D ’
document . writeln ( obj1 . instVar4 ) // ’C ’ !!
document . writeln ( obj2 . instVar4 ) // ’D ’ !!
COMP519 Web Programming Lecture 14 Slide L14 – 9
(User-defined) Objects Prototype Property

Objects: Prototype Property

• The prototype property can be modified ‘on-the-fly’


; all already existing objects gain new properties / methods
; manipulation of properties / methods associated with the
prototype property needs to be done with care
function SomeObj () { ... }
obj1 = new SomeObj ()
obj2 = new SomeObj ()

SomeObj . prototype . instVar5 = ’E ’

SomeObj . prototype . setInstVar5 = function ( arg ) {


this . instVar5 = arg
}

obj1 . setInstVar5 ( ’E ’)
obj2 . setInstVar5 ( ’F ’)

document . writeln ( obj1 . instVar5 ) // ’E ’ !!


document . writeln ( obj2 . instVar5 ) // ’F ’ !!
COMP519 Web Programming Lecture 14 Slide L14 – 10
(User-defined) Objects Public and Private Static Variables

‘Class’ Variables and ‘Class’ Methods


Function properties can be used to emulate Java’s class variables
(static variables shared among objects) and class methods
function Circle ( radius ) { this . r = radius }

// ‘ class variable ’ - property of the Circle constructor function


Circle . PI = 3.14159

// ‘ instance method ’
Circle . prototype . area = function () {
return Circle . PI * this . r * this . r ; }

// ‘ class method ’ - property of the Circle constructor function


Circle . max = function ( cx , cy ) {
if ( cx . r > cy . r ) { return cx } else { return cy }
}

c1 = new Circle (1.0) // create an object of the Circle class


c1 . r = 2.2; // set the r property
c1_area = c1 . area (); // invoke the area () instance method
x = Math . exp ( Circle . PI ) // use the PI class variable in a computation
c2 = new Circle (1.2) // create another Circle object
bigger = Circle . max ( c1 , c2 ) // use the max () class method

COMP519 Web Programming Lecture 14 Slide L14 – 11


(User-defined) Objects Public and Private Static Variables

Private Static Variables


In order to create private static variables shared between objects
we can use a self-executing anonymous function
var Person = ( function () {
var population = 0 // private static ‘ class ’ variable

return function ( value ) { // constructor


population ++
var name = value // private property
this . setName = function ( value ) { name = value }
this . getName = function () { return name }
this . getPop = function () { return population }
}
}())

person1 = new Person ( ’ Peter ’)


person2 = new Person ( ’ James ’)
person1 . getName () --> ’ Peter ’
person2 . getName () --> ’ James ’
person1 . name --> undefined
Person . population || person1 . population --> undefined
person1 . getPop () --> 2
person1 . setName ( ’ David ’)
person1 . getName () --> ’ David ’

COMP519 Web Programming Lecture 14 Slide L14 – 12


(User-defined) Objects Public and Private Static Variables

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

var person1 = { age : 32 ,


gender : ’ male ’ ,
name : ’ Bob Smith ’
}
for ( prop in person1 ) {
document . writeln ( ’ person1 [ ’+ prop + ’] has value ’
+ person1 [ prop ]+ ’<br > ’);
}

person1 [ gender ] has value male < br >


person1 [ name ] has value Bob Smith < br >
person1 [ age ] has value 32 < br >

COMP519 Web Programming Lecture 14 Slide L14 – 13


(User-defined) Objects Inheritance

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 }
}

function Square ( length ) {


this . width = this . height = length ;
this . type = ’ Square ’
}

// Square inherits from Rectangle


Square . prototype = new Rectangle ();

var sq1 = new Square (5);

document . writeln (" The area of sq1 is " + sq1 . area () );


The area of sq1 is 25
COMP519 Web Programming Lecture 14 Slide L14 – 14
(User-defined) Objects Classes as Syntactic Sugar

Classes as Syntactic Sugar

• ECMAScript 2015 introduced classes as syntactic sugar for


prototype-based objects
class Rectangle {
constructor ( width , height ) {
this . width = width
this . height = height
this . type = ’ Rectangle ’
}
get area () { return this . width * this . height }
}

class Square extends Rectangle {


constructor ( length ) {
super ( length , length )
this . type = ’ Square ’
}
}

var sq1 = new Square (5)


document . writeln (" The area of sq1 is " + sq1 . area ) // not sq1 . area ()!
COMP519 Web Programming Lecture 14 Slide L14 – 15
Pre-defined Objects Regular Expressions

Pre-defined Objects: RegExp

• JavaScript has a collection of pre-defined objects,


including Array, Date, RegExp, String
• RegExp objects are called regular expressions
• Regular expressions are patterns that are matched against strings
• Regular expressions are created via
/ regexp / // regular expression literal
new RegExp ( ’ regexp ’) // converting a string into a reg exp

• There are two methods provided by RegExp:


test(str) Tests for a match in a string, returns true or false
exec(str) Executes a search for a match in the string str,
returns an array with a match or null otherwise

COMP519 Web Programming Lecture 14 Slide L14 – 16


Pre-defined Objects Regular Expressions

Pre-defined Objects: RegExp


• The simplest regular expressions consist of a sequence of
• alphanumberic characters and
• non-alphanumeric characters escaped by a backslash:
that matches exactly this sequence of characters
/100\ $ / matches "100 $ " in " This 100 $ bill "

• There is a range of special characters that match characters other than


themselves or have special meaning
. Matches any character except the newline character \n
\n Matches the newline character \n
\w Matches a ‘word’ character (alphanumeric plus ‘_’)
\s Matches a whitespace character
\d Matches a decimal digit character
/\ w \ d / matches " P5 " , "51" , and "19" in " COMP519 "

COMP519 Web Programming Lecture 14 Slide L14 – 17


Pre-defined Objects Regular Expressions

Pre-defined Objects: RegExp


• There is a range of special characters that match characters other than
themselves or have special meaning
^ Matches beginning of input/line
$ Matches end of input/line
+ Matches the preceding expression 1 or more times
* Matches the preceding expression 0 or more times
[set] Matches any character in set which consists of
characters, special characters and ranges of characters
[^set] Matches any character not in set
/^[ a - z ]+ $ / matches " abc " , " x "
but not "0 abc " , " abc1 " , " ab " , " AB " , ""

/^\ s *[ a - z ]+\ s * $ / matches " abc " , " x " , " ab "
but not "0 abc " , " abc1 " , " AB " , ""

/^[^ a - z ]+ $ / matches " AB " , "0123"


but not " abc " , "x", "0 abc "
COMP519 Web Programming Lecture 14 Slide L14 – 18
Pre-defined Objects String

Pre-defined Objects: String

• JavaScript has a collection of pre-defined objects,


including Array, Date, Regular Expression, String
• A String object encapsulates values of the primitive datatype string
• Properties of a String object include
• length the number of characters in the string
• Methods of a String object include
• charAt(index)
the character at position index (counting from 0)
• substring(start,end)
returns the part of a string between positions start (inclusive)
and end (exclusive)
• toUpperCase()
returns a copy of a string with all letters in uppercase
• toLowerCase()
returns a copy of a string with all letters in lowercase
COMP519 Web Programming Lecture 14 Slide L14 – 19
Pre-defined Objects String

Pre-defined Objects: String and RegExp

• JavaScript supports (Perl-like) regular expressions and the String


objects have methods that use regular expressions:
• search(regexp)
matches regexp with a string and returns the start position of the first
match if found, -1 if not
• match(regexp)
– without g modifier returns the matching groups for the first match
or if no match is found returns null
– with g modifier returns an array containing all the matches for
the whole expression
• replace(regexp,replacement)
replaces matches for regexp with replacement,
and returns the resulting string

name1 = ’ Dave Shield ’. replace (/(\ w +)\ s (\ w +)/ , " $2 , $1 ")


regexp = new RegExp ("(\\ w +)\\ s (\\ w +)")
name2 = ’ Ken Chan ’. replace ( regexp , " $2 , $1 ")

COMP519 Web Programming Lecture 14 Slide L14 – 20


Pre-defined Objects Date

Pre-defined Objects: Date

• 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)

• Methods provided by Date include


• toString()
returns a string representation of the Date object
• getFullYear()
returns a four digit string representation of the (current) year
• parse()
parses a date string and returns the number of milliseconds
since midnight of 1 January 1970
COMP519 Web Programming Lecture 14 Slide L14 – 21
Further Reading

Revision and Further Reading

• 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

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents

42 Dynamic Web Pages Using JavaScript


Window and Document Objects
Window Object: Properties and Methods
Dialog Boxes
Input Validation

43 Further Reading

COMP519 Web Programming Lecture 15 Slide L15 – 1


Dynamic Web Pages Using JavaScript Window and Document Objects

Window and Document Objects


JavaScript provides two objects that are essential to the creation of
dynamic web pages and interactive web applications:
window object
• a JavaScript object that represents a browser window or tab
• automatically created whith every instance of a body or
frameset element
• allows properties of a window to be accessed and manipulated
• also allows new window objects to be created and manipulated
Example: window.open(’http://www.csc.liv.ac.uk’,’Home’)
• whenever an object method or property is referenced in a script without
an object name and dot prefix it is assumed by JavaScript to be a
property of the window object
Example: We can write alert() instead of window.alert()

COMP519 Web Programming Lecture 15 Slide L15 – 2


Dynamic Web Pages Using JavaScript Window Object: Properties and Methods

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

COMP519 Web Programming Lecture 15 Slide L15 – 6


Dynamic Web Pages Using JavaScript Window Object: Properties and Methods

Window Object: Example


< html lang =" en - GB " > < head > < title > Window handling </ title >
< script >
function Help () {
var OutputWindow = window . open ( ’ ’ , ’ Help ’ , ’ resizable =1 ’);
with ( OutputWindow . document ) {
open ()
writeln (" <! DOCTYPE html > < html > < head > < title > Help </ title >\
</ head > < body > This might be a context - sensitive help \
message , depending on the application and state of the \
page . </ body > </ html >");
close ()
}
}
</ script > </ head > < body >
< form name =" ButtonForm " id =" ButtonForm " action ="" >
<p >
< input type =" button " value =" Click for Help "
onclick =" Help ();" >
</p >
</ form > </ body > </ html >
COMP519 Web Programming Lecture 15 Slide L15 – 7
Dynamic Web Pages Using JavaScript Dialog Boxes

Window Object: Dialog Boxes

• Often we only want to open a new window in order to


• display a message
• ask for confirmation of an action
• request an input

• For these purposes, the window object in JavaScript provides


pre-defined methods for the handling of dialog boxes
(windows for simple dialogs):
• null alert(message_string)
• bool confirm(message_string)
• string prompt(message_string, default)

COMP519 Web Programming Lecture 15 Slide L15 – 8


Dynamic Web Pages Using JavaScript Dialog Boxes

Window Object: Dialog Boxes

• 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 ())

COMP519 Web Programming Lecture 15 Slide L15 – 9


Dynamic Web Pages Using JavaScript Dialog Boxes

Window Object: Dialog Boxes

• 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 ?")

COMP519 Web Programming Lecture 15 Slide L15 – 10


Dynamic Web Pages Using JavaScript Dialog Boxes

Window Object: Dialog boxes

• string prompt(message_string, default)


• creates a dialog box Example:
displaying message_string
var userName =
and an input field prompt (" What is your name ?" ,
• if a second argument default "")
is given, default will be
shown in the input field
• the box contains two buttons
‘Cancel’ and ‘OK’
• if the user selects ‘OK’ then
the current value entered in
the input field is returned as a
string, otherwise null is
returned

COMP519 Web Programming Lecture 15 Slide L15 – 11


Dynamic Web Pages Using JavaScript Dialog Boxes

Window Object: Dialog boxes

• prompt() always returns a string, even if the user enters a number


• To convert a string to number the following functions can be used:
• number parseInt(string [,base])
– converts string to an integer number wrt numeral system base
– only converts up to the first invalid character in string
– if the first non-whitespace character in string is not a digit, returns NaN
• number parseFloat(string)
– converts string to a floating-point number
– only converts up to the first invalid character in string
– if the first non-whitespace character in string is not a digit, returns NaN
• number Number(string)
– returns NaN if string contains an invalid character

COMP519 Web Programming Lecture 15 Slide L15 – 12


Dynamic Web Pages Using JavaScript Dialog Boxes

Dialog Boxes: Example


<! DOCTYPE html >
< html lang =" en - GB " >
< head > < title > Interaction example </ title > </ head >
< body >
< script >
do {
string = prompt (" How many items do you want to buy ?")
quantity = parseInt ( string )
} while ( isNaN ( quantity ) || quantity <= 0)
do {
string = prompt (" How much does an item cost ?")
price = parseFloat ( string )
} while ( isNaN ( price ) || price <= 0)
buy = confirm (" You will have to pay "+
( price * quantity ). toFixed (2)+
"\ nDo you want to proceed ?")
if ( buy ) alert (" Purchase made ")
</ script >
</ body > </ html >
http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/jsPrompt.html
COMP519 Web Programming Lecture 15 Slide L15 – 13
Dynamic Web Pages Using JavaScript Input Validation

User Input Validation


• A common use of JavaScript is the validation of user input
in an HTML form before it is processed:
• check that required fields have not been left empty
• check that fields only contain allowed characters or
comply to a certain grammar
• check that values are within allowed bounds
< form method =" post " action =" process . php "
onSubmit =" return validate ( this )" >
< label > User name : < input type =" text " name =" user " > </ label >
< label > Email address : < input type =" text " name =" email " > </ label >
< input type =" submit " name =" submit " / >
</ form >
< script >
function validate ( form ) {
fail = validateUser ( form . user . value )
fail += validateEmail ( form . email . value )
if ( fail == "") return true
else { alert ( fail ); return false } }
</ script >
COMP519 Web Programming Lecture 15 Slide L15 – 14
Dynamic Web Pages Using JavaScript Input Validation

User Input Validation

1 function validateUser ( field ) {


2 if ( field == "") return " No username entered \ n "
3 else if ( field . length < 5)
4 return " Username too short \ n "
5 else if (/[^ a - zA - Z0 -9 _ -]/. test ( field ))
6 return " Invalid character in username \ n "
7 else return ""
8 }
9
10 function validateEmail ( field ) {
11 if ( field == "") return " No email entered \ n "
12 else if (!(( field . indexOf (".") > 0) &&
13 ( field . indexOf (" @ ") > 0)) ||
14 /[^ a - zA - Z0 -9\.\ @ \ _ \ -]/. test ( field ))
15 return " Invalid character in email \ n "
16 else return ""
17 }

http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/jsValidate.html
COMP519 Web Programming Lecture 15 Slide L15 – 15
Further Reading

Revision and 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

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents

44 Dynamic Web Pages Using JavaScript


Document Object and Document Object Model
Accessing and Manipulating HTML Elements

45 Event-driven Programs
Introduction
Events

46 Extended Example

47 Further Reading

COMP519 Web Programming Lecture 16 Slide L16 – 1


Dynamic Web Pages Using JavaScript Document Object and Document Object Model

Window and Document objects


JavaScript provides two objects that are essential to the creation of
dynamic web pages and interactive web applications:
document object
• an object-oriented representation of a web page (HTML document) that
is displayed in a window
• allows interaction with the Document Object Model (DOM) of a page
Example: document.writeln() adds content to a web page

Document Object Model


A platform- and language-neutral interface that allows programs and
scripts to dynamically access and update the content, structure and style
of HTML, XHTML and XML documents

COMP519 Web Programming Lecture 16 Slide L16 – 2


Dynamic Web Pages Using JavaScript Document Object and Document Object Model

Document Object Model


Example:
The HTML table below is parsed into the following DOM
< table >
< tbody >
<tr >
<td > Shady Grove </ td >
<td > Aeolian </ td >
</ tr >
<tr >
<td > Over the River , Charlie </ td >
<td > Dorian </ td >
</ tr >
</ tbody >
</ table >

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

Accessing HTML Elements: Object Methods


Example:
// access the tbody element from the table element
var myTbodyElement = myTableElement . firstChild ;

// access its second tr element ; the list of children starts at 0 ( not 1).
var mySecondTrEle ment = myTbodyElement . childNodes [1];

// remove its first td element


mySe condTrElement . removeChild ( myS econdT rElement . firstChild );

// change the text content of the remaining td element


mySe condTrElement . firstChild . firstChild . data = " Peter ";

COMP519 Web Programming Lecture 16 Slide L16 – 4


Dynamic Web Pages Using JavaScript Accessing and Manipulating HTML Elements

Accessing HTML Elements: Names (1)


Instead of using methods such as firstChild and childNodes[n], it is
possible to assign names to denote the children of an HTML element
Example:
< form name =" form1 " action ="" >
< label > Temperature in Fahrenheit : </ label >
< input type =" text " name =" fahrenheit " size =10 value ="0" / > < br >
< label > Temperature in Celsius : </ label >
< input type =" text " name =" celsius " size ="10" value ="" / >
</ form >

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

Accessing HTML elements: Names (2)


Accessing HTML elements by giving them names and using paths within
the Document Object Model tree structure is still problematic
; If that tree structure changes, then those paths no longer work
Example:
Changing the previous form to
< form name =" form1 " action ="" >
< div class =" field " name =" fdiv " >
< label > Temperature in Fahrenheit : </ label >
< input type =" text " name =" fahrenheit " size ="10" value ="0" >
</ div >
< div class =" field " name =" cdiv " >
< label > Temperature in Celsius : </ label >
< input type =" text " name =" celsius " size ="10" value ="" >
</ div >
</ form >
means that document.form1.celsius no longer works as there is now a
div element between form and text field, we would now need to use
document.form1.cdiv.celsius
COMP519 Web Programming Lecture 16 Slide L16 – 6
Dynamic Web Pages Using JavaScript Accessing and Manipulating HTML Elements

Accessing HTML elements: IDs


A more reliable way is to give each HTML element an ID
(using the id attribute) and to use getElementById to retrieve
an HTML element by its ID
Example:
< form id =" form1 " action ="" >
Temperature in Fahrenheit :
< input type =" text " id =" fahrenheit " size ="10" value ="0" / > < br >
Temperature in Celsius :
< input type =" text " id =" celsius " size ="10" value ="" / > < br >
</ form >

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

COMP519 Web Programming Lecture 16 Slide L16 – 7


Dynamic Web Pages Using JavaScript Accessing and Manipulating HTML Elements

Manipulating HTML elements


It is not only possible to access HTML elements,
but also possible to change them on-the-fly
< html > < head > < title > Manipulating HTML elements </ title >
< style >
td . RedBG { background : # f00 ; }
</ style >
< script >
function change Bac k g ro u n dB l u e ( id ) {
document . getElementById ( id ). style . background = "#00 f ";
document . getElementById ( id ). innerHTML = " blue ";
}
function ch ang eBac k g ro un dR e d ( cell ) {
cell . className = " RedBG ";
cell . innerHTML = " red ";
}
</ script > </ head > < body >
< table border ="1" > < tr >
< td id ="0" onclick =" c h a ng e B ac k g r ou nd B l u e ( ’0 ’);" > white </ td >
< td id ="1" onclick =" c ha n geB ac kgr o und R ed ( this );" > white </ td >
</ tr > </ table > </ body > </ html >
http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/jsBG.html

COMP519 Web Programming Lecture 16 Slide L16 – 8


Event-driven Programs Introduction

Event-driven JavaScript Programs

• The JavaScript programs we have seen so far


were all executed sequentially
• programs have a particular starting point
• programs are executed step-by-step,
involving control structures and function execution
• programs reach a point at which their execution stops

COMP519 Web Programming Lecture 16 Slide L16 – 9


Event-driven Programs Introduction

Event-Driven JavaScript Programs


• Web applications are event-driven
; they react to events such as mouse clicks and key strokes

nickywalters: What is Event Driven Programming?


SlideShare, 7 September 2014.
https://tinyurl.com/ya58xbs9 [accessed 5/11/2017]

• 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

Event Handlers and HTML Elements

• HTML events are things, mostly user actions,


that happen to HTML elements
• Event handlers are JavaScript functions that process events
• Event handlers must be associated with HTML elements
for specific events
• This can be done via attributes
< input type =" button " value =" Help " onclick =" Help ()" >
• Alternatively, a JavaScript function can be used to add a handler to an
HTML element
// All good browsers
window . addEventListener (" load " , Hello )
// MS IE browser
window . attachEvent (" onload " , Hello )
More than one event handler can be added this way to the same
element for the same event
COMP519 Web Programming Lecture 16 Slide L16 – 11
Event-driven Programs Introduction

Event Handlers and HTML Elements

• As our scripts should work with as many browsers as possible,


we need to detect which method works:
if ( window . addEventListener ) {
window . addEventListener (" load " , Hello )
} else {
window . attachEvent (" onload " , Hello )
}

• Event handlers can also be removed


if ( window . re m o ve E ventListener ) {
window . r em o ve E v entListener (" load " , Hello )
} else {
window . detachEvent (" onload " , Hello )
}

COMP519 Web Programming Lecture 16 Slide L16 – 12


Event-driven Programs Introduction

Events: Load

• An (on)load event occurs when an object has been loaded


• Typically, event handlers for onload events are associated with the
window object or the body element of an HTML document

<! DOCTYPE html >


< html lang =" en - GB " >
< head >
< title > Onload Example </ title >
< script >
function Hello () { alert (" Welcome to my page !") }
</ script >
</ head >
< body onload =" Hello ()" >
<p > Content of the web page </ p >
</ body >
</ html >

http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/jsOnload.html
COMP519 Web Programming Lecture 16 Slide L16 – 13
Event-driven Programs Events

Events: Focus / Change

• 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 >

COMP519 Web Programming Lecture 16 Slide L16 – 14


Event-driven Programs Events

Events: Focus / Change


• 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
< form >
< label > Temperature in Fahrenheit : </ label >
< input type =" text " id =" fahrenheit " size ="10" value ="0"
onchange =" document . getElementById ( ’ celsius ’). value =
F ahrenhei tT o C el s i us ( parseFloat (
document . getElementById ( ’ fahrenheit ’). value )). toFixed (1);"
><br >
< label > Temperature in Celsius : </ label >
< input type =" text " id =" celsius "
size ="10" value ="" onfocus =" blur ();" > </ form >
http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/jsOnchange.html
COMP519 Web Programming Lecture 16 Slide L16 – 15
Event-driven Programs Events

Events: Blur / Click

• A blur event occurs when an HTML element loses focus


; onBlur attribute
• A click event occurs when an object on a form is clicked
; onClick attribute
Example:
< html > < head > < title > Onclick Example </ title > </ head > < body >
< form name =" form1 " action ="" >
Enter a number here :
< input type =" text " size ="12" id =" number " value ="3.1" >
<br > < br >
< input type =" button " value =" Double "
onclick =" document . getElementById ( ’ number ’). value =
parseFloat ( document . getElementById ( ’ number ’). value )
* 2;" >
</ form > </ body > </ html >

http://cgi.csc.liv.ac.uk/~ullrich/COMP284/examples/jsOnclick.html

COMP519 Web Programming Lecture 16 Slide L16 – 16


Event-driven Programs Events

Events: MouseOver / Select / Submit

• A keydown event occurs when the user presses a key


; onkeydown attribute
• A mouseOver event occurs once each time the mouse pointer moves
over an HTML element from outside that element
; onMouseOver attribute
• A select event occurs when a user selects some of the text within a text
or textarea field
; onSelect attribute
• A submit event occurs when a user submits a form
; onSubmit attribute

COMP519 Web Programming Lecture 16 Slide L16 – 17


Event-driven Programs Events

Events and DOM


• When an event occurs, an event object is created
; an event object has attributes and methods
; event objects can be created by your code
independent of an event occurring
• In most browsers, the event object is passed to event handler functions
as an argument
• In most versions of Microsoft Internet Explorer, the most recent event
can only be accessed via window.event
< html > < body onKeyDown =" processKey ( event )" >
< script >
function processKey ( e ) {
e = e || window . event
document . getElementById (" message "). innerHTML =
String . fromCharCode ( e . keyCode )+ ’ has been pressed ’ }
</ script >
<! - - key code will appear in the paragraph below -->
<p id =" message " > </p >
</ body > </ html >
COMP519 Web Programming Lecture 16 Slide L16 – 18
Extended Example

Example: Two-Player Board Game


• We want to develop a two-player board game
along the lines of Tic-Tac-Toe
• The full code is available at
http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/jsBoard.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 >

COMP519 Web Programming Lecture 16 Slide L16 – 19


Extended Example

Example: Two-Player Board Game


• Following the Model-View-Controller paradigm we need a model of the
game, including the board and overall state of the
var board = [[0 ,0 ,0] ,[0 ,0 ,0] ,[0 ,0 ,0]];
var free = 9; // free positions on the board
var turn = 1; // alternates between 0 and 1

• We will use 0 to represent an empty position on the board


1 to represent a position taken by player 1
2 to represent a position taken by player 2
• We have a function that turns these values into ‘nice’ representations
function numToLetter ( num ) {
switch ( num ) {
case 0: return " "
case 1: return " O "
case 2: return " X "
}
}

COMP519 Web Programming Lecture 16 Slide L16 – 20


Extended Example

Example: Two-Player Board Game


• We need a function to show a message to the user
and another to clear that message
function showMessage ( message , style ) {
m1 = document . getElementById (" m1 ");
m1 . innerHTML = message ;
m1 . style . display = " block ";
m1 . className = style ;
}

function clearMessage () {
m1 = document . getElementById (" m1 ");
m1 . style . display = " none ";
}

COMP519 Web Programming Lecture 16 Slide L16 – 21


Extended Example

Example: Two-Player Board Game


• The play function implements the turn of a user
function play (x ,y , event ) {
clearMessage ();
console . log (" x = " + x + " y = " + y );
console . log (" b = " + board [ y ][ x ]);
if ( board [ y ][ x ] > 0) {
showMessage (" Grid position [" + x + " ," + y +
"] already occupied " ," RedBG ");
} else {
board [ y ][ x ] = 2 - turn ;
free - -;
event . target . innerHTML = numToLetter (2 - turn );
turn = 1 - turn ;
}
}

• 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

Example: Two-Player Board Game


• At the start we create a representation of the board
function init ( table ) {
for ( j =0; j < board . length ; j ++) {
var tr = document . createElement (" tr ");
table . appendChild ( tr );
for ( i =0; i < board [ j ]. length ; x ++) {
var td = document . createElement (" td ");
var txt = document . createTextNode (
numToLetter ( board [ j ][ i ]);
td . appendChild ( txt );
td . addEventListener (" click " , play . bind ( null ,i , j ));
tr . appendChild ( td );
}
}
}
table = document . getElementById ( ’ t1 ’);
init ( table );
• play.bind makes sure that parameters x and y of play are bound to the
current values of i and y
COMP519 Web Programming Lecture 16 Slide L16 – 23
Extended Example

Example: Two-Player Board Game


• Finally, we add some CSS directives to improve the visual appearance
of the game
< style >
td { border : 1 px solid black ;
width : 2 em ;
height : 2 em ;
text - align : center ;
vertical - align : middle ;
}
div . RedBG {
background - color : # f00 ;
}
div . GreenBG {
background - color : #0 f0 ;
}
</ style >

COMP519 Web Programming Lecture 16 Slide L16 – 24


Extended Example

Example: Adding a Computer Player / Delays


var processing = false

async function play (x ,y , event ) {


if (! processing ) {
processing = true ;
clearMessage ();
if ( board [ y ][ x ] > 0) {
showMessage (" Grid position [" + x + " ," + y +
"] already occupied " ," RedBG ");
} else {
board [ y ][ x ] = 2 - turn ; free - -;
event . target . innerHTML = numToLetter (2 - turn );
turn = 1 - turn ;
await sleep (250); // sleep 250 ms
computerMove ();
processing = false
} } }

function sleep ( ms ) {
return new Promise ( resolve = > setTimeout ( resolve , ms )) }
COMP519 Web Programming Lecture 16 Slide L16 – 25
Extended Example

Example: Two-Player Board Game


Possible improvements:
• We should detect that the board is full (free == 0) and
end the game with an appropriate message
• We should detect a winning placement of pieces on the board,
end the game and declare a winner

COMP519 Web Programming Lecture 16 Slide L16 – 26


Further Reading

Revision and Further Reading

• 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

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents

48 Python
Overview
Example
Basic Syntax
Type System

49 Primitive Data Types


Integers
Floating-Point Numbers
Complex Numbers
Strings
Booleans

50 Further Reading

COMP519 Web Programming Lecture 17 Slide L17 – 1


Python Overview

Python: History

• The implementation of Python was started in December 1989


by Guido van Rossum at CWI in the Netherlands
• The name “Python” is a reference to Monty Python’s Flying Circus
• In 2001 the Python Software Foundation took over the development of
Python; it maintans the CPython reference implementation of Python
• Python 2.0 was released in October 2000
• Python 3.0 was released in October 2008
with major imcompatibilities to Python 2.0
• Python 3.7, released 27 June 2018, is the current version
• Python is described as a “multi-paradigm programming language”,
including support for functional programming, object-oriented
programming, design by contract, and logic programming
• There exist interpreters as well as compilers for Python

COMP519 Web Programming Lecture 17 Slide L17 – 2


Python Example

Python: Hello World

1 #!/ usr / bin / python3


2 # HelloWorld . py
3 # Our first Python script
4
5 print (" Hello World ")

• On Unix/Linux systems, Python scripts begin with #! (called ‘hash


bang’ or ‘she bang’) and the location of the Python interpreter/compiler
• If not intended to be web-accessible, the script can be stored anywhere,
for example, in a file HellowWorld.py
• The script HellowWorld.py must be executable
• The script can then be executed using
bash$ ./ HelloWorld . py

assuming that the script is stored in the current working directory

COMP519 Web Programming Lecture 17 Slide L17 – 3


Python Basic Syntax

Basic Python Syntax

• A Python program/script consists of one or more statements and


comments
• One-line comments start with # and run to the end of the line
• Multi-line comments simply consist of several one-line comments
• Statements are delimited by newlines except where a newline is escaped
(by a backslash \)
print \
(" Hello World ")

COMP519 Web Programming Lecture 17 Slide L17 – 4


Python Basic Syntax

Basic Python Syntax


• Blocks of statements, called suites are delimited with indentation
; each time the level of indentation is increased, a new block starts
; each time the level of indentation is decreased, a block has ended
• A colon : separates the header of block from the rest of the suite
i = 0
while (i <3):
i += 1
print ( i ) # prints 1 , 2 , 3 ( on separate lines )
j = 0
while (j <3):
j += 1
print ( j ) # prints 3
k = 0
while (k <3):
k += 1
print ( k ) # IndentationError ,
# whole program does not run
COMP519 Web Programming Lecture 17 Slide L17 – 5
Python Type System

Python: Type System


• Python is both
• a dynamically typed language:
a variable declaration does not include a type and
a variable can hold values of different types over time
x = " Hello "
x = 42
is a valid sequence of statements
• a (mostly) strongly typed language:
values are not automatically converted from ‘unrelated’ types
y = " Hello " + 42
will cause an error in Python
• However, quite a number of types are considered to be ‘related’
z = 42 and True # z --> True
will not cause an error in Python although a boolean operator is applied
to a number
COMP519 Web Programming Lecture 17 Slide L17 – 6
Python Type System

Types

Data Type / Datatype / Type


A set of computer represented values together with a set of operations
that can be performed on those values

• Python distinguished a lot more types than JavaScript, including


• int – integers
• float – floating-point numbers
• complex – complex numbers
• str – strings
• bool – booleans
• list – lists
• Types are classified into
• immutable – value is unchangeable once created
• mutable – value is changeable afer creation
COMP519 Web Programming Lecture 17 Slide L17 – 7
Primitive Data Types Integers

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

• Python 2 distinguishes between


int (32-bit integers) and
long (arbitrary length)
Elements of long are suffixed with the character l or L
• Python 3 only has the type int but it now stands for integers of
arbitrary length (only limited by memory)
; there are elements of int that are bigger than any element of float
• Python 3.6 allows to separate groups of digits by an underscore _
to improve readability of long numbers
10 _000_000 0 xCAFE_F00D 0 b_0011_1111_0100
1 _2_3_4_50 0 xC0_F_F_EE 0 b_00_11_1_0_01_0
• Python has no auto-increment ++ nor auto-decrement -- operator

COMP519 Web Programming Lecture 17 Slide L17 – 9


Primitive Data Types Floating-Point Numbers

Floating-point Numbers and Arithmetic Operators

• The Python immutable datatype float covers


(64-bit) floating-point numbers
1.25 256.0 -12e19 2.4e-10 1.7976931348623157e+308
• Python has no auto-increment ++ nor auto-decrement -- operator
• Python supports a wide range of arithmetic operators
+, *, -, ** applied to two integers produce an int
// (integer division) applied to a float produce a float
% (modulo)
/ always produces a float
round(number,prec) round fractions
• Peculiarities:
round(2.5) returns 3 as int
round(2.5,0) returns 3.0 as float
round(-2.5) returns -2 as int
COMP519 Web Programming Lecture 17 Slide L17 – 10
Primitive Data Types Floating-Point Numbers

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)

COMP519 Web Programming Lecture 17 Slide L17 – 11


Primitive Data Types Floating-Point Numbers

Additional Arithmetic Operators

• Additional arithmetic operators are available from the math module:


math.fabs(number) absolute value
math.ceil(number) round fractions up
math.floor(number) round fractions down
math.log(number) natural logarithm
math.sqrt(number) square root
• Interesting instances:
• math.sqrt(-1) returns ValueError: math domain error
• math.log(0) returns ValueError: math domain error
• 1/0 returns ZeroDivisionError: division by zero
• 0/0 returns ZeroDivisionError: division by zero

• Random number operators are available from the random module


random.uniform(low, high) random float between low and high
random.randint(low, high) random int between low and high
COMP519 Web Programming Lecture 17 Slide L17 – 12
Primitive Data Types Complex Numbers

Complex Numbers

• The Python immutable datatype complex covers complex numbers of


the form
real + imagJ
where real and imag are floating-point numbers
and J (or j) represents the square root of -1
• The cmath module provides additional arithmetic operators including
math.log(number) natural logarithm
math.sqrt(number) square root
• Interesting instances:
• cmath.sqrt(-1) returns 1j
• cmath.log(0) returns ValueError: math domain error

COMP519 Web Programming Lecture 17 Slide L17 – 13


Primitive Data Types Strings

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 ’ ’ ’

• In all these forms \ acts as escape character


• Each character in a string has an (index) position given by the number
of preceding characters
" university "
||||||||||
0123456789
COMP519 Web Programming Lecture 17 Slide L17 – 14
Primitive Data Types Strings

Strings

• Escape sequences have the same meaning as in JavaScript:


\’ (single quote) \" (double quote) \\ (backslash)
\b (backspace) \f (form feed) \n (newline)
\r (carriage return) \t (tab)
• Prefixing a string literal with the character r turns \ into an ordinary
character
"\" COMP519 \"" # " COMP519 "
r "\" COMP519 \"" # \" COMP519 \"

• Python uses + for string concatenation


" COMP " + ’519 ’ # returns " COMP519 "
’ the ’ + ’end ’ # returns " the end "
but does not automatically convert values of other types to strings
" COMP " + 519 # results in TypeError : must be str , not int

COMP519 Web Programming Lecture 17 Slide L17 – 15


Primitive Data Types Strings

Strings

• There are a range of additional string operators, for example:

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"

COMP519 Web Programming Lecture 17 Slide L17 – 16


Primitive Data Types Strings

Strings

• There are a range of additional string operators, for example:

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"]

COMP519 Web Programming Lecture 17 Slide L17 – 17


Primitive Data Types Booleans

Booleans

• Python has an immutable datatype bool


with constants True and False (case sensitive)
• Python offers the following short-circuit boolean operators:
and (conjunction) or (disjunction) not (negation)
• The following objects are evaluated by Python as False:
• numerical zero values (0, 0.0, 0.0+0.0j)
• the Boolean value False
• empty strings (but not the string "0")
• empty lists, empty tuples, empty dictionaries,
• the special value None
all other objects are evaluated as True
(truth testing procedure)

COMP519 Web Programming Lecture 17 Slide L17 – 18


Further Reading

Revision and Further Reading


Read
• Chapter 26: The Python Language: The History of Python
to
• Chapter 26: The Python 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

COMP519 Web Programming Lecture 17 Slide L17 – 19


COMP519 Web Programming
Lecture 18: Python (Part 2)
Handouts

Ullrich Hustadt

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents

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

COMP519 Web Programming Lecture 18 Slide L18 – 1


Complex Datatypes Lists

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

Operators on List Literals

• It is possible to access an element of a list literal via its index position:


listLiteral[index]
• Accessing an index position for which there is no element results in an
error
0 1 2 3 4
| | | | |
[2 ,3 ,5 ,7 ,11][5] # IndexError : list index out of range
[2 ,3 ,5 ,7 ,11][ -6 ] # IndexError : list index out of range

• 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

Operators on List Literals


• The len operation returns the number of elements in a list literal:
len(list)
len ([2 ,3 ,5 ,7 ,11]) # returns 5

• The + operation returns the concatenation of two list literals


[2 ,3] + [5 ,7 ,11] # returns [2 ,3 ,5 ,7 ,11]

• There are operators in and not in that check whether a value


occurs in a list or not
5 in [2 ,3 ,5 ,7 ,11] # returns True
6 not in [2 ,3 ,5 ,7 ,11] # returns True

• The operator count allows us to determine the number of occurrences


of an object in a list (using equality ==)
[2 ,3 ,2 ,4 ,2 ,5]. count (2) # returns 3
[2 e0 ,3 ,2.0 ,2.0+0 j ,5]. count (2) # returns 3

COMP519 Web Programming Lecture 18 Slide L18 – 4


Complex Datatypes Lists

Operators on List Literals


• Operators min and max return the minimal and maximal element of a
list literal, provided any two elements are comparable using <
min ([5 ,2 ,11 ,3 ,7]) # returns 2
max ([5 ,2 ,11 ,3 ,7]) # returns 11
min ([5 ,"2" ,11 ,7]) # TypeError

• The operator * applied to a list literal and a number N, creates a list


literal with N copies of the list literal
[5 ,2] * 3 # returns [5 ,2 ,5 ,2 ,5 ,2]

• We will discuss more operators in the context of list variables

COMP519 Web Programming Lecture 18 Slide L18 – 5


Complex Datatypes Sets

The Set Type


• Python 3 has a mutable set type for unordered collections with no
duplicate elements
• A set literal is a comma-separated list of values enclosed in
curly brackets
{ ’ apple ’ , ’ orange ’ , ’ apple ’ , ’ pear ’ , ’ orange ’ , ’ banana ’}

• While we can write duplicate elements in a set literal,


only one copy (up to equality == will be stored)
{1 , 1.0 , 1 e0 , 1.0+0 j , True } # same as {1}

• The empty set has to be written as set() not {}


• With set(sequence) we can convert a sequence into a set
set ([1 ,2 ,3 ,2 ,1]) # returns {1 ,2 ,3}

COMP519 Web Programming Lecture 18 Slide L18 – 6


Complex Datatypes Sets

The Set Type


• With value in set we can check whether value occurs in set
’ apple ’ in { ’ apple ’ , ’ orange ’ , ’ pear ’} # True
’ citron ’ in { ’ apple ’ , ’ orange ’ , ’ pear ’} # False

• 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

• Python supports the following set operators


set1 | set2 union set1 & set2 intersection
set1 - set2 difference set1 ^ set2 symmetric difference
{1 ,2 ,3} | {3 , 4, 5} # returns {1 ,2 ,3 ,4 ,5}
{1 ,2 ,3} & {3 , 4, 5} # returns {3}
{1 ,2 ,3} - {3 , 4, 5} # returns {1 ,2}
{1 ,2 ,3} ^ {3 , 4, 5} # returns {1 ,2 ,4 ,5}

COMP519 Web Programming Lecture 18 Slide L18 – 7


Complex Datatypes Ranges

The Range Type


• Python 3 has an immutable range type for sequences
of integer numbers, distinct from list literals of integer numbers
• Elements of range are used in for-loops
• Elements of range are constructed using
range ( after )
range ( start , after [ , step ])
where start is the first element of the range (default 0),
step is the increment added repeatedly to obtain the next ele-
ment of the range (default 1), and
after is the first element excluded from the range
• The operator list converts a range into a list
list ( range (5)) # returns [0 ,1 ,2 ,3 ,4]
list ( range (0 ,11 ,3)) # returns [0 ,3 ,6 ,9]
list ( range (9 ,0 , -3)) # returns [9 ,6 ,3]
• Most operators on list literals also work on ranges
COMP519 Web Programming Lecture 18 Slide L18 – 8
Complex Datatypes List and Set Comprehension

List and Set Comprehension

• In Mathematics we often construct sets as follows


{x | x ∈ E ∧ Φ(x)} or {f (x) | x ∈ E ∧ Φ(x)}
• In Python this approach is used in list comprehension and
set comprehension to construct lists and sets
{x 2 | x ∈ {0, . . . , 9}}
[x**2 for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 65, 81]

{x | x ∈ {0, . . . , 19} ∧ x is even}


[x for x in range(20) if x % 2 == 0]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

{y | x ∈ {2, 3} ∧ ∃n : n ≥ 2 ∧ y = x ∗ n ∧ y < 20}


{y for x in range(2, 4) for y in range(x*2, 20, x)}
{4, 6, 8, 10, 12, 14, 16, 18, 9, 15}
COMP519 Web Programming Lecture 18 Slide L18 – 9
Complex Datatypes List and Set Comprehension

Equality and Comparison Operators

• Python provides the following equality and comparison operators

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

COMP519 Web Programming Lecture 18 Slide L18 – 10


Equality and Comparison Operators

Equality and Comparison Operators


(1) "123" == 123 ; False
(2) "123" != 123 ; True
(3) 1.23e2 == 123 ; True
(4) 1.23e2 == 12.3e1 + 0j ; True
(5) 1.23e2 <= 12.3e1 + 0j ; TypeError
(6) 0 == False ; True
(7) 1 == True ; True
(8) 5 == True ; False
(9) "" == False ; False
(10) [1.0,0,2e1] == [1,False,20] ; True
(11) [1,2] is [1,2] ; False
(4) + (5) contradict the mathematical axiom
∀x, y ∈ C : (x = y ) → (x ≤ y )
(8) contradicts that 5 will ‘evaluate’ to True in all situations where
a boolean expression is involved (e.g. conditional statements)
(9) contradicts that ”” will ‘evaluate’ to False in all situations
where a boolean expression is involved
COMP519 Web Programming Lecture 18 Slide L18 – 11
Special Values nan and inf

nan and inf


• Since Python 3.5, the math module provides constants
math.nan (case sensitive) ‘not a number’
math.inf (case sensitive) ‘infinity’
in addition to math.pi for π that existed before
• However, only arithmetic operators with math.nan or math.inf as
arguments will return one of these constants
math.inf + 1 ; math.inf math.inf / math.inf ; math.nan
math.nan + 1 ; math.nan 1 / math.inf ; 0.0
• For comparisons we get
nan == nan ; False 1 == nan ; False
1 < nan ; False 1 > nan ; False
inf == inf ; True inf == nan ; False
• For testing whether a value is equal to nan or inf, Python provides
• math.isnan(value) returns True iff value is NaN
• math.isinf(value) returns True iff value is inf or -inf

COMP519 Web Programming Lecture 18 Slide L18 – 12


Special Values None

None

• The Python equivalent to JavaScript’s ‘undefined’ value


and Java’s ‘null’ value is the value None (case sensitive)
of type NoneType
• To check for None use the operator is
None is None # returns True
" High " is None # returns False
[] is None # returns False

COMP519 Web Programming Lecture 18 Slide L18 – 13


Determining the Type of a Value

Values and Types


• Python provides two functions to ‘query’ the type of an expression:
• type(value)
returns the type of value as a type object
• isinstance(value,type)
returns True iff value is of type
type(123) ; <class ’int’>
type(123.0) ; <class ’float’>
type("hello" ) ; <class ’str’>
type(False) ; <class ’bool’>
type([1,2,3]) ; <class ’list’>
isinstance(123,int) ; True
isinstance(123,float) ; False
isinstance(123.0,int) ; False
isinstance(123.0,float) ; True
isinstance("hello",str) ; True
isinstance(False,bool) ; True
isinstance([1,2,3],list) ; True

COMP519 Web Programming Lecture 18 Slide L18 – 14


Type Conversion

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

COMP519 Web Programming Lecture 18 Slide L18 – 16


Further Reading

Revision and Further Reading


Read
• Chapter 26: The Python Language: Data Types and Variables
• Chapter 26: The Python 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

COMP519 Web Programming Lecture 18 Slide L18 – 17


COMP519 Web Programming
Lecture 19: Python (Part 3)
Handouts

Ullrich Hustadt

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents

57 Storing Values
Variables
Assignments
Constants

58 Complex Datatypes Revisited

59 Control Structures
Conditional Statements
While-loops

60 Further Reading

COMP519 Web Programming Lecture 19 Slide L19 – 1


Storing Values Variables

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

• Accessing a variable before it has been assigned a value results in an


error
# student_id has not been assigned a value
print ( student_id )

NameError : name ’ student_id ’ is not defined

• If we want to introduce a variable, but do not have a sensible


initialisation value for it, None can be used
student_id = None

COMP519 Web Programming Lecture 19 Slide L19 – 3


Storing Values Assignments

Assignments

• Strictly speaking, in Python one assigns a (variable) name to a value,


not the other way round
; a (variable) name does not exist before the first assignment
• But, the syntax for an assignment is the same as in JavaScript
student_id = 200846369

• An assignment is not an expression


b = ( a = 0) + 1 # SyntaxError

• But more than one variable can be assigned a value in one go


a = b = c = 1 # a == 1, b == 1, c == 1
a ,b , c = 1 ,2 ,3 # a == 1, b == 2, c == 3
x ,y , z = [1 ,2 ,3] # x == 1, y == 2, z == 3
[x ,y , z ] = [1 ,2 ,3] # x == 1, y == 2, z == 3

• The first assignment to a variable defines that variable

COMP519 Web Programming Lecture 19 Slide L19 – 4


Storing Values Assignments

Assignments

• The assignment of a name var to a value can be removed by


del(var)
; the variable reverts to being undefined and
attempts to access it result in an error
student_id = 200846369
del ( student_id )
print ( student_id )
NameError : name ’ student_id ’ is not defined

COMP519 Web Programming Lecture 19 Slide L19 – 5


Storing Values Assignments

Assignments

• Python supports the standard binary assignment operators:


Binary assignment Equivalent assignment
var += expr var = var + expr
var -= expr var = var - expr
var *= expr var = var * expr
var /= expr var = var / expr
var %= expr var = var % expr
var **= expr var = var ** expr
• Remember:
Python has no auto-increment ++ nor auto-decrement -- operator
x += 1
y -= 1

is the closest you can get to an equivalent

COMP519 Web Programming Lecture 19 Slide L19 – 6


Storing Values Constants

Constants

• Python has no straightforward way of defining constants

COMP519 Web Programming Lecture 19 Slide L19 – 7


Storing Values Constants

Lists
• If we assign a list literal to a variable, we have a list
list1 = [2 ,3 ,5 ,7 ,11]

• All operations that can be performed on list literals can be performed on


lists
• If we assign one list to another, then both refer to the same list literal
list2 = list1
list1 [0] = 13
print ( list2 [0]) # prints 13 , not 2

• 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

• Given a variable lvar storing a list,


with lvar.sort() we can turn lvar into a sorted list based on <
; all elements of list must be comparable using <,
otherwise the operation fails
• The function has two keyword-only arguments
• reverse=True: reverses the order
• key=func: the function func is applied to elements before comparison
a = [2 ,11 ,3 ,7 ,5]
a . sort () # a now is [2 ,3 ,5 ,7 ,11]
a . sort ( reverse = True ) # a now is [11 ,7 ,5 ,3 ,2]

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 ’]

COMP519 Web Programming Lecture 19 Slide L19 – 9


Storing Values Constants

Lists

• The function sorted(sequence) returns a sorted list with the elements


of sequence
• sequence does not have to be a list, sorted can be applied to any
sequence
• sequence itself is not changed
• The function has two keyword-only arguments
• reverse=True: reverses the order
• key=func: the function func is applied to elements before comparison
sorted ([2 ,11 ,3 ,7 ,5]) # returns [2 ,3 ,5 ,7 ,11]
sorted ([2 ,11 ,3 ,7 ,5] , reverse = True ) # returns [11 ,7 ,5 ,3 ,2]

a = [2 ,11 ,3 ,7 ,5]
sorted ( a ) # returns [2 ,3 ,5 ,7 ,11]
print ( a ) # prints [2 ,11 ,3 ,7 ,5]

COMP519 Web Programming Lecture 19 Slide L19 – 10


Complex Datatypes Revisited

Lists

• The function zip(sequence1,...,sequenceN)


returns a sequence of tuples, where the i-th tuple contains the i-th
element from each input sequence
• construction stops when the shortest input sequence is exhausted
• We can use the list function to turn the result of zip into a list
list ( zip ([" Jim " , " Joe " , " Joy "] , [33 , 28 , 21]))
# returns [(" Jim " ,33) ,(" Joe " ,28) ,(" Joy " ,21)]

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 )]

COMP519 Web Programming Lecture 19 Slide L19 – 11


Complex Datatypes Revisited

Tuples

• A tuple literal is a comma-separated list of values enclosed in


parentheses and it is of type tuple
(2 , ’two ’ , 3 , " three " , 1.1 e1 , [ True , 1.3+2 j ])

• Tuple literals can be assigned to variables


tuple1 = (2 , ’two ’ , 3 , " three " , 1.1 e1 , [ True , 1.3+2 j ])

• In contrast to lists, parts of a tuple (literal) cannot be changed


tuple1 [0] = 5 # TypeError
del ( tuple1 [0]) # TypeError

• The operator tuple takes a list as an argument and returns a tuple


tuple ([3 , ’ three ’ , 4]) # returns (3 , ’ three ’ , 4)

COMP519 Web Programming Lecture 19 Slide L19 – 12


Complex Datatypes Revisited

Dictionaries

• A Python dictionary is a mapping of keys to values


(aka associative array or hash table)
• A dictionary literal is a comma-separated list of key-value pairs
consisting of a key and a value separated by a colon :
surrounded by curly brackets
{ ’ name ’: ’ Dave ’ , ’age ’: 23 , ’ height ’: ’185 cm ’ }

• Elements of any immutable type can be used as keys


• The value associated with a specific key key in a dictionary dict can
be accessed (and modified) using
dict [ key ]

dct = { ’ name ’: ’ Dave ’ , ’age ’: 23 , ’ height ’: ’185 cm ’ }


print ( dct [ ’ name ’]) # prints ’ Dave ’
dct [ ’ height ’] = ’190 cm ’ # ’ height ’ now maps to ’190 cm ’
dct [ ’ age ’] += 1 # ’age ’ now maps to 24
dct [ ’ surname ’] = ’ Shield ’ # ’ surname ’ maps to ’ Shield ’

COMP519 Web Programming Lecture 19 Slide L19 – 13


Complex Datatypes Revisited

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 ’

• The operators in and not in can be used to check whether a key is


in a dictionary
’ name ’ in dct # returns True
’job ’ not in dct # returns True

• A key-value pair can be removed using del :


del ( dct [ ’ height ’])

• For a dictionary dict


list(dict.keys()) returns a list of all keys in dict
list(dict.values()) returns a list of all values in dict
list(dict.items()) returns a list of all key-value pairs in dict
COMP519 Web Programming Lecture 19 Slide L19 – 14
Complex Datatypes Revisited

Dictionaries: Example

db = { 200846369: { ’ name ’: ’ Jan Olsen ’ ,


’ marks ’: { ’ COMP516 ’: 61 ,
’ COMP517 ’: 57 ,
’ COMP518 ’: 43 ,
’ COMP519 ’: 78 }
} }

average = sum ( db [200846369][ ’ marks ’]. values ()) / \


len ( db [200846369][ ’ marks ’]. values ())

print (" Average :" , average )


Average : 59.75

COMP519 Web Programming Lecture 19 Slide L19 – 15


Control Structures

Control Structures

Python control structures


• conditional statements
• (switch statements)
• while-loops
• for-loops
are all syntactically different to those in Java and JavaScript

COMP519 Web Programming Lecture 19 Slide L19 – 16


Control Structures Conditional Statements

Conditional Statements
Python conditional statements take the following form
if condition :
suite
elif condition :
suite
else :
suite

• The else-clause is optional and there can be at most one


• The elif-clause is optional and there can be more than one
• None of the suite blocks of statements can be empty
; the statement pass can be used as a ‘null statement’
if x == 0:
# We ’ ll come up with a solution for x == 0 later
pass
else :
y = y / x
COMP519 Web Programming Lecture 19 Slide L19 – 17
Control Structures Conditional Statements

Conditional Expressions
Since Python 2.5 also supports conditional expressions
if_true_expr if condition else if_false_expr

where condition is evaluated first and depending on the result


if_true_expr or if_false_expr are evaluated and returned

COMP519 Web Programming Lecture 19 Slide L19 – 18


Control Structures Conditional Statements

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 ;
}

• Note: If expr is a complex expression it is better to assign it to


a variable first
COMP519 Web Programming Lecture 19 Slide L19 – 19
Control Structures While-loops

While-loops
Python offers while-loops but has no do while-loops
while condition :
suite
else :
suite

• The break command can also be used in a while-loop and discontinues


the execution of the loop
• The continue command can be used to stop the execution of the
current iteration of a loop and to move to the next iteration
• A while-loop can have an optional else-clause that is executed if the
loop is not terminated by a break, exception, or error
• None of the suite blocks can be empty

COMP519 Web Programming Lecture 19 Slide L19 – 20


Control Structures While-loops

While-loops

• A while-loop can have an else-clause that is executed if the loop is not


terminated by break, exception or error
Example:
while value < 3:
if value == 0:
print (" Break ")
break
print ( value )
value += 1
else :
print (" Loop stopped with " + str ( value ))
print (" Statement after Loop ")
Output for value = 1 Output for value = 0
1 Break
2 Statement after Loop
Loop stopped with 3
Statement after Loop
COMP519 Web Programming Lecture 19 Slide L19 – 21
Further Reading

Revision and Further Reading


Read
• Chapter 26: The Python Language: Control Structures
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

COMP519 Web Programming Lecture 19 Slide L19 – 22


COMP519 Web Programming
Lecture 20: Python (Part 4)
Handouts

Ullrich Hustadt

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents

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

COMP519 Web Programming Lecture 20 Slide L20 – 1


Control Structures For-loops

For-loops
for-loops in Python take the form
for var1 ,... , varN in sequence :
suite
else :
suite

• var1, . . . , varN are variables


• sequence is a sequence (list, range, tuple)
• The loop iterates over the elements of sequence
• In each iteration an element E of sequence is assigned to
var1, . . . , varN: var1, ..., varN = E
; if there is more than one variable, then E must itself be
a sequence with a matching number of elements
• The optional else-clause is executed after the last iteration of the loop
unless the loop is left via a break, exception, or error
COMP519 Web Programming Lecture 20 Slide L20 – 2
Control Structures For-loops

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

COMP519 Web Programming Lecture 20 Slide L20 – 3


Control Structures For-loops

For-loops
Example: Iteration over a list
oldnames = [" Dave Jackson " , " Ullrich Hustadt "]
newnames = []

for name in oldnames :


nameParts = name . split (" ")
newnames . append ( nameParts [1] + " , "+ nameParts [0])

print ( newnames )
[ ’ Jackson , Dave ’ , ’ Hustadt , Ullrich ’]

Example: Iteration over a string


for letter in ’Jim ’:
print ( letter , letter . upper ())
J J
i I
m M

COMP519 Web Programming Lecture 20 Slide L20 – 4


Control Structures For-loops

Break and Continue

• The break command be used in while- and for-loops and discontinues


the execution of the loop
while value < 100:
if value == 0:
break ;
value += 1

• The continue command stops the execution of the current iteration of a


loop and moves the execution to the next iteration
for x in range ( -2 ,+2 ,1):
if x == 0:
continue
print ("10 / " + str ( x ) + " = " + str (10/ x ))
10 / -2 = -5
10 / -1 = -10
10 / 1 = 10
10 / 2 = 5

COMP519 Web Programming Lecture 20 Slide L20 – 5


Control Structures Try Statements

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

COMP519 Web Programming Lecture 20 Slide L20 – 6


Control Structures Try Statements

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

Else Clause Revisited


The example below illustrates the usefulness of else-clauses
in loop constructs:
for x in data :
if acceptable ( x ):
break
else :
raise ValueError (" No acceptable value found ")
# Computation with x continues here

COMP519 Web Programming Lecture 20 Slide L20 – 8


Functions Defining a Function

Defining a Function
Functions are elements of type function and can be defined as follows:
def identifier ( param1 , param2 , ...):
docstring
suite

• The function name identifier is case-sensitive


• The function name must be followed by parentheses
• A function has zero, one, or more parameters that are variables
• Parameters are not typed
• Parameters can be given default values param1 = value
• Parameter of the form *param1 and **param1 can take
a variable number of arguments
• docstring is a string describing the function and will be returned by
help(identifier) or identifier.__doc__
• suite is a non-empty sequence of statements
COMP519 Web Programming Lecture 20 Slide L20 – 9
Functions Defining a Function

Defining a Function
Functions are elements of type function and can be defined as follows:
def identifier ( param1 , param2 , ...):
suite

• The return statement


return value
can be used to terminate the execution of a function and to make the
optional value the return value of the function
• The return value does not have to be of a primitive type
• A function can contain more than one return statement
• Different return statements can return values of different types
; there is no return type for a function
• If the executation of a function
• ends without encountering a return statement or
• ends with a return statement without value
then the function returns the value None
COMP519 Web Programming Lecture 20 Slide L20 – 10
Functions Calling a Function

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

... identifier ( arg1 , arg2 ,...) ... # Function call


• Arguments are passed by assignment
param1 = arg1, param2 = arg2 ...
• The number of arguments has to match the number of parameters
(excluding * and ** parameters)
; too many or too few arguments result in TypeError
def exp ( base , exp ):
return base ** exp

exp (2 ,3) # returns 8


exp (2 ,3 ,1) # TypeError
exp (2) # TypeError
COMP519 Web Programming Lecture 20 Slide L20 – 11
Functions Calling a Function

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

... identifier ( arg1 , arg2 ,...) ... # Function call


• Arguments can be specified as keyword arguments param=value ,
where param matches one of the parameters in the function definition
; having good parameter names pays off
• The order of keyword arguments is irrelevant
; makes modifications easier
def exp ( base , exp ):
return base ** exp

exp (2 ,3) # returns 8


exp ( base =2 , exp =3) # returns 8
exp ( exp =3 , base =2) # returns 8
COMP519 Web Programming Lecture 20 Slide L20 – 12
Functions Variable-length Argument Lists

Variable-length Argument Lists


def identifier ( param1 , param2 , ...):
suite

• For a parameter *param1, param1 is initialised to a tuple receiving any


excess positional parameters, defaulting to the empty tuple

def sumAll (* args ): # no minimum number of arguments


sum = 0
for val in args :
sum = sum + val
return sum

sumAll () # returns 0
sumAll (5) # returns 5
sumAll (5 ,4 ,3) # returns 12

COMP519 Web Programming Lecture 20 Slide L20 – 13


Functions Variable-length Argument Lists

Variable-length Argument Lists


def identifier ( param1 , param2 , ...):
suite

• For a parameter **param2, param2 is initialised to a dictionary mapping


any excess keyword arguments, defaulting to an empty dictionary
def printFile ( file ,** kwargs ): # at least one arguments
if ’ duplex ’ in kwargs and kwargs [ ’ duplex ’]:
print ( ’ Duplex option enabled ’)
if ’ orientation ’ in kwargs and \
kwargs [ ’ orientation ’] == ’ landscape ’:
print ( ’ Landscape option enabled ’)
if ’ orientation ’ in kwargs and \
kwargs [ ’ orientation ’] == ’ portrait ’:
print ( ’ Portrait option enabled ’)
print ( ’ Printing ’ , file )
printFile(’python1.py’) – No option enabled
printFile(’python1.py’,orientation=’landscape’) – Landscape option enabled
printFile(’python1.py’,duplex=’True’) – Duplex option enabled
printFile(’python1.py’,orientation=’landscape’, – Both Landscape and
duplex=’True’) Duplex option enabled
COMP519 Web Programming Lecture 20 Slide L20 – 14
Functions Variable-length Argument Lists

Variable-length Argument Lists


• When mixing ordinary parameters / arguments, keyword arguments and
variable-length argument lists, parameters and arguments need to occur
in a particular order to work correctly
• In a function definition we have
1 ‘Normal’ parameters
2 *param1
3 **param2

def applyFunc ( func , resultFormat ,* arg ,** kwargs ):

• In a function call we have


1 ‘Normal’ (positional) arguments
2 Keyword arguments
applyFunc ( lambda x : 2* x , ’ list ’ ,1 ,2 ,3 , debug = True )

COMP519 Web Programming Lecture 20 Slide L20 – 15


Functions Static Variables

JavaScript Functions and Static Variables


• Python does not have a static keyword to declare a variable to be
static and preserve its value between different calls of a function
• A solution is to use a function attribute instead
def counter ():
try :
counter . count += 1
except AttributeError :
counter . count = 1
return counter . count

print ("1: static count = " , counter ())


print ("2: static count = " , counter ())
print ("3: global counter . count = " , counter . count )
1: static count = 1
2: static count = 2
3: global counter . count = 2

• As the example shows the function property is public


COMP519 Web Programming Lecture 20 Slide L20 – 16
Functions Nested Function Definitions

Nested Function Definitions


• Function definitions can be nested in Python
• By default, inner functions can not be invoked from outside
the function they are defined in
def bubble_sort ( arr ):
def swap (i , j ):
tmp = arr [ i ]
arr [ i ] = arr [ j ]
arr [ j ] = tmp

if not ( isinstance ( arr , list )):


raise TypeError (" bubble_sort argument must be a list ")
for i in range (0 , len ( arr ) -1):
for j in range (0 , len ( arr ) -i -1):
if arr [ j +1] < arr [ j ]:
swap (j , j +1)
return arr

COMP519 Web Programming Lecture 20 Slide L20 – 17


Further Reading

Revision and Further Reading


Read
• Chapter 26: The Python Language: User-Defined Functions
• Chapter 26: The Python Language: Python Errors and Exception
Handling
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

COMP519 Web Programming Lecture 20 Slide L20 – 18


COMP519 Web Programming
Lecture 21: Python (Part 5)
Handouts

Ullrich Hustadt

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents

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

COMP519 Web Programming Lecture 21 Slide L21 – 1


Functions Variable Scope and Functions

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)

Where in this Java class can we validly refer


public class Test {
int x ; to the variables x, y and z, for example, print
void method1 () { them out?
... Code A ... • Can we refer to x, y, and z in method2()?
int x ;
int y ; Which occurrence of x do we refer to?
... Code B ... • Which occurrence of x would we refer to in
}
method1() either in Code ...A... or
void method2 () {
... Code C ... ...B...?
} Such questions become even more complicated
int z ; when function definitions can be nested as in
}
JavaScript and Python
COMP519 Web Programming Lecture 21 Slide L21 – 2
Functions Variable Scope and Functions

A Look Back to JavaScript

function state (s ,a ,k ,b ,l ,c , m ) { Main(1):


document . writeln ( s + ’: ’+ a + ’= ’+ k + ’ , ’+ u=1, v=2, w=[0,1,2]
b + ’= ’+ l + ’ , ’+ c + ’=[ ’+ m + ’] < br > ’)
} Outer(1):
x=1, y=2, z=[0,1,2]
function outer (x ,y , z ) {
function inner () { Inner(1):
state ( ’ Inner (1) ’ , ’x ’ ,x , ’y ’ ,y , ’z ’ , z ) x=1, y=2, z=[0,1,2]
x = 3
z [1] = 3 Inner(2):
state ( ’ Inner (2) ’ , ’x ’ ,x , ’y ’ ,y , ’z ’ , z ) x=3, y=2, z=[0,3,2]
}
state ( ’ Outer (1) ’ , ’x ’ ,x , ’y ’ ,y , ’z ’ , z ) Outer(2):
inner () x=3, y=4, z=[0,3,4]
y = 4
z [2] = 4 Main(2):
state ( ’ Outer (2) ’ , ’x ’ ,x , ’y ’ ,y , ’z ’ , z ) u=1, v=2, w=[0,3,4]
}
u = 1; v = 2; w = [0 ,1 ,2] x, y, z are local variables of outer
state ( ’ Main (1) ’ , ’u ’ ,u , ’v ’ ,v , ’w ’ , w ) x, y, z in inner are those of outer
outer (u ,v , w ) x, y, z are accessible in inner
state ( ’ Main (2) ’ , ’u ’ ,u , ’v ’ ,v , ’w ’ , w )
COMP519 Web Programming Lecture 21 Slide L21 – 3
Functions Variable Scope and Functions

Variable Scope in Python: Example

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

COMP519 Web Programming Lecture 21 Slide L21 – 4


Functions Variable Scope and Functions

Variable Scope in Python: Analysis


• By default, any assignment to a variable within a function
creates a new local variable
def outer (x ,y , z ):
def inner ():
x = 3 # x is a new local variable
• Not all statements that look like assignments are assignments
def bubble_sort ( arr ):
def swap (i , j ):
arr [ i ] = tmp # why is arr not a new local variable ?
is syntactic sugar for
def bubble_sort ( arr ):
def swap (i , j ):
arr . __setitem__ (i , tmp )
that is, the ‘assignment’ is a method call for the object arr
; arr[i] = tmp does not result in the creation of
a new local variable arr
COMP519 Web Programming Lecture 21 Slide L21 – 5
Functions Variable Scope and Functions

Variable Scope in Python

• A variable that is a function parameter or defined inside a function


is local to that function
; the variable (only) exists as long as a function execution does
; the variable can only be accessed inside the function
• A variable that is outside any function (or class) is global
; the variable can be accessed anywhere if is not hidden
by a local variable with the same name
• The declaration
global var1 , var2 , ...
causes the listed variables to be interpreted as global variables
• The declaration
nonlocal var1 , var2 , ...
causes the listed variables to refer to previously bound variables in the
nearest enclosing scope excluding globals
COMP519 Web Programming Lecture 21 Slide L21 – 6
Functions Variable Scope and Functions

Global vs Local Variables in Python

def state (s ,a ,k ,b ,l ,c , m ): Main(1):


print ( s + ’: ’+ a + ’= ’+ str ( k )+ ’ , ’+ u=1, v=2, w=[0,1,2]
b + ’= ’+ str ( l )+ ’ , ’+ c + ’= ’+ str ( m ))
Outer(1):
def outer (x ,y , z ): x=1, y=2, z=[0,1,2]
def inner ():
nonlocal x Inner(1):
state ( ’ Inner (1) ’ , ’x ’ ,x , ’y ’ ,y , ’z ’ , z ) x=1, y=2, z=[0,1,2]
x = 3
z [1] = 3 Inner(2):
state ( ’ Inner (2) ’ , ’x ’ ,x , ’y ’ ,y , ’z ’ , z ) x=3, y=2, z=[0, 3, 2]
state ( ’ Outer (1) ’ , ’x ’ ,x , ’y ’ ,y , ’z ’ , z )
inner () Outer(2):
y = 4 x=3, y=4, z=[0, 3, 4]
z [2] = 4
state ( ’ Outer (2) ’ , ’x ’ ,x , ’y ’ ,y , ’z ’ , z ) Main(2):
u=1, v=2, w=[0, 3, 4]
u , v , w = 1 , 2 , [0 ,1 ,2]
state ( ’ Main (1) ’ , ’u ’ ,u , ’v ’ ,v , ’w ’ , w ) x in inner is now 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

COMP519 Web Programming Lecture 21 Slide L21 – 7


Functions Static Variables

Python Functions and Static Variables

• Python does not have a static keyword to declare a variable to be


static and preserve its value between different calls of a function
• The solution is to use a function attribute instead
def counter ():
try :
counter . count += 1
except AttributeError :
counter . count = 1
return counter . count

print ("1: static count =" , counter ())


print ("2: static count =" , counter ())
print ("3: global counter . count = "+ counter . count )
1: static count = 1
2: static count = 2
3: global counter . count = 2

• As the example shows the function attribute is global/public


COMP519 Web Programming Lecture 21 Slide L21 – 8
Functions Static Variables

Anonymous Functions
Python supports a weak form of anonymous functions:
lambda param1 , param2 , ...: expression

• Parameters work as for named functions


• The return value of an anonymous function is the value of expression

lambda x , y : x ** y if y > 0 else x **(1/ y )

• Both named and anonymous functions can be assigned to variables:


def exp ( base , exp ):
return base ** exp
func1 = exp
func2 = lambda x : 2* x
print ( func1 (2 ,2) + func2 (3)) # prints 10

• Both named and anonymous functions can be passed to other functions


as arguments or used as values in complex data structures
COMP519 Web Programming Lecture 21 Slide L21 – 9
Classes Defining and Instantiating a Class

Defining and Instantiating a Class

• Python is an object-oriented language with classes


• A class can be defined as follows:
class identifier :
docstring
suite

• The class name identifier is case-sensitive


• docstring is a string describing the class and will be returned by
help(identifier) or identifier.__doc__
• suite is a non-empty sequence of statements, typically defining attributes
and methods
• An object of a class is created using
identifier ( arg1 , arg2 ,...)

where arg1,arg2,... is a possibly empty list of arguments passed to


the constructor of the class identifier
COMP519 Web Programming Lecture 21 Slide L21 – 10
Classes Defining and Instantiating a Class

A Closer Look at Class Definitions


In more detail, the definition of a class • Every instance obj of this
typically looks as follows class will have an attribute
class id : iAttrib accessible as
docstring obj.iAttrib
# Class Attributes
cAttrib = value1 • cAttrib is a class attribute
accessible as id.cAttrib or
# Constructor obj.cAttrib
def __init__ ( self , p1 , p2 ,...):
# Instance Attribute • __init__ is the constructor
self . iAttrib = value2 of the class and will be called
suite1 whenever id(a1,a2,...)
is executed
# Methods
def method2 ( self , p1 , p2 ,...): • Via self the constructor
suite2 receives a reference to the
newly created object
def methodN ( self , p1 , p2 ,...): • p1,p2,... will be
suiteN
instantiated by a1,a2,...
COMP519 Web Programming Lecture 21 Slide L21 – 11
Classes Defining and Instantiating a Class

A Closer Look at Class Definitions


In more detail, the definition of a class
typically looks as follows • Every instance obj of this
class id : class will have methods
docstring method2 to methodN
# Class Attributes
cAttrib = value1 • For an instance obj of this
class, method calls will take
# Constructor the form
def __init__ ( self , p1 , p2 ,...): obj.method2(a1,a2,...) to
# Instance Attribute obj.methodN(a1,a2,...)
self . iAttrib = value2 • p1,p2,... will be
suite1
instantiated by a1,a2,... in
# Methods the normal way for function
def method2 ( self , p1 , p2 ,...): calls
suite2 • Via self each method
receives a reference to obj as
def methodN ( self , p1 , p2 ,...): additional argument
suiteN
COMP519 Web Programming Lecture 21 Slide L21 – 12
Classes Defining and Instantiating a Class

Defining and Instantiating a Class: Example

class Rectangle :
""" A simple rectangle class """
type = ’ Rectangle ’

def __init__ ( self , width =0 , height =0):


self . width = width
self . height = height

def area ( self ):


return self . height * self . width
# Using the class
r1 = Rectangle ()
print ( ’ Area of r1 : ’ , r1 . area ()) Area of r1 : 0
r2 = Rectangle (5 ,2)
print ( ’ Area of r2 : ’ , r2 . area ()) Area of r2 : 10
r3 = Rectangle ( width =5 , height =2)
print ( ’ Area of r3 : ’ , r3 . area ()) Area of r3 : 10

COMP519 Web Programming Lecture 21 Slide L21 – 13


Classes Class and Instance Attributes

Class and Instance Attributes

• 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

r1 . colour = " blue "


r1 . type = " Point "
print ( r1 . __dict__ )
{ ’ width ’: 0 , ’ height ’: 0 , ’ colour ’: ’ blue ’ , ’ type ’: ’ Point ’}
COMP519 Web Programming Lecture 21 Slide L21 – 14
Classes Class and Instance Attributes

‘Private’ Attributes

• Python has no private class or instance attributes


• By convention, an attribute whose name starts with a double underscore
should be ‘considered’ private
• Python supports this convention by name mangling:
Within the definition of a class id an attribute __attrib is textually
replaced by _id__attrib
class Hide : h1 = Hide ()
print (" Class : " , Hide . __dict__ )
__cHide = 1 print (" Instance :" , h1 . __dict__ )
print (" Value of __iHide for h1 :" ,
def __init__ ( self ): h1 . _Hide__iHide )
self . __iHide = 2 print ( h1 . __iHide )
Class : { ’ _Hide__cHide ’: 1 , ’ __init__ ’: ... }
Instance : { ’ _Hide__iHide ’: 2}
Value of __iHide for h1 : 2
AttributeError : ’ Hide ’ object has no attribute ’ __iHide ’
COMP519 Web Programming Lecture 21 Slide L21 – 15
Classes Class and Instance Attributes

‘Private’ Attributes: Example


class Mapping :
def __init__ ( self , iterable ):
self . items_list = []
self . __update ( iterable )

def update ( self , iterable ):


for item in iterable :
self . items_list . append ( item )

__update = update # private copy of original update ()

class MappingSubclass ( Mapping ):


def update ( self , keys , values ):
# provides a new signature and definition for update ()
# but does not break __init__ () in Mapping
for item in zip ( keys , values ):
self . items_list . append ( item )
Section 9.6. Private Variables (https://docs.python.org/3/tutorial/classes.html#private-variables)
of Python Software Foundation: The Python Tutorial. Python Software Foundation, 21 December 2017.
https://docs.python.org/3/tutorial/ [accessed 21 December 2017]

COMP519 Web Programming Lecture 21 Slide L21 – 16


Classes Deleting Instances

Deleting Instances

• An instance obj can be deleted using


del obj
• Deleting an instance will implicitly call the method __del__

class Employee : e1 = Employee (" Ada ")


e2 = Employee (" Ben ")
totalNumber = 0; print (" A : # employees : " ,
Employee . totalNumber )
def __init__ ( self , name ): del e1
self . name = name print (" B : # employees : " ,
type ( self ). totalNumber += 1 Employee . totalNumber )
e2 = None
def __del__ ( self ): print (" C : # employees : " ,
type ( self ). totalNumber -= 1 Employee . totalNumber )
A : # employees : 2
B : # employees : 1
C : # employees : 0
COMP519 Web Programming Lecture 21 Slide L21 – 17
Classes Class Methods

Static Methods (Class Methods)


• The Pythonic way is to define getter
class Employee :
and setter method only for ‘private’ __tNum = 0;
class and instance attributes
• For ‘private’ instance variables this is def __init__ ( self , name ):
self . __name = name
done in the standard way type ( self ). __tNum += 1
• For ‘private’ class variables we need
to declare the getter / setter method def __del__ ( self ):
type ( self ). __tNum -= 1
to be static
def getName ( self ):
e3 = Employee (" Ada ") return self . __name
e4 = Employee (" Ben ")
print (" Number of employees : " , def setName ( self , name ):
Employee . getNumber ()) self . __name = name
print (" Number of employees : " ,
e3 . getNumber ()) @staticmethod
Number of employees : 2 def getNumber ():
Number of employees : 2 return Employee . __tNum
COMP519 Web Programming Lecture 21 Slide L21 – 18
Classes Class Methods

Static Methods (Class Methods)

• A static declaration should also be used for methods that are


independant of specific instances
class Circle : c1 = Circle (1.2)
PI = 3.14159265359 c2 = Circle (1.0)

def __init__ ( self , radius ): print (" c1 radius :" , c1 . r )


self . r = radius print (" c1 area : " , c1 . area ())
print (" c2 radius :" , c2 . r )
def area ( self ): print (" c2 area : " , c2 . area ())
return round ( Circle . PI * \
self . r * self .r ,5) bg = Circle . max ( c1 , c2 )
print (" bg radius :" , bg . r )
@staticmethod
def max ( cx , cy ): c1 radius : 1.2
if cx . r > cy . r : c1 area : 4.52389
return cx c2 radius : 1.0
else : c2 area : 3.14159
return cy bg radius : 1.2
COMP519 Web Programming Lecture 21 Slide L21 – 19
Classes Inheritance

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 ’

def __init__ ( self , width =0 , height =0):


self . width = width sq1 = Square (5)
self . height = height print (" The type of sq1 is " ,
sq1 . type )
def area ( self ): print (" The area of sq1 is " ,
return self . height * self . width sq1 . area () )
The type of sq1 is Square
class Square ( Rectangle ): The area of sq1 is 25
type = ’ Square ’
def __init__ ( self , size ):
super (). __init__ ( size , size )
COMP519 Web Programming Lecture 21 Slide L21 – 20
Classes Magic Methods

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

Magic Methods: Index Operators

• 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 ]

building1 = Building (3)


building1 [0] = ’ Reception ’
building1 [1] = ’ ABC Corp ’
building1 [2] = ’ DEF Ltd ’
print ( building1 [2] ) # prints ’ DEF Ltd ’
COMP519 Web Programming Lecture 21 Slide L21 – 22
Classes Magic Methods

Magic Methods: Iterators

• A for-loop starts by calling the __iter__() on an object to obtain an


iterator object
• At each iteration (including the first), a for-loop calls the __next__()
method on the iterator object to get the next item
• If __next__() raises the exception StopIteration, the for-loop stops
class PowTwo :
def __next__ ( self ):
def __init__ ( self , max = 0): if self . n <= self . max :
self . max = max result = 2 ** self . n
self . n += 1
def __iter__ ( self ): return result
self . n = 0 else :
return self raise StopIteration
for x in PowTwo (2):
print ( x )
1 # 2 ** 0
2 # 2 ** 1
4 # 2 ** 2
COMP519 Web Programming Lecture 21 Slide L21 – 23
Further Reading

Revision and Further Reading

• 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

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents

67 Regular Expressions and Regular Expression Search


Motivation
The re module
Characters
Character Classes

68 Further Reading

COMP519 Web Programming Lecture 22 Slide L22 – 1


Regular Expressions and Regular Expression Search Motivation

Regular Expressions

• Many programming languages support the use of regular expressions


either
• as a built-in part of the language (Perl, JavaScript), or
• through a standard library (Java, C++, Python)

• Regular expressions are either used


• to check for the presence of an instance of a particular pattern in a text, or
• to extract instances of a particular pattern in a text, or
• to modify instances of a particular pattern in a text

COMP519 Web Programming Lecture 22 Slide L22 – 2


Regular Expressions and Regular Expression Search Motivation

Regular expressions: Motivation


Suppose you are testing the performance of a new sorting algorithm by
measuring its runtime on randomly generated arrays of numbers
of a given length:
Generating an unsorted array with 10000 elements took 1.250 seconds
Sorting took 7.220 seconds
Generating an unsorted array with 10000 elements took 1.243 seconds
Sorting took 10.486 seconds
Generating an unsorted array with 10000 elements took 1.216 seconds
Sorting took 8.951 seconds

Your task is to write a program that determines the average runtime of


the sorting algorithm:
Average runtime for 10000 elements is 8.886 seconds

Solution: The regular expression "Sorting took (\d+\.\d+) seconds"


allows us to get the required information
; Regular expressions are useful for information extraction
COMP519 Web Programming Lecture 22 Slide L22 – 3
Regular Expressions and Regular Expression Search Motivation

Regular expressions: Motivation


Suppose you have recently taken over responsibility for a company’s
website. You note that their HTML files contain a large number of
URLs containing superfluous occurrences of ‘..’, e.g.
http://www.myorg.co.uk/info/refund/../vat.html

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

while making sure that URLs like


http://www.myorg.co.uk/../video/help.html
../video/help.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

Regular Expressions: Introductory Example


Python’s syntax for regular expressions is based on that of Perl
\ Ahttps ?:\/\/[^\/]+\/.\ w .\/( cat | dog )\/\1

• \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

COMP519 Web Programming Lecture 22 Slide L22 – 5


Regular Expressions and Regular Expression Search The re module

The re module

• The re module of Python provides functions that use regular expressions

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

re.findall(regexp, string, flags)


returns a sequence of strings for all non-overlapping matches
for regexp in string
re.findall(r’[mM][rs]’,"Mr and Ms Dobbs")
# returns (’Mr’,’Ms’)
re.split(regexp, string, maxsplit, flags)
returns a list of split components of string wrt regexp
– optional argument maxsplit is the maximum number of splits
that will be performed
re.split(r’\W+’,’Deeds, not (words) non-negative’)
# returns [’Deeds’, ’not’, ’words’, ’non’, ’negative’]
re.split(r’\W+’,’Deeds, not (words) non-negative’,2)
# returns [’Deeds’, ’not’, ’words) non-negative’]

COMP519 Web Programming Lecture 22 Slide L22 – 7


Regular Expressions and Regular Expression Search The re module

The re module
• The re module of Python provides functions that use regular expressions

re.sub(regexp, repl, string, count, flags)


returns the string obtained by replacing the leftmost non-overlapping
occurrences of regexp in string by repl
– repl can be a string or a function; if it is a string,
any backslash escapes in it are processed
– optional argument count is the maximum number of regexp
occurrences to be replaced (default: all)
re.sub(r’\s+’,r’ ’,’Mr and Ms Dobbs’)
# returns ’Mr and Ms Dobbs’

COMP519 Web Programming Lecture 22 Slide L22 – 8


Regular Expressions and Regular Expression Search The re module

Regular Expression Objects


• Regular expressions are compiled before they are used, normally,
when a function using a regular expression is executed
• It is possible to pre-compile a regular expression using
reObj = re . compile ( regexp )
which return a regular expression object
• These regular expression objects cannot take the place of
regular expression strings
• Instead the regular expression objects themselves support the
following methods:
reObj.match(string,flags)
reObj.search(string,flags)
reObj.findall(string,flags)
reObj.finditer(string,flags)
reObj.split(string,maxsplit,flags)
reObj.sub(string,count,flags)
COMP519 Web Programming Lecture 22 Slide L22 – 9
Regular Expressions and Regular Expression Search Characters

Regular expressions: Characters


The simplest regular expression just consists of a sequence of
• alphanumberic characters and
• non-alphanumeric characters escaped by a backslash:
that matches exactly this sequence of characters occurring as a substring
in the target string

if re . search (r ’ cbc ’ ," ababcbcdcde "):


print (" Match ")
else :
print (" No match ")
Match

if re . search (r ’ dbd ’ ," ababcbcdcde "):


print (" Match ")
else :
print (" No match ")
No match
COMP519 Web Programming Lecture 22 Slide L22 – 10
Regular Expressions and Regular Expression Search Characters

Match Objects: Basics


• Detailed information about a match is provided by the match object
mObj returned by operations such as re.search:
mObj.group(0): the substring matched
mObj[0]: the substring matched
mObj.start(0): the index position at which the match starts
mObj.end(0): the index position after which the match ends
mObj.span(0): start and end index as a tuple
mObj.re: regular expression that was matched
mObj.string: the target string

# 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

COMP519 Web Programming Lecture 22 Slide L22 – 11


Regular Expressions and Regular Expression Search Characters

Regular Expressions: Special Escapes


There are various special escapes and metacharacters that match more
then one character:

. Matches any character except \n


\w Matches a ‘word’ character (alphanumeric
plus ‘_’, plus other connector punctuation
characters plus Unicode characters
\W Matches a non-‘word’ character
\s Matches a whitespace character
\S Matches a non-whitespace character
\d Matches a decimal digit character
\D Matches a non-digit character
\uhex Matches corresponding unicode character

COMP519 Web Programming Lecture 22 Slide L22 – 12


Regular Expressions and Regular Expression Search Character Classes

Regular Expressions: Character Class

• A character class, a list of characters, special escapes, and


metacharacters enclosed in square brackets,
matches any single character from within the class,
for example, [ad\t\n\-\\09]
• One may specify a range of characters with a hyphen -,
for example, [b-u]
• A caret ^ at the start of a character class negates/complements it,
that is, it matches any single character that is not from within the class,
for example, [^01a-z]

# 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

Revision and Further Reading


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

COMP519 Web Programming Lecture 22 Slide L22 – 14


COMP519 Web Programming
Lecture 23: Python (Part 7)
Handouts

Ullrich Hustadt

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents

69 Regular Expressions and Regular Expression Search


Quantifiers
Capture Groups
Alternations
Anchors
Flags and Inline Flags
70 Regular Expression Split
71 Regular Expression Substitution
Substitution Operators
Capture Groups
Flags and Inline Flags
Functions as Replacement
72 Revision and Further Reading

COMP519 Web Programming Lecture 23 Slide L23 – 1


Regular Expressions and Regular Expression Search Quantifiers

Regular Expressions: Quantifiers

• 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

Regular Expressions: 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

m = re . search (r ’\ d +\.\ d + ’ ," Sorting took 10.486 seconds ")


if m :
print (" Match at indices " , m . start (0) ,\
" to " , m . end (0) -1 ,":" , m . group (0))
m = re . search (r ’[ A - Z ]0{2}\ d + ’ ," E00481370 ")
if m :
print (" Match at indices " , m . start (0) ,\
" to " , m . end (0) -1 ,":" , m . group (0))
Match at indices 13 to 18 : 10.486
Match at indices 0 to 8 : E00481370
COMP519 Web Programming Lecture 23 Slide L23 – 3
Regular Expressions and Regular Expression Search Quantifiers

Regular Expressions: Quantifiers


m = re . search (r ’ a .+ e ’ ," aabcdeabcdeabcd ")
if m :
print (" Match at indices " , m . start (0) ,\
" to " , m . end (0) -1 ,":" , m . group (0))
Match at indices 0 to 10 : aabcdeabcde

• The regular expression .+ matches 1 or more characters


• As the example illustrates, it matches as many characters as possible
; quantifiers are greedy by default
• Note that the regular expression also matches as early as possible
• What if we wanted to match as few characters as possible?

COMP519 Web Programming Lecture 23 Slide L23 – 4


Regular Expressions and Regular Expression Search Quantifiers

Regular Expressions: Non-greedy Quantifiers


For every greedy quantifier there is a non-greedy quantifier that is
obtained by adding the quantifier ? to it:
regexp*? Match regexp 0 or more times
regexp+? Match regexp 1 or more times
regexp?? Match regexp 1 or 0 times as few 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

m = re . search (r ’ a .+? e ’ ," aabcdeabcdeabcd ")


if m :
print (" Match at indices " , m . start (0) ,\
" to " , m . end (0) -1 ,":" , m . group (0))
Match at indices 0 to 5 : aabcde

COMP519 Web Programming Lecture 23 Slide L23 – 5


Regular Expressions and Regular Expression Search Capture Groups

Regular Expressions: Capture Groups and Backreferences

• We often encounter situations where we want to identify the repetition


of the same or similar text, for example, in HTML markup:
< code > ... < strong > ... </ strong > ... </ code >
<em > ... </ em >
• We might also not just be interested in the repeating text itself,
but the text between or outside the repetition
• We can characterise each individual example above
using regular expressions:
r ’ < code >.* </ code > ’
r ’ < em >.* </ em > ’
but we cannot characterise both without losing fidelity, for example:
r ’ <\ w + >.* </\ w + > ’
does not capture the ‘pairing’ of HTML tags
COMP519 Web Programming Lecture 23 Slide L23 – 6
Regular Expressions and Regular Expression Search Capture Groups

Regular Expressions: Capture Groups


The solution are capture groups and backreferences
(regexp) creates a capture group
(?P<name>regexp) creates a named capture group
(?:regexp) creates a non-capturing group
\N backreference to capture group N
(where N is a natural number 1 ≤ N ≤ 9)
(?P=name) backreference to a named capture group
r ’ Sorting took (\ d +\.\ d +) seconds ’
r ’([ A - Z ])0{2}(\ d +) ’

r ’(? P <A >\ w )(? P <B >\ w )(? P = B )(? P = A ) ’


r ’((? P <A >\ w )(? P <B >\ w )\3\2) ’
# || |
# 12 3
r ’ <(\ w +) >.* </\1 > ’
# |
# 1
COMP519 Web Programming Lecture 23 Slide L23 – 7
Regular Expressions and Regular Expression Search Capture Groups

Match Objects: Accessing Capture Groups


• A match object mObj contains information about each capture group:
mObj.group(N): the substring matched by capture group N
(where N is a natural number 1 ≤ N ≤ 99)
mObj[N]: the substring matched by capture group N
mObj.start(N): the index position at which the match for
capture group N starts
mObj.end(N): the index position after which the match for
capture group N ends
mObj.span(N): start and end index for capture group N
as a tuple
mObj.group(’name’): the substring matched by the capture group
with name name
mObj[’name’]: analogous (since Python 3.6)
mObj.start[’name’]: analogous (since Python 3.6)
mObj.end[’name’]: analogous (since Python 3.6)
mObj.span[’name’]: analogous (since Python 3.6)
COMP519 Web Programming Lecture 23 Slide L23 – 8
Regular Expressions and Regular Expression Search Capture Groups

Match Objects: Accessing Capture Groups

• A match object mObj contains information about each capture group:


mObj.group(N): the substring matched by capture group N
(where N is a natural number 1 ≤ N ≤ 99)
mObj.group(’name’): the substring matched by the capture group
with name name

# Example using names for capture groups


#
r = r ’(? P <A >\ w )(? P <B >\ w )(? P = B )(? P = A ) ’
m = re . search (r ," Yabba dabba doo ")
if m :
print (" Capture Group 0:" , m [0] ," at " , m . span (0))
print (" Capture Group 1:" , m [1] ," aka Group A :" , m [ ’A ’])
print (" Capture Group 2:" , m [2] ," aka Group B :" , m [ ’B ’])
Capture Group 0: abba at (1 ,5)
Capture Group 1: a aka Group A : a
Capture Group 2: b aka Group B : b

COMP519 Web Programming Lecture 23 Slide L23 – 9


Regular Expressions and Regular Expression Search Capture Groups

Match Objects: Accessing Capture Groups


• A match object mObj contains information about each capture group:
mObj.groups(): a tuple containing all the substrings matched
by the capture groups
mObj.groupdict(): a dictionary contained all the substrings matched
by named captures groups using their names
as keys
# Example using both names and numbers for capture groups
#
r = r ’(? P <A >\ w )(? P <B >\ w )(\ w )\3(? P = B )(? P = A ) ’
m = re . search (r ," Yabba dabbad doo ")
if m :
print (" Groups :" , m . groups ())
print (" Dict : " , m . groupdict ())
for i in range (1 , len ( m . groups ())+1):
print (" Group " ,i ,": " , m [ i ] , sep ="" , end ="\ t ")
Groups : ( ’d ’ , ’a ’ , ’b ’)
Dict : { ’A ’: ’d ’ , ’B ’: ’a ’}
Group 1: d Group 2: a Group 3: b
COMP519 Web Programming Lecture 23 Slide L23 – 10
Regular Expressions and Regular Expression Search Capture Groups

Capture Groups: Examples

string = " firefox : 10.3 seconds ; chrome : 9.5 seconds ";


dict = { m . group (1): m . group (2) \
for m in re . finditer (r ’(\ w +)\:\ s +(\ d +\.\ d +) ’ , string )}
print ( dict )

{ ’ firefox ’: ’10.3 ’ , ’ chrome ’: ’9.5 ’}

# Convert a list of names given as strings


# into a list of dictionaries
# with keys ’ first ’ , ’ second ’ , ’ title ’
namesIn = [" Dr Ullrich Hustadt " , " Andrew Craig "]
ro = re . compile (r ’( Mr | Ms | Mrs | Dr )?\ s *(\ w +)\ s +(\ w +) ’)
namesOut = [{ ’ first ’: m . group (2) , ’ second ’: m . group (3) ,\
’ title ’: m . group (1)}\
for n in namesIn for m in [ ro . match ( n )] if m ]
print ( namesOut )

[{ ’ first ’: ’ Ullrich ’ , ’ second ’: ’ Hustadt ’ , ’ title ’: ’Dr ’} ,


{ ’ first ’: ’ Andrew ’ , ’ second ’: ’ Craig ’ , ’ title ’: None }]

COMP519 Web Programming Lecture 23 Slide L23 – 11


Regular Expressions and Regular Expression Search Alternations

Regular Expressions: Alternations


• The regular expression regexp1|regexp2 matches
if either regexp1 or regexp2 matches
This type of regular expression is called an alternation
• Within a larger regular expression we need to enclose alternations
in a capture group or non-capturing group:
(regexp1|regexp2) or (?:regexp1|regexp2)

r ’ cat | dog | bird ’


r ’(?: Bill | Hillary ) Clinton ’

COMP519 Web Programming Lecture 23 Slide L23 – 12


Regular Expressions and Regular Expression Search Alternations

Regular Expressions: Alternations


• The regular expression regexp1|regexp2 matches
if either regexp1 or regexp2 matches
This type of regular expression is called an alternation
• Within a larger regular expression we need to enclose alternations
in a capture group or non-capturing group:
(regexp1|regexp2) or (?:regexp1|regexp2)
list = [" Dr Ullrich Hustadt " ," Dave Shield "]
for name in list :
m = re . match (r ’( Mr | Ms | Mrs | Dr )?\ s *(\ w +) ’ , name )
if m : print (" Hello " , m . group (2))
for i in range (1 , len ( m . groups ())+1):
print (" Group " ,i ,": " , m [ i ] , sep ="" , end ="\ t ")
print ()
Hello Ullrich
Group 1: Dr Group 2: Ullrich
Hello Dave
Group 1: None Group 2: Dave
COMP519 Web Programming Lecture 23 Slide L23 – 13
Regular Expressions and Regular Expression Search Alternations

Regular Expressions: Alternations


• The order of expressions in an alternation only matters
if one expression matches a sub-expression of another
ts = "cats and dogs"

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

Regular Expressions: Anchors


Anchors allow us to fix where a match has to start or end
\A Match only at string start
^ Match only at string start (default)
Match only at a line start (with re.M)
\Z Match only at string end
$ Match only at string end modulo a preceding \n
Match only at a line end (with re.M)
\b Match word boundary (between \w and \W)
\B Match except at word boundary

target = " The girl who \ nplayed with fire \ n "


m = re . search (r ’ fire \Z ’ , target )
if m : print (" Match with \\ Z : ‘ fire ’ at string end ")
m = re . search (r ’ fire$ ’ , target )
if m : print (" Match with $ : ‘ fire ’ at string end modulo \\ n ")
Match with $ : ‘ fire ’ at string end modulo \ n

COMP519 Web Programming Lecture 23 Slide L23 – 15


Regular Expressions and Regular Expression Search Flags and Inline Flags

Regular Expressions: Flags and Inline Flags

• 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.S (?s) Make . match any character including newline


re . search (r ’ Adam .+ Eve ’ ," Adam \ nEve ") # None
re . search (r ’ Adam .+ Eve ’ ," Adam \ nEve " , re . S )[0] # " Adam \ nEve "
re . search (r ’(? s ) Adam .+ Eve ’ ," Adam \ nEve ")[0] # " Adam \ nEve "

COMP519 Web Programming Lecture 23 Slide L23 – 16


Regular Expressions and Regular Expression Search Flags and Inline Flags

Regular Expressions: Flags and Inline Flags

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 "

re.I (?i) Perform case-insensitive matching


re . search (r ’ Help \ sme ’ ," help Me ") # None
re . search (r ’ Help \ sme ’ ," help Me " , re . I )[0] # " help Me "
re . search (r ’(? i ) Help \ sme$ ’ ," help Me ")[0] # " help Me "

re.X Allows nicer layouts of and comments in regular expres-


sions
re . search (r ’ ’ ’\ d + # integral part
\. # decimal point
\d+ # fractional digits ’ ’ ’ ," $10 .12" , re . X )[0]
# returns 10.12
COMP519 Web Programming Lecture 23 Slide L23 – 17
Regular Expressions and Regular Expression Search Flags and Inline Flags

Regular Expressions: Flags and Inline Flags

• 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 "

COMP519 Web Programming Lecture 23 Slide L23 – 18


Regular Expressions and Regular Expression Search Flags and Inline Flags

Finditer and Findall Revisited


finditer and findall return all non-overlapping matches
for a regular expression
for m in re . finditer (r ’ aa ’ ," aaaa "):
print (" Match found :" , m . group (0) ,\
" starts at " , m . start (0) ," and ends at " , m . end (0) -1)
Match found : aa starts at 0 and ends at 1
Match found : aa starts at 2 and ends at 3
; the match that starts at 1 and ends at 2 is not found!
for s in re . findall (r ’\ d {2} ’ ,"1234"):
print (" Match found :" , s )
Match found : 12
Match found : 34

; the match ‘23’ is not found!

COMP519 Web Programming Lecture 23 Slide L23 – 19


Regular Expression Split

Regular Expression Split

re.split(regexp, string, maxsplit, flags)


returns a list of split components of string wrt regexp
– optional argument maxsplit is the maximum number of splits
that will be performed
people = \
[" surname : Marcon , forename : Emmanuel , position : president " ,
" surname : Merkel , forename : Angela , position : chancellor "]
for person in people :
data = re . split (r ’ ,?\ s *\ w +:\ s + ’ , person )
print ( data )
[ ’ ’ , ’ Macron , ’ Emmanuel , ’ president ’]
[ ’ ’ , ’ Merkel ’ , ’ Angela ’ , ’ chancellor ’]

for person in people :


data = re . split (r ’ ,?\ s *\ w +:\ s + ’ , person )[1:]
print ( data )
[ ’ Macron , ’ Emmanuel , ’ president ’]
[ ’ Merkel ’ , ’ Angela ’ , ’ chancellor ’]
COMP519 Web Programming Lecture 23 Slide L23 – 20
Regular Expression Substitution Substitution Operators

Regular Expression Substitution

re.sub(regexp, repl, string, count, flags)


returns the string obtained by replacing the leftmost non-overlapping
occurrences of regexp in string by repl
– repl can be a string or a function; if it is a string,
any backslash escapes in it are processed
– optional argument count is the maximum number of regexp
occurrences to be replaced (default: all)
re.sub(r’\s+’,r’ ’,’Mr and Ms Dobbs’)
# returns ’Mr and Ms Dobbs’
reObj.sub(string,count,flags)
analogous
ro = re.compile(r’\s+’)
ro.sub(r’ ’,’Mr and Ms Dobbs’)
# returns ’Mr and Ms Dobbs’

COMP519 Web Programming Lecture 23 Slide L23 – 21


Regular Expression Substitution Substitution Operators

Regular Expression Substitution

re.subn(regexp, repl, string, count, flags)


returns a tuple consisting of the result of
re.sub(regexp,repl,string,count,flags)
and the number of replacements performed
– repl can be a string or a function; if it is a string,
any backslash escapes in it are processed
– optional argument count is the maximum number of regexp
occurrences to be replaced (default: all)
re.subn(r’\s+’,r’ ’,’Mr and Ms Dobbs’)
# returns (’Mr and Ms Dobbs’,3)
reObj.subn(string,count,flags)
analogous
ro = re.compile(r’\s+’)
ro.subn(r’ ’,’Mr and Ms Dobbs’)
# returns (’Mr and Ms Dobbs’,3)
COMP519 Web Programming Lecture 23 Slide L23 – 22
Regular Expression Substitution Substitution Operators

Regular Substitution: Basics


• All leftmost non-overlapping occurrences are replaced
print ( re . sub (r ’\ d {3} ’ ,r ’A ’ , "1234567") )
" AA7 "
• The search for occurrences is not continued at the same index position
nor restarted after a replacement
print ( re . sub (r ’\ d {3} ’ ,r ’8989 ’ , "1234567") )
"898989897"
# "123|4567" -> "8989|456|7" -> "8989|8989|7"
# not "123|4567" -> "898|945|67" -> "898|898|967" -> ...

print ( re . sub (r ’ ABBA ’ ,r ’ ’ , " CABABBABAC ") )


" CABBAC " # not " CC "
text = " CABABBABAC "
while True :
( text , count ) = re . subn (r ’ ABBA ’ ,r ’ ’ , text )
if count == 0: break
print ( text )
" CC "
COMP519 Web Programming Lecture 23 Slide L23 – 23
Regular Expression Substitution Capture Groups

Substitution: Capture Groups


In a replacement string we can refer back to substrings matched by
capture groups
In the regular expression
(regexp) creates a capture group
(?P<name>regexp) creates a named capture group
In the replacement string
\N backreference to capture group N
(where N is a natural number 1 ≤ N ≤ 99)
\g<N> backreference to capture group N
\g<name> backreference to a named capture group
list = [" Dr Ullrich Hustadt " ," Dave Shield "]
for i in range (0 , len ( list )):
list [ i ] = re . sub (r ’( Mr | Ms | Dr )?\ s *(? P <F >\ w +)\ s +(? P <S >\ w +) ’ ,
r ’\ g <S > , \g <F > ’ , list [ i ])
print ( list )
[ ’ Hustadt , Ullrich ’ , ’ Shield , Dave ’]
COMP519 Web Programming Lecture 23 Slide L23 – 24
Regular Expression Substitution Flags and Inline Flags

Substitution: Flags and Inline Flags


• The same flags and inline flags can be used with re.sub
as with re.search
; only affects the behaviour of matching
• Beware that flags must be the fifth positional argument of re.sub or
use the keyword argument flags=flagValue

# Replace strong - elements by b - elements in an HTML document


# independent of the way tags were written
#
ts = " < strong > help </ STRONG > < em > me </ em >"
ts = re . sub (r ’ < strong >([^ <]*) </ strong > ’ ,
r ’ <b >\1 </ b > ’ , ts ,0 , re . I )
print ( ts )

<b > help </ b > < em > me </ em >

COMP519 Web Programming Lecture 23 Slide L23 – 25


Regular Expression Substitution Functions as Replacement

Substitution: Functions as Replacement


• re.sub can take a function instead of a replacement string as argument
• The function gets a match object as argument and should return a string

# Replace degrees Fahrenheit by degrees Celsius in a text


#
ts = ‘‘‘ The temperature on Monday was 105 degrees Fahrenheit
The temperature on Tuesday was 95.3 degrees Fahrenheit ’ ’ ’

r = r ’(? i )(? P <T >\ -?[\ d \.]+) degrees fahrenheit ’

def convertF ( mObj ):


return str ( round (( float ( mObj . group ( ’T ’)) -32)*5/9 ,1)) +\
" degrees Celsius "

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

COMP519 Web Programming Lecture 23 Slide L23 – 26


Revision and Further Reading

Regular Expressions and the Chomsky Hierarchy

• In Computer Science, formal


languages are categorised
according to the type of
grammar needed to generate
them (or the type of automaton
needed to recognise them)
• Python regular expressions can
at least recognise all regular
languages Chomsky Hiearchy of Formal Languages

• The regex library is intended to replace the re module at some point


and will be more powerful
• There are libraries specifically for parsing context free languages or
dealing with specific languages, e.g. HTML, CSV

COMP519 Web Programming Lecture 23 Slide L23 – 27


Revision and Further Reading

Revision and Further Reading

• 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]

COMP519 Web Programming Lecture 23 Slide L23 – 28


COMP519 Web Programming
Lecture 24: Python (Part 8)
Handouts

Ullrich Hustadt

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
73 CGI
Overview
CGI I/O
74 CGI Programs
Motivation
Local Setup
75 Python CGI Programs
Accessing and Processing Environment Variables: The os Module
Accessing and Processing Form Data: The cgi Module
Input Checks and Code Injection
Debugging Python CGI Scripts
76 Opening URLs: The urllib Module
Functions
Example
77 Revision and Further Reading
COMP519 Web Programming Lecture 24 Slide L24 – 1
CGI Overview

Common Gateway Interface — CGI


The Common Gateway Interface (CGI) is a standard method
for web servers to use an external application, a CGI program,
to dynamically generate web pages
1 A web client generates a client request,
for example, from an HTML form, and sends it to a web server
2 The web server selects a CGI program to handle the request,
converts the client request to a CGI request, executes the program
3 The CGI program then processes the CGI request and
the server passes the program’s response back to the client

COMP519 Web Programming Lecture 24 Slide L24 – 2


CGI CGI I/O

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 >

COMP519 Web Programming Lecture 24 Slide L24 – 3


CGI CGI I/O

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 >

COMP519 Web Programming Lecture 24 Slide L24 – 4


CGI CGI I/O

Encoding of input data

• Input data from an HTML form is sent URL-encoded as sequence of


key-value pairs: key1=value1&key2=value2&...
username = dave & fullname = David %20 Davidson
• Keys may not be unique (for example, in the case of checkboxes)
• Form controls without name do not appear
• All characters except A-Z, a-z, 0-9, -, _, ., ∼ (unreserved characters)
are encoded
• ASCII characters that are not unreserved characters are represented
using ASCII codes (preceded by %)
• A space is represented as %20 or +
• + is represented as %2B
• % is represented as %25

username = cath & fullname = Catherine + O %27 Donnell


COMP519 Web Programming Lecture 24 Slide L24 – 5
CGI CGI I/O

Request methods: GET versus POST


The two main request methods used with HTML forms
are GET and POST:
• GET:
• Form data is appended to the URI in the request (limited to 1024 characters)
<scheme> "://" <server-name> ":" <server-port>
<script-path> <extra-path> "?" <query-string>

• Form data is accessed by the CGI program via environment variables

GET / cgi - bin / cgiwrap / uh / process ? username = dave & fullname = David
,→+ Davidson HTTP /1.1
Host : student . csc . liv . ac . uk

COMP519 Web Programming Lecture 24 Slide L24 – 6


CGI CGI I/O

Request methods: GET versus POST


The two main request methods used with HTML forms
are GET and POST:
• POST:
• Form data is appended to end of the request (after headers and blank line)
• There is no limit on the length/size of the form data
• Form data can be accessed by the CGI program via standard input
• Form data is not necessarily URL-encoded (but URL-encoding is the default)

POST / cgi - bin / cgiwrap / uh / process HTTP /1.1


Host : student . csc . liv . ac . uk

username = dave & fullname = David + Davidson

COMP519 Web Programming Lecture 24 Slide L24 – 7


CGI CGI I/O

Environment variables: GET


Env variable Meaning
QUERY_STRING The query information passed to the program
REQUEST_METHOD The request method that was used
PATH_INFO Extra path information passed to a CGI program
PATH_TRANSLATED Translation of PATH_INFO from virtual to physical
path
SCRIPT_NAME The relative virtual path of the CGI program
SCRIPT_FILENAME The physical path of the CGI program
GET http :// student . csc . liv . ac . uk / cgi - bin / cgiwrap / uh / demo / more / dirs ?
username = dave & fullname = David + Davidson
QUERY_STRING username = dave & fullname = David + Davidson
REQUEST_METHOD GET
PATH_INFO / more / dirs
PATH_TRANSLATED / users / www / external / docs / more / dirs
SCRIPT_NAME / cgi - bin / cgiwrap / uh / demo
SCRIPT_FILENAME / users / loco / uh / public_html / cgi - bin / demo

STDIN # empty
COMP519 Web Programming Lecture 24 Slide L24 – 8
CGI CGI I/O

Environment variables: GET


Env variable Meaning
QUERY_STRING The query information passed to the program
REQUEST_METHOD The request method that was used
PATH_INFO Extra path information passed to a CGI program
PATH_TRANSLATED Translation of PATH_INFO from virtual to physical
path
SCRIPT_NAME The relative virtual path of the CGI program
SCRIPT_FILENAME The physical path of the CGI program
GET http :// student . csc . liv . ac . uk / cgi - bin / cgiwrap / uh / process / more / dirs ?
username =2%60 n + d %2 Bt + e + s %27 t & fullname = Peter + Newton
QUERY_STRING username =2%60 n + d %2 Bt + e + s %27 t & fullname = Peter + Newton
REQUEST_METHOD GET
PATH_INFO / more / dirs
PATH_TRANSLATED / users / www / external / docs / more / dirs
SCRIPT_NAME / cgi - bin / cgiwrap / uh / process
SCRIPT_FILENAME / users / loco / uh / public_html / cgi - bin / process

STDIN # empty
COMP519 Web Programming Lecture 24 Slide L24 – 9
CGI CGI I/O

Environment variables: POST


Env variable Meaning
QUERY_STRING The query information passed to the program
REQUEST_METHOD The request method that was used
SCRIPT_NAME The relative virtual path of the CGI program
SCRIPT_FILENAME The physical path of the CGI program

POST / cgi - bin / cgiwrap / uh / demo


Host : student . csc . liv . ac . uk

username =2%60 n + d %2 Bt + e + s %27 t & fullname = Peter + Newton


QUERY_STRING # empty
REQUEST_METHOD POST
SCRIPT_NAME / cgi - bin / cgiwrap / uh / demo
SCRIPT_FILENAME / users / loco / uh / public_html / cgi - bin / demo

STDIN username =2%60 n + d %2 Bt + e + s %27 t & fullname = Peter + Newton

COMP519 Web Programming Lecture 24 Slide L24 – 10


CGI CGI I/O

More environment variables

Env variable Meaning


HTTP_ACCEPT A list of the MIME types that the client can accept
HTTP_REFERER The URL of the document that the client points
to before accessing the CGI program
HTTP_USER_AGENT The browser the client is using to issue the request
REMOTE_ADDR The remote IP address of the user making the
request
REMOTE_HOST The remote hostname of the user making the re-
quest
SERVER_NAME The server’s hostname
SERVER_PORT The port number of the host on which the server
is running
SERVER_SOFTWARE The name and version of the server software

COMP519 Web Programming Lecture 24 Slide L24 – 11


CGI Programs Motivation

CGI programs and Python

• CGI programs need to process input data from environment variables


and STDIN, depending on the request method
; preferably, the input data would be accessible by the program
in a uniform way
• CGI programs need to process input data that is encoded
; preferably, the input data would be available in decoded form
• CGI programs need to produce HTML markup/documents as output
; preferably, there would be an easy way to produce HTML markup

In Python, we can use


• the cgi module to process inputs
• the environ dictionary of the os module
to access environment variables
• print statements to produce HTML markup
COMP519 Web Programming Lecture 24 Slide L24 – 12
CGI Programs Local Setup

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)

COMP519 Web Programming Lecture 24 Slide L24 – 13


CGI Programs Local Setup

Hello World CGI Program


#!/ usr / bin / python3

print ( ’ ’ ’\
Content - type : text / html

<! DOCTYPE html >


< html lang =" en - GB " >
< head >
< meta charset =" utf -8" >
< title > Hello World </ title >
</ head >
< body >
Hello World
</ body >
</ html > ’ ’ ’)

COMP519 Web Programming Lecture 24 Slide L24 – 14


Python CGI Programs

User-Defined Functions for an HTML Wrapper


It makes sense to define functions that print out the
initial (up to body start) and final HTML markup (from body end)
#!/ usr / bin / python3
# htmlUH . py placed in ∼ ullrich / public_html / cgi - bin /

def start_html ( title ):


print ( ’ ’ ’\
Content - type : text / html

<! DOCTYPE html >


< html lang =" en - GB " >
< head >
< meta charset =" utf -8" >
< link rel =" stylesheet " type =" text / css "
href ="/ ∼ ullrich / COMP519 / examples / table . css " >
< title > ’ ’ ’ + title + ’ ’ ’ </ title >
</ head > < body > ’ ’ ’)
def end_html ():
print ( ’ ’ ’ </ body > </ html > ’ ’ ’)
COMP519 Web Programming Lecture 24 Slide L24 – 15
Python CGI Programs Accessing and Processing Environment Variables: The os Module

Accessing Environment Variables


• The environ dictionary of the os module allows us to access
environment variables
• Standard dictionary operations can be applied
import os , sys , codecs , locale
from htmlUH import start_html , end_html
sys . stdout = codecs . getwriter (" utf -8")( sys . stdout . detach ())

start_html (" Environmental variables ")


print ( ’ ’ ’ < h1 > Unix environmental variables </ h1 > ’ ’ ’)
print ( ’ ’ ’ < table > < tbody > ’ ’ ’)
for k in sorted ( os . environ . keys ()):
print (" < tr > < th >"+ k +" </ th > < td >"+ os . environ [ k ]+" </ td > </ tr >")
print ( ’ ’ ’ </ tbody > </ table > ’ ’ ’)
print ( os . environ [ ’ QUERY_STRING ’])
print ( os . environ [ ’ REQUEST_METHOD ’])
if ’ PATH_INFO ’ in os . environ :
print ( os . environ [ ’ PATH_INFO ’])
end_html ()
COMP519 Web Programming Lecture 24 Slide L24 – 16
Python CGI Programs Accessing and Processing Environment Variables: The os Module

Accessing Environment Variables

COMP519 Web Programming Lecture 24 Slide L24 – 17


Python CGI Programs Accessing and Processing Environment Variables: The os Module

Processing Environment Variables: HTTP USER AGENT


• The environment variable HTTP_USER_AGENT contains information
about the user agent (browser) and operating system from which the
request pretents to come
• This information can be used to tailor the response

agent = os . environ [ ’ HTTP_USER_AGENT ’]


if re . search ( ’ Windows , agent ) and re . search ( ’ Edge ’ , agent ):
suite # Edge browser on Windows
elif re . search ( ’ Mac | iPad | iPhone ’ , agent ):
suite
else :
suite

COMP519 Web Programming Lecture 24 Slide L24 – 18


Python CGI Programs Accessing and Processing Environment Variables: The os Module

Processing Environment Variables: REMOTE ADDR


• The environment variable REMOTE_ADDR contains the IP address from
which the request comes
• Again, this information can be used to tailor the response, for example,
restricting access to a certain domain
• The module socket provides the function gethostbyaddr that can
(try to) convert an IP address to a domain

COMP519 Web Programming Lecture 24 Slide L24 – 19


Python CGI Programs Accessing and Processing Environment Variables: The os Module

Processing Environment Variables: REMOTE ADDR


import os , sys , socket , re , codecs , locale
from htmlUH import start_html , end_html
sys . stdout = codecs . getwriter (" utf -8")( sys . stdout . detach ())

start_html (" Where are you coming from ?")


print ( ’ < h1 > Where are you coming from ? </ h1 > ’)

user_ip = os . environ [" REMOTE_ADDR "]


try :
host = socket . gethostbyaddr ( user_ip )[0] # socket module
except :
host = ’ Not resolvable ’

print ( ’ < div > Clients IP address : ’ + user_ip + ’ </ div > ’)
print ( ’ < div > Clients hostname : ’ + host + ’ </ div > ’)

if re . search ( ’ liv \. ac \. uk ’ , host ) :


print ( ’ <p > Welcome , university user ! </p > ’)
else :
print ( ’ < div > <b > Sorry , please come back \
when you are on a uni computer </ b > </ div > ’)
end_html ()
COMP519 Web Programming Lecture 24 Slide L24 – 20
Python CGI Programs Accessing and Processing Environment Variables: The os Module

Processing Environment Variables: HTTP REFERER


• The environment variable HTTP_REFERER (not a typo) contains the URL
(if any) which referred the user agent to the current URL (your script)
• Not all user agents set this variable
• If a user agent accesses your script directly, then HTTP_REFERER may
not be set or may be meaningless
if processingError :
if ’ HTTP_REFERER ’ in os . environ :
target = os . environ [ ’ HTTP_REFERER ’]
print ( ’ Sorry , your booking cannot be processed < br > ’)
print ( ’ Please go back to <a href =" ’+ target + ’" > ’+ target + ’ </a > ’)
end_html ()

COMP519 Web Programming Lecture 24 Slide L24 – 21


Python CGI Programs Accessing and Processing Form Data: The cgi Module

Accessing and Processing Form Data


The module cgi provides methods to access the input data of HTML
forms in a two step process:
1 Create an instance of the FieldStorage class and assign it to a
variable
variable = cgi . FieldStorage ()
This reads the form data from standard input or the environment
variable QUERY_STRING
2 Then
• variable[’name’].value
• variable.getvalue(’name’)
• variable.getfirst(’name’, default=None)
• variable.getlist(’name’)
return the value/values entered for the form control with name name

COMP519 Web Programming Lecture 24 Slide L24 – 22


Python CGI Programs Accessing and Processing Form Data: The cgi Module

Accessing and Processing Form Data

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

COMP519 Web Programming Lecture 24 Slide L24 – 23


Python CGI Programs Accessing and Processing Form Data: The cgi Module

Accessing and Processing Form Data

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

Accessing and Processing Form Data: Example (1)

# 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 >

COMP519 Web Programming Lecture 24 Slide L24 – 25


Python CGI Programs Accessing and Processing Form Data: The cgi Module

Accessing and Processing Form Data: Example (1)


# Part of process
print ( ’ QUERY_STRING ’ , os . environ [ ’ QUERY_STRING ’] , ’ < br > < br > ’)
inputs = cgi . FieldStorage ()
for name in inputs . keys ():
print ( ’ Name : ’ , name , ’[]. value : ’ , inputs [ name ]. value , ’<br > ’)
print ( ’ Name : ’ , name , ’ getvalue : ’ , inputs . getvalue ( name ) , ’ < br > ’)
print ( ’ Name : ’ , name , ’ getfirst : ’ , inputs . getfirst ( name ) , ’ < br > ’)
print ( ’ Name : ’ , name , ’ getlist : ’ , inputs . getlist ( name ) , ’<br > ’)
print ( ’ < br > ’)
QUERY_STRING userName = dave & fullname = David + Davidson

Name : userName []. value : dave


Name : userName getvalue : dave
Name : userName getfirst : dave
Name : userName getlist : [ ’ dave ’]

Name : fullname []. value : David Davidson


Name : fullname getvalue : David Davidson
Name : fullname getfirst : David Davidson
Name : fullname getlist : [ ’ David Davidson ’]

COMP519 Web Programming Lecture 24 Slide L24 – 26


Python CGI Programs Accessing and Processing Form Data: The cgi Module

Accessing and Processing Form Data: Example (2)

# 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 >

COMP519 Web Programming Lecture 24 Slide L24 – 27


Python CGI Programs Accessing and Processing Form Data: The cgi Module

Accessing and Processing Form Data: Example (2)


# Part of process
print ( ’ QUERY_STRING ’ , os . environ [ ’ QUERY_STRING ’] , ’ < br > < br > ’)
inputs = cgi . FieldStorage ()
for name in inputs . keys ():
print ( ’ Name : ’ , name , ’[]. value : ’ , inputs [ name ]. value , ’<br > ’)
print ( ’ Name : ’ , name , ’ getvalue : ’ , inputs . getvalue ( name ) , ’ < br > ’)
print ( ’ Name : ’ , name , ’ getfirst : ’ , inputs . getfirst ( name ) , ’ < br > ’)
print ( ’ Name : ’ , name , ’ getlist : ’ , inputs . getlist ( name ) , ’<br > ’)
print ( ’ < br > ’)
QUERY_STRING userName =& fullname = Catherine + O %27 Donnell

Name : fullname []. value : Catherine O ’ Donnell


Name : fullname getvalue : Catherine O ’ Donnell
Name : fullname getfirst : Catherine O ’ Donnell
Name : fullname getlist : [" Catherine O ’ Donnell "]

COMP519 Web Programming Lecture 24 Slide L24 – 28


Python CGI Programs Input Checks and Code Injection

Input Checks and Code Injection


• Do not trust any data accessed via param (beware code injection)
print ( ’ Username : ’ , inputs . getfirst ( ’ username ’) , ’ < br > ’)
together with input
< script > window . location =" http :// malware_site /" </ script >

for username, would redirect the browser to malware_site.


• Either check whether the data has the format expected
if ’ username ’ in inputs and \
re . search (r ’^[ a - z0 -9]+ $ ’ , inputs . getfirst ( ’ username ’)):
print ( ’ Username : ’ , inputs . getfirst ( ’ username ’) , ’ < br > ’)
else :
print ( ’ Not a valid user name ’)
or sanitise the input using the cgi method cgi.escape:
print ( ’ Username : ’ ,
cgi . escape ( inputs . getfirst ( ’ username ’) , quote = True ) , ’ < br > ’)

or even better, do both


COMP519 Web Programming Lecture 24 Slide L24 – 29
Python CGI Programs Debugging Python CGI Scripts

Debugging Python CGI Scripts

• 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 ()

COMP519 Web Programming Lecture 24 Slide L24 – 30


Opening URLs: The urllib Module Functions

Opening a URL from a Python Script


The urllib.request module provides functions that retrieve data
from URLs
• urlopen(url)
attempts to open the URL url given as a string or Request object
• If retrieval fails, it raises an exception
• If retrieval succeeds, it returns a Response object
• A Response object has the methods such as
• info(): returns the meta-information of the retrieve data
• getcode(): returns the HTTP status code of the response
• read(): returns the content that was retrieved as a bytes object
• A bytes object has the method
• decode(enc): returns a string obtained by decoding the object
according to the encoding enc,
examples of encodings are ’utf-8’, ’ascii’

COMP519 Web Programming Lecture 24 Slide L24 – 31


Opening URLs: The urllib Module Example

Opening a URL from a Python Script


import cgi , codecs , locale , os , re , sys , urllib . request
sys . stdout = codecs . getwriter (" utf -8")( sys . stdout . detach ())
url = ’ ’ ’\
http :// cgi . csc . liv . ac . uk / ∼ ullrich / COMP519 / examples / HW . html ’ ’ ’
try :
response = urllib . request . urlopen ( url )
text = response . read (). decode ( ’ utf -8 ’)
print ( text )
except :
print (" Could not retrieve " , url )

<! DOCTYPE html >


< html lang =" en - GB " >
< head >
< title > Hello World </ title >
</ head >
< body >
Hello World
</ body >
</ html >
COMP519 Web Programming Lecture 24 Slide L24 – 32
Revision and Further Reading

Revision and Further Reading


• Read
• Chapter 28: Using CGI: How and When to Use CGI
• Chapter 28: Using CGI: Sample Data
• Chapter 28: Using CGI: Python Examples
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
• 21.2. cgi — Common Gateway Interface support
https://docs.python.org/3/library/cgi.html#module-cgi
• 21.6. urllib.request — Extensible library for opening URLs
https://docs.python.org/3/library/urllib.request.html?
highlight=urllib%20request#module-urllib.request
of Python Software Foundation: The Python Standard Library,
3 October 2017. https://docs.python.org/3/library
[accessed 26 November 2017]
COMP519 Web Programming Lecture 24 Slide L24 – 33
COMP519 Web Programming
Lecture 25: PHP (Part 1)
Handouts

Ullrich Hustadt

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents

78 PHP
Motivation

79 Overview
Features
Applications

80 Types and Variables


Types
Variables
Type juggling and Type casting
Comparisons

81 Further Reading

COMP519 Web Programming Lecture 25 Slide L25 – 1


PHP Motivation

Common Gateway Interface — CGI


The Common Gateway Interface (CGI) is a standard method for web
servers to use external applications, a CGI program, to dynamically
generate web pages
1 A web client generates a client request, for example, from a HTML
form, and sends it to a web server
2 The web server selects a CGI program to handle the request,
converts the client request to a CGI request, executes the program
3 The CGI program then processes the CGI request and the server passes
the program’s response back to the client

COMP519 Web Programming Lecture 25 Slide L25 – 2


PHP Motivation

Disadvantages of CGI Programming


• A distinction is made between static web pages and
dynamic web pages created by an external program
• Using CGI programs it is difficult to add ‘a little bit’ of
dynamic content to a web page
– can be alleviated to some extent by using triple-quoted strings
• Use of an external program requires
• starting a separate process every time an external program is requested
• exchanging data between web server and external program
; resource-intensive

If our main interest is the creation of dynamic web pages,


then the scripting language we use
• should integrate well with HTML
• should not require a web server to execute an external program
COMP519 Web Programming Lecture 25 Slide L25 – 3
Overview Features

PHP

• PHP is (now) a recursive acronym for PHP: Hypertext Preprocessor


• Development started in 1994 by Rasmus Lerdorf
• Originally designed as a tool for tracking visitors at Lerdorf’s website
• Developed into full-featured, scripting language for
server-side web programming
• Inherits a lot of the syntax and features from Perl
• Easy-to-use interface to databases
• Free, open-source
• Probably the most widely used server-side web programming language
• Negatives: Inconsistent, muddled API; no scalar objects
The departmental web server uses PHP 5.6.25 (released August 2014)
PHP 7 was released in December 2015 (PHP 6 was never released)

COMP519 Web Programming Lecture 25 Slide L25 – 4


Overview Features

PHP Processing

• Server plug-ins exist for various web servers


; avoids the need to execute an external program
• PHP code is embedded into HTML pages using tags
; static web pages can easily be turned into dynamic ones
PHP satisfies the criteria we had for a good web scripting language

Processing proceeds as follows:


1 The web server receives a client request
2 The web server recognizes that the client request is for
a HTML page containing PHP code
3 The server executes the PHP code, substitutes output
into the HTML page, the resulting page is then send to the client
As in the case of Python, the client never sees the PHP code,
only the HTML web page that is produced
COMP519 Web Programming Lecture 25 Slide L25 – 5
Overview Applications

PHP: Applications

• Applications written using PHP


• activeCollab – Project Collaboration Software
http://www.activecollab.com/
• Drupal – Content Management System (CMS)
http://drupal.org/home
• Magento – eCommerce platform
http://www.magentocommerce.com/
• MediaWiki – Wiki software
http://www.mediawiki.org/wiki/MediaWiki
• Moodle – Virtual Learning Environment (VLE)
http://moodle.org/
• Sugar – Customer Relationship Management (CRM) platform
http://www.sugarcrm.com/crm/
• WordPress – Blogging tool and CMS
http://wordpress.org/

COMP519 Web Programming Lecture 25 Slide L25 – 6


Overview Applications

PHP: Websites

• Websites using PHP:


• Delicious – social bookmarking
http://delicious.com/
• Digg – social news website
http://digg.com
• Facebook – social networking
http://www.facebook.com
• Flickr – photo sharing
http://www.flickr.com
• Frienster – social gaming
http://www.frienster.com
• SourceForge – web-based source code repository
http://sourceforge.net/
• Wikipedia – collaboratively built encyclopedia
http://www.wikipedia.org

COMP519 Web Programming Lecture 25 Slide L25 – 7


Overview Applications

PHP: Hello World!


1 < html lang = " en - GB " >
2 < head > < title > Hello World </ title > </ head >
3 < body >
4 <h1 > Our first PHP script </ h1 >
5 <? php
6 print ( " <p > <b > Hello World ! </b > </p >\ n " );
7 ?>
8 </ body > </ html >

• PHP code is enclosed between <?php and ?>


• File must be stored in a directory accessible by the web server, for
example $HOME/public_html, and be readable by the web server
• File name must have the extension .php, e.g. hello_world.php

COMP519 Web Programming Lecture 25 Slide L25 – 8


Overview Applications

PHP: Hello World!


Since version 4.3.0, PHP also has a command line interface
1 # !/ usr / bin / php
2 <? php
3 /* Author : Ullrich Hustadt
4 A " Hello World " PHP script . */
5 print ( " Hello World !\ n " );
6 // A single - line comment
7 ?>

Hello World !

• PHP code still needs to be enclosed between <?php and ?>


• Code must be stored in an executable file
• File name does not need to have any particular format
; PHP can be used to write CGI programs
; PHP can be used as a scripting language outside a web program-
ming context
COMP519 Web Programming Lecture 25 Slide L25 – 9
Overview Applications

PHP: Hello World!


< html lang = " en - GB " >
< head > < title > Hello World </ title > </ head >
< body > < h1 > Our first PHP script </ h1 >
<? php
print ( " <p > <b > Hello World ! </b > </p >\ n " );
?>
</ body > </ html >

• Can also ‘executed’ using


php filename
• File does not need to exectuable, only readable for the user

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 >

COMP519 Web Programming Lecture 25 Slide L25 – 10


Overview Applications

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 */

COMP519 Web Programming Lecture 25 Slide L25 – 11


Types and Variables Types

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

• Integers, floating-point numbers, and booleans do not differ significantly


from the corresponding JavaScript types
• Strings differ from those in JavaScript and Python

COMP519 Web Programming Lecture 25 Slide L25 – 12


Types and Variables Variables

Variables

• All PHP variable names start with $ followed by a PHP identifier


• A PHP identifier consists of letters, digits, and underscores,
but cannot start with a digit
PHP identifiers are case sensitive
• In PHP, a variable does not have to be declared before it can be used

• A variable also does not have to be initialised before it can be used,


although initialisation is a good idea
• Uninitialized variables have a default value of their type depending on
the context in which they are used
Type Default Type Default
bool FALSE string empty string
int/float 0 array empty array
If there is no context, then the default value is NULL
COMP519 Web Programming Lecture 25 Slide L25 – 13
Types and Variables Variables

Assignments

• Just like Java, JavaScript and Python, PHP uses the equality sign = for
assignments
$student_id = 200846369;

As in JavaScript, this is an assignment expression


• The value of an assignment expression is the value assigned
$b = ( $a = 0) + 1;
// $a has value 0
// $b has value 1

COMP519 Web Programming Lecture 25 Slide L25 – 14


Types and Variables Variables

Binary Assignments
PHP also supports the standard binary assignment operators:

Binary assignment Equivalent assignment


$a += $b $a = $a + $b
$a -= $b $a = $a - $b
$a *= $b $a = $a * $b
$a /= $b $a = $a / $b
$a %= $b $a = $a % $b
$a **= $b $a = $a ** $b
$a .= $b $a = $a . $b

// Convert Fahrenheit to Celsius :


// Subtract 32 , then multiply by 5 , then divide by 9
$temperature = 105; // temperature in Fahrenheit
$temperature -= 32;
$temperature *= 5;
$temperature /= 9; // converted to Celsius

COMP519 Web Programming Lecture 25 Slide L25 – 15


Types and Variables Variables

Constants

• bool define(string, expr [, case_insensitive])


• defines a constant that is globally accessible within a script
• string should be a string consisting of a PHP identifier
(preferably all upper-case)
The PHP identifier is the name of the constant
• expr is an expression that should evaluate to a value of a primitiver type (In
PHP 7, expr can also be an array)
• case_insensitive is an optional boolean argument, indicating
whether the name of the constant is case-insensitive (default is FALSE)
• returns TRUE on success or FALSE on failure

define ( " PI " ,3.14159);


define ( " SPEED_OF_LIGHT " ,299792458 , true );
# PHP 7
define ( " ANIMALS " ,[ " bird " ," cat " ," dog " ]);

COMP519 Web Programming Lecture 25 Slide L25 – 16


Types and Variables Variables

Constants

• To use a constant we simply use its name


define ( " PI " ,3.14159);
define ( " SPEED_OF_LIGHT " ,299792458 , true );
# PHP 7
define ( " ANIMALS " ,[ " bird " ," cat " ," dog " ]);

$circumfence = PI * $diameter ;
$distance = speed_of_light * $time ;
$myPet = ANIMALS [1];

• Caveat: PHP does not resolve constants within double-quoted strings


(or here documents)
print " 1 - Value of PI : PI \ n " ;
print " 2 - Value of PI : " . PI . " \ n " ;
1 - Value of PI : PI
2 - Value of PI : 3.14159

COMP519 Web Programming Lecture 25 Slide L25 – 17


Types and Variables Variables

Values, Variables and Types


PHP provides several functions that explore the type of an expression:
string gettype(expr) returns the type of expr as string
bool is_type(expr) checks whether expr is of type type
void var_dump(expr) displays structured information about expr
that includes its type and value

<? php print " Type of 23: " . gettype (23). " \ n " ;
print " Type of 23.0: " . gettype (23.0). " \ n " ;
print " Type of \"23\": " . gettype ( " 23 " ). " \ n " ;

if ( is_int (23)) { echo " 23 is an integer \ n " ; }


else { echo " 23 is not an integer \ n " ; }
?>
Type of 23: integer
Type of 23.0: double
Type of " 23 " : string
23 is an integer

COMP519 Web Programming Lecture 25 Slide L25 – 18


Types and Variables Type juggling and Type casting

Type juggling and Type casting

• PHP automatically converts a value to the appropriate type as required


by the operation applied to the value (type juggling)
2 . " worlds" ; "2 worlds"
"2" * 3 ; 6
"1.23e2" + 0 ; 123
"hello" * 3 ; 0
"10hello5" + 5 ; 15
• PHP also supports explicit type casting via (type)
(int) "12" ; 12 (bool) "0" ; FALSE
(int) "1.23e2" ; 1 (bool) "foo" ; TRUE
(int) ("1.23e2" + 0) ; 123 (float) "1.23e2" ; 123
(int) "10hello5" ; 10
(int) 10.5 ; 10
(array) "foo" ; array(0 => "foo")
COMP519 Web Programming Lecture 25 Slide L25 – 19
Types and Variables Comparisons

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

COMP519 Web Programming Lecture 25 Slide L25 – 21


Types and Variables Comparisons

Comparison Operators: The Spaceship Operator


PHP 7 introduced an additional comparison operator
expr1 <=> expr2 Compare -1 iff expr1 < expr2
0 iff expr1 == expr2
1 iff expr1 > expr2

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

COMP519 Web Programming Lecture 25 Slide L25 – 22


Further Reading

Revision and Further Reading


Read
• Chapter 29: PHP Basics
• Chapter 30: The PHP 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

COMP519 Web Programming Lecture 25 Slide L25 – 23


COMP519 Web Programming
Lecture 26: PHP (Part 2)
Handouts

Ullrich Hustadt

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
82 Primitive Datatypes
Integers and Floating-point numbers
Exceptions and error handling
Booleans
Strings
83 Arrays
Basics
Foreach-loops
Array Operators
84 Special types
NULL
Resources
85 Printing
86 Revision and Further Reading

COMP519 Web Programming Lecture 26 Slide L26 – 1


Primitive Datatypes Integers and Floating-point numbers

Integers and Floating-point numbers

• PHP distinguishes between


• integer numbers 0 2012 -40 1263978
• floating-point numbers 1.25 256.0 -12e19 2.4e-10
• PHP supports a wide range of pre-defined mathematical functions
abs(number) absolute value
ceil(number) round fractions up
floor(number) round fractions down
round(number [,prec,mode]) round fractions
log(number [,base]) logarithm
rand(min,max) generate an integer random number
sqrt(number) square root
• PHP provides a range of pre-defined number constants including
M_PI 3.14159265358979323846
NAN ‘not a number’
INF ‘infinity’
COMP519 Web Programming Lecture 26 Slide L26 – 2
Primitive Datatypes Integers and Floating-point numbers

Integers and Floating-point numbers: NAN and INF


The constants NAN and INF are used as return values for some applications
of mathematical functions that do not return a number
• log(0) returns -INF (negative ‘infinity’)
• sqrt(-1) returns NAN (‘not a number’)

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!

COMP519 Web Programming Lecture 26 Slide L26 – 3


Primitive Datatypes Integers and Floating-point numbers

Integers and Floating-point numbers: NAN and INF


NAN and INF can be compared with each other and other numbers using
equality and comparison operators:

NAN == NAN ; FALSE NAN === NAN ; FALSE NAN == 1 ; FALSE


INF == INF ; FALSE INF === INF ; TRUE INF == 1 ; FALSE
NAN < NAN ; TRUE INF < INF ; TRUE 1 < INF ; TRUE
NAN < INF ; TRUE INF < NAN ; TRUE INF < 1 ; FALSE
NAN < 1 ; TRUE 1 < NAN ; TRUE

In PHP 5.3 and earlier versions, INF == INF returns FALSE


In PHP 5.4 and later versions, INF == INF returns TRUE

COMP519 Web Programming Lecture 26 Slide L26 – 4


Primitive Datatypes Integers and Floating-point numbers

Integers and Floating-point numbers: NAN and INF

• PHP provides three functions to test whether a value is or is not NAN,


INF or -INF:
• bool is_nan(value)
returns TRUE iff value is NAN
• bool is_infinite(value)
returns TRUE iff value is INF or -INF
• bool is_finite(value)
returns TRUE iff value is neither NAN nor INF/-INF
• In conversion to a boolean value,
both NAN and INF are converted to TRUE
• In conversion to a string,
NAN converts to ’NAN’ and INF converts to ’INF’

COMP519 Web Programming Lecture 26 Slide L26 – 5


Primitive Datatypes Exceptions and error handling

Exceptions and error handling


PHP distinguishes between exceptions and errors
• A possible way to perform exception handling in PHP is as follows:
try { ... run code here ... // try
} catch ( Exception $e ) {
... handle the exception here using $e // catch
}

• Errors must be dealt with by an error handling function


(‘Division by zero’ produces an error not an exception)
One possible approach is to let the error handling function
turn errors into exceptions
function e x c e p t i o n _e r ro r _h an d le r ( $errno , $errstr ,
$errfile , $errline ) {
throw new ErrorException ( $errstr , $errno ,
0 , $errfile , $errline ); }
set_error_ handle r ( " e x ce p ti on _ er r or _h a nd le r " );

http://www.php.net/manual/en/class.errorexception.php
COMP519 Web Programming Lecture 26 Slide L26 – 6
Primitive Datatypes Booleans

Booleans

• PHP has a boolean datatype


with constants TRUE and FALSE (case insensitive)
• PHP offers the same short-circuit boolean operators as Java and
JavaScript:
&& (conjunction) || (disjunction) ! (negation)
• Alternatively, and and or can be used instead of && and ||, respectively
• However, not is not a PHP operator
• The truth tables for these operators are the same as for JavaScript
• Remember that && and || are not commutative, that is,
(A && B) is not the same as (B && A)
(A || B) is not the same as (B || A)

COMP519 Web Programming Lecture 26 Slide L26 – 7


Primitive Datatypes Booleans

Type conversion to boolean


When converting to boolean, the following values are considered FALSE:
• the boolean FALSE itself
• the integer 0 (zero)
• the float 0.0 (zero)
• the empty string, and the string ’0’
• an array with zero elements
• an object with zero member variables (PHP 4 only)
• the special type NULL (including unset variables)
• SimpleXML objects created from empty tags

Every other value is considered TRUE (including any resource)

COMP519 Web Programming Lecture 26 Slide L26 – 8


Primitive Datatypes Strings

Strings

• PHP supports both single-quoted and double-quoted strings


• PHP also supports heredocs as a means to specify multi-line strings
<<< identifier
here document
identifier
• identifier might optionally be surrounded by double-quotes
• identifier might also be surrounded by single-quotes,
making the string a nowdoc in PHP terminology

print ’ < html lang =" en - GB " >


< head > < title > Multi - line String </ title > </ head > ’;
print < < < EOF
< body > Some text </ body >
</ html >
EOF ;

COMP519 Web Programming Lecture 26 Slide L26 – 9


Primitive Datatypes Strings

Strings
PHP distinguishes between
• single-quoted strings and
• double-quoted strings

single-quoted strings double-quoted strings


(‘taken literally’) (‘interpreted’/‘evaluated’)
’hello’ ; hello "hello" ; hello
’don\’t’ ; don’t "don’t" ; don’t
’"hello"’ ; "hello" "\"hello\"" ; "hello"
’backslash\\’ ; backslash\ "backslash\\" ; backslash\
’glass\\table’ ; glass\table "glass\\table" ; glass\table
’glass\table’ ; glass\table "glass\table" ; glass able

COMP519 Web Programming Lecture 26 Slide L26 – 10


Primitive Datatypes Strings

Strings

• Variable interpolation is applied to double-quoted strings


$title = " String Operators " ;
print " < title > $title </ title > " ;

< title > String Operators </ title >

• The string concatenation operator is denoted by ‘.’


• Instead of Perl’s string multiplication operator ‘x’ there is
string str_repeat(string_arg, number)
$string = " <p > I shall not repeat myself . <p >\ n " ;
print " < body > " . str_repeat ( $string ,3). ’ </ body > ’;

< body > <p > I shall not repeat myself . <p >
<p > I shall not repeat myself . <p >
<p > I shall not repeat myself . <p >
</ body >

COMP519 Web Programming Lecture 26 Slide L26 – 11


Arrays Basics

Arrays

• PHP only supports associative arrays (hashes), simply called arrays


• PHP arrays are created using the array construct or,
since PHP 5.4, [ ... ]:
array ( key = > value , ... )
[ key = > value , ...]
where key is an integer or string and value can be of any type,
including arrays
$arr1 = [1 = > " Peter " , 3 = > 2009 , " a " = > 101];
$arr2 = array (200846369 = > array ( " name " = > " Jan Olsen " ,
" COMP518 " = > 69 ,
" COMP519 " = > 52));

• The size of an array can be determined using the count function:


int count(array[, mode])
print count ( $arr1 ); // prints 3
print count ( $arr2 ); // prints 1
print count ( $arr2 ,1); // prints 4
COMP519 Web Programming Lecture 26 Slide L26 – 12
Arrays Basics

Arrays

• It is possible to omit the keys when using the array construct:


$arr3 = array ( " Peter " , " Paul " , " Mary " );

The values given in array will then be associated with the


natural numbers 0, 1, . . .

• All the keys of an array can be retrieved using


array_keys($array1)
; returns a natural number-indexed array containing
the keys of $array1
• All the values of an array can be retrieved using
array_values($array1)
; returns a natural number-indexed array containing
the values stored in $array1

COMP519 Web Programming Lecture 26 Slide L26 – 13


Arrays Basics

Arrays

• An individual array element can be accessed via its key


• Accessing an undefined key produces an error message
and returns NULL
$arr1 = array (1 = > " Peter " , 3 = > 2009 , " a " = > 101);
print " ’a ’: " . $arr1 [ " a " ]. " \ n " ;
print " ’b ’: " . $arr1 [ " b " ]. " \ n " ;
$arr1 [ ’b ’] = 102;
print " ’b ’: " . $arr1 [ " b " ]. " \ n " ;
’a ’: 101
PHP Notice : Undefined index : b in < file > on line < lineno >
’b ’: // $arr1 [" b "] returns NULL
’b ’: 102
• The function array_key_exists(key,array1) can be used to check
whether there is a value for key in array1
array_key_exists ( " a " , $arr1 ) # returns TRUE
array_key_exists ( " c " , $arr1 ) # returns FALSE

COMP519 Web Programming Lecture 26 Slide L26 – 14


Arrays Basics

Arrays

• PHP allows the construct


$ array [] = value ;

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

• A key-value pair can be removed from an array using the


unset function:
$arr1 = array (1 = > " Peter " , 3 = > 2009 , " a " = > 101);
unset ( $arr1 [3]); // Removes the pair 3 = > 2009
unset ( $arr1 ); // Removes the whole array

COMP519 Web Programming Lecture 26 Slide L26 – 15


Arrays Foreach-loops

Arrays: foreach-loop

• PHP provides a foreach-loop construct to ‘loop’ through the elements


of an array
foreach ( array as $ value )
statement

foreach ( array as $ key = > $ value )


statement
• array is an array expression
• $key and $value are two variables, storing a different key-value pair in
array at each iteration of the foreach-loop
• foreach iterates through an array in the order in which elements were
defined

COMP519 Web Programming Lecture 26 Slide L26 – 16


Arrays Foreach-loops

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

COMP519 Web Programming Lecture 26 Slide L26 – 17


Arrays Foreach-loops

Arrays: foreach-loop
Example 3:
$arr6 = array ( " name " = > " Peter " , " year " = > 2009);

foreach ( $arr6 as $key = > $value ) {


print " The array maps $key to $value \ n " ;
$value .= " - modified " ; // Changing $value
}
print " \ n " ;

foreach ( $arr6 as $key = > $value )


print " The array now maps $key to $value \ n " ;
The array maps name to Peter
The array maps year to 2009

The array now maps name to Peter


The array now maps year to 2009

In each iteration, $value contains a copy of an array element


; changing the copy does not affect the array element itself
COMP519 Web Programming Lecture 26 Slide L26 – 18
Arrays Foreach-loops

Arrays: foreach-loop

• In order to modify array elements within a foreach-loop we need use a


reference
foreach ( array as & $ value )
statement
unset ( $ value );

foreach ( array as $ key = > & $ value )


statement
unset ( $ value );
• In the code schemata above, $value is a variable whose value is stored at
the same location as an array element
• Note that PHP does not allow the key to be a reference
• The unset statement is important to return $value to being a ‘normal’
variable

COMP519 Web Programming Lecture 26 Slide L26 – 19


Arrays Foreach-loops

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 " ;

foreach ( $arr6 as $key = > $value )


print " The array now maps $key to $value \ n " ;
The array maps name to Peter
The array maps year to 2009

The array now maps name to Peter - modified


The array now maps year to 2009 - modified

In each iteration, $value contains a reference to an array element


; changing $value changes the array element
COMP519 Web Programming Lecture 26 Slide L26 – 20
Arrays Foreach-loops

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

$array1 = range (1 , 1000);


$mem2 = memory_get_usage ();
$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 " ;
(2) 24 more bytes
$array1 [1] = 10002 | $array2 [1] = 10002
(3) 0 more bytes

COMP519 Web Programming Lecture 26 Slide L26 – 22


Arrays Array Operators

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

COMP519 Web Programming Lecture 26 Slide L26 – 23


Special types NULL

NULL

• NULL is both a special type and a value


• NULL is the only value of type NULL
and the name of this constant is case-insensitive
• A variable has both type NULL and value NULL in the following three
situations:
1 The variable has not yet been assigned a value (not equal to NULL)
2 The variable has been assigned the value NULL
3 The variable has been unset using the unset operation

• There are a variety of functions that can be used to test whether a


variable is NULL including:
• bool isset($variable)
TRUE iff $variable exists and does not have value NULL
• bool is_null(expr)
TRUE iff expr is identical to NULL

COMP519 Web Programming Lecture 26 Slide L26 – 24


Special types 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

Type juggling means that an empty array is (loosely) equal to NULL


but not identical (strictly equal) to NULL

COMP519 Web Programming Lecture 26 Slide L26 – 25


Special types Resources

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

COMP519 Web Programming Lecture 26 Slide L26 – 26


Special types Resources

Resources

• bool fclose(resource)
• Closes the resource
• Returns TRUE on success

• string fgets(resource [, length])


• Returns a line read from resource and
returns FALSE if there is no more data to be read
• With optional argument length, reading ends when length − 1 bytes
have been read, or a newline or on EOF (whichever comes first)
• string fread(resource,length)
• Returns length characters read from resource

$handle = fopen ( ’ somefile . txt ’ , ’r ’ );


while ( $line = fgets ( $handle )) {
// processing the line of the file
}
fclose ( $handle );
COMP519 Web Programming Lecture 26 Slide L26 – 27
Special types Resources

Resources

• int fwrite(resource, string [, length])


• Writes a string to a resource
• If length is given, writing stops after length bytes have been written or
the end of string is reached, whichever comes first
• int fprintf(resource, format, arg1, arg2, ...)
• Writes a list of arguments to a resource in the given format
• Identical to fprintf with output to resource
• int vfprintf (resource, format, array)
• Writes the elements of an array to a resource in the given format
• Identical to vprintf with output to resource

$handle = fopen ( ’ somefile . txt ’ , ’w ’ );


fwrite ( $handle , " Hello World ! " . PHP_EOL ); // ‘ logical newline ’
fclose ( $handle );
In PHP \n always represents the character with ASCII code 10 not the
platform dependent newline ; use PHP_EOL instead
COMP519 Web Programming Lecture 26 Slide L26 – 28
Printing

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)

Additionally, PHP also provides the functions print, and printf:


• int print(arg)
• Outputs its argument
Only one argument is allowed!
• Returns value 1
• Parentheses can be omitted

COMP519 Web Programming Lecture 26 Slide L26 – 29


Printing

Printing

• string sprintf(format, arg1, arg2, ....)


• Returns a string produced according to the formatting string format
• Parentheses are necessary
See http://www.php.net/manual/en/function.sprintf.php
for details
• int printf(format, arg1, arg2, ...)
• Produces output according to format
• Parentheses are necessary
• Returns the length of the outputted string

• Important: In contrast to Python, a PHP array cannot take the


place of a list of arguments
printf ( " %2 d apples %2 d oranges \ n " , array (5 ,7));
produces an error message
COMP519 Web Programming Lecture 26 Slide L26 – 30
Printing

Printing

• string vsprintf(format, array)


• Returns a string produced according to the formatting string format
• Identical to sprintf but accepts an array as argument
• Parentheses are necessary

• int vprintf(format, array)


• Produces output according to format
• Identical to printf but accepts an array as argument
• Parentheses are necessary

vprintf ( " %2 d apples %2 d oranges \ n " , array (5 ,7));


5 apples 7 oranges

COMP519 Web Programming Lecture 26 Slide L26 – 31


Revision and Further Reading

Revision and Further Reading


Read
• Language Reference: Types: Booleans
http://uk.php.net/manual/en/language.types.boolean.php
• Language Reference: Types: Integers
http://uk.php.net/manual/en/language.types.integer.php
• Language Reference: Types: Floating Point Numbers
http://uk.php.net/manual/en/language.types.float.php
• Language Reference: Types: Strings
http://uk.php.net/manual/en/language.types.string.php
• Language Reference: Types: Arrays
http://uk.php.net/manual/en/language.types.array.php
• Language Reference: Control Structures: foreach
http://uk.php.net/manual/en/control-structures.foreach.php
of M. Achour, F. Betz, A. Dovgal, et al: PHP Manual. The PHP Group,
2017. http://uk.php.net/manual/en [accessed 28 Nov 2017]
COMP519 Web Programming Lecture 26 Slide L26 – 32
COMP519 Web Programming
Lecture 27: PHP (Part 3)
Handouts

Ullrich Hustadt

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
87 Control Structures
Conditional Statements
Switch Statements
While- and Do While-loops
For-loops
88 Functions
Defining and Calling a Function
Scope of Variables
Functions and HTML
Variable-length Argument Lists
Closures and Anonymous Functions
Type Declarations
89 PHP libraries
Include/Require
90 Revision and Further Reading
COMP519 Web Programming Lecture 27 Slide L27 – 1
Control Structures

Control Structures

PHP control structures


• conditional statements
• switch statements
• while- and Do while-loops
• for-loops
• break and continue
are mostly identical to those of Java

COMP519 Web Programming Lecture 27 Slide L27 – 2


Control Structures Conditional Statements

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
}

• the elseif-clauses is optional and there can be more than one


Note: elseif instead of elif or else if
• the else-clause is optional but there can be at most one
• the curly brackets can be omitted if there is only
a single statement in a clause

COMP519 Web Programming Lecture 27 Slide L27 – 3


Control Structures Conditional Statements

Conditional Statements/Expressions

• PHP allows to replace curly brackets with a colon : combined with an


endif at the end of the statement:
if ( condition ):
statements
elseif ( condition ):
statements
else :
statements
endif

This also works for the switch statement in PHP


However, this syntax becomes difficult to parse
when nested conditional statements are used and is best avoided

• PHP also supports conditional expressions


condition ? if_true_expr : if_false_expr

COMP519 Web Programming Lecture 27 Slide L27 – 4


Control Structures Switch Statements

Switch Statement
A switch statement in PHP takes the following form

switch ( expr ) { • there can be arbitrarily many case-clauses


case expr1 : • the default-clause is optional but there can be
statements
break ; at most one
case expr2 : • expr is evaluated only once and then compared
statements
to expr1, expr2, etc using (loose) equality ==
break ;
default : • once two expressions are found to be equal the
statements corresponing clause is executed
break ;
}
• if none of expr1, expr2, etc are equal to expr,
then the default-clause will be executed
• break ‘breaks out’ of the switch statement
• if a clause does not contain a break command,
then execution moves to the next clause

COMP519 Web Programming Lecture 27 Slide L27 – 5


Control Structures Switch Statements

Switch Statement: Example (1)


Example: Classic Adventure Game Commands
switch ( $command ) {
case " North " :
$y += 1; break ;
case " South " :
$y -= 1; break ;
case " West " ;
$x -= 1; break ;
case " East " :
$x += 1; break ;
case " Search " :
if (( $x = 5) && ( $y = 3))
echo " Found a treasure \ n " ;
else
echo " Nothing here \ n " ;
break ;
default :
echo " Not a valid command \ n " ; break ;
}
COMP519 Web Programming Lecture 27 Slide L27 – 6
Control Structures Switch Statements

Switch Statement: Example (2)


Not every case-clause needs to have associated statements

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 ;
}

COMP519 Web Programming Lecture 27 Slide L27 – 7


Control Structures While- and Do While-loops

While- and Do While-loops

• PHP offers while-loops and do while-loops


while ( condition ) {
statements
}

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);

COMP519 Web Programming Lecture 27 Slide L27 – 8


Control Structures For-loops

For-loops

• for-loops in PHP take the form


for ( initialisation ; test ; increment ) {
statements
}
Again, the curly brackets are not required if the body of the loop only
consists of a single statement
• In PHP initialisation and increment can consist of more than one
statement, separated by commas instead of semicolons
Example:
for ( $i = 3 , $j = 3; $j >= 0; $i ++ , $j - -)
echo " $i - $j - " , $i * $j , " \ n " ;
3 - 3 - 9
4 - 2 - 8
5 - 1 - 5
6 - 0 - 0
COMP519 Web Programming Lecture 27 Slide L27 – 9
Control Structures For-loops

Break and Continue

• 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 ;
}

• The continue command stops the execution of the current iteration of a


loop and moves the execution to the next iteration
for ( $x = -2; $x <= 2; $x ++) {
if ( $x == 0) continue ;
printf ( " 10 / %2 d = %3 d \ n " ,$x ,(10/ $x ));
}
10 / -2 = -5
10 / -1 = -10
10 / 1 = 10
10 / 2 = 5

COMP519 Web Programming Lecture 27 Slide L27 – 10


Functions Defining and Calling a Function

Functions
Functions are defined as follows in PHP:
function identifier ( $ param1 , & $ param2 , ...) {
statements
}

• Functions can be placed anywhere in a PHP script but preferably they


should all be placed at start of the script (or at the end of the script)
• Function names are case-insensitive
• The function name must be followed by parentheses
• A function has zero, one, or more parameters that are variables
• Parameters can be given a default value using
$param = const_expr
• When using default values, any defaults must be on the right side of
any parameters without defaults

COMP519 Web Programming Lecture 27 Slide L27 – 11


Functions Defining and Calling a Function

Functions
Functions are defined as follows in PHP:
function identifier ( $ param1 , & $ param2 , ...) {
statements
}

• The return statement


return value
can be used to terminate the execution of a function and to make
value the return value of the function
• The return value does not have to be scalar value
• A function can contain more than one return statement
• Different return statements can return values of different types

COMP519 Web Programming Lecture 27 Slide L27 – 12


Functions Defining and Calling a Function

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);

COMP519 Web Programming Lecture 27 Slide L27 – 13


Functions Scope of Variables

Variables
PHP distinguishes three categories of variables:
• Local variables are only accessible in the part of the code in which they
are introduced

• Global variables are accessible everywhere in the code

• Static variables are local variables within a function that retain their
value between separate calls of the function

By default, variables in PHP are local but not static

COMP519 Web Programming Lecture 27 Slide L27 – 14


Functions Scope of Variables

PHP Functions: Example

function bubble_sort ( $array ) {


// $array , $size , $i , $j are all local
if (! is_array ( $array ))
trigger_error ( " Argument not an array \ n " , E_USER_ERROR );
$size = count ( $array );
for ( $i =0; $i < $size ; $i ++) {
for ( $j =0; $j < $size -1 - $i ; $j ++) {
if ( $array [ $j +1] < $array [ $j ]) {
swap ( $array , $j , $j +1); } } }
return $array ;
}

function swap (& $array , $i , $j ) {


// swap expects a reference ( to an array )
$tmp = $array [ $i ];
$array [ $i ] = $array [ $j ];
$array [ $j ] = $tmp ;
}
Note: The functions are not nested
COMP519 Web Programming Lecture 27 Slide L27 – 15
Functions Scope of Variables

PHP Functions: Example

function bubble_sort ( $array ) {


... swap ( $array , $j , $j +1); ...
return $array ;
}

function swap (& $array , $i , $j ) {


$tmp = $array [ $i ];
$array [ $i ] = $array [ $j ];
$array [ $j ] = $tmp ; }

$array = array (2 ,4 ,3 ,9 ,6 ,8 ,5 ,1);


echo " Before sorting " , join ( " , " , $array ) , " \ n " ;
$sorted = bubble_sort ( $array );
echo " After sorting " , join ( " , " , $array ) , " \ n " ;
echo " Sorted array " , join ( " , " , $sorted ) , " \ n " ;
Before sorting 2 , 4 , 3 , 9 , 6 , 8 , 5 , 1
After sorting 2 , 4 , 3 , 9 , 6 , 8 , 5 , 1
Sorted array 1, 2, 3, 4, 5, 6, 8, 9

COMP519 Web Programming Lecture 27 Slide L27 – 16


Functions Scope of Variables

Nested Functions

• PHP allows the definition of nested functions


function outer ( $param1 , & $param2 , ...) {
function inner ( $param3 , & $param4 , ...) { ... }
}

• 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 , ...) { ... }
}

COMP519 Web Programming Lecture 27 Slide L27 – 17


Functions Scope of Variables

Functions and Scope


$x = " hello " ;
function func1 () {
echo " 1: " ,$x , " \ n " ;
}
func1 ();
function func2 () { • A variable defined outside any function is
echo " 2: " ,$x , " \ n " ;
global
$x = " Bye " ;
echo " 3: " ,$x , " \ n " ; • A global variable can be accessed from any
} part of the script that is not inside a
func2 ();
function
echo " 4: " ,$x , " \ n " ;
• A variable within a PHP function is by
1: PHP Notice :
Undefined variable : x default local and can only be accessed
within that function
2: PHP Notice :
Undefined variable : x

3: Bye
4: hello
COMP519 Web Programming Lecture 27 Slide L27 – 18
Functions Scope of Variables

Functions and Global Variables

• A variable is declared to be global using the keyword global


function echo_x ( $x ) {
echo " $x " ;
global $x ;
echo $x ;
}

$x = 5; // this is a global variable called $x


echo_x (10); // prints first ‘10 ’ then ‘5 ’

; an otherwise local variable is made accessible outside its normal


scope using global
; all global variables with the same name refer to the same
storage location/data structure
; an unset operation removes a specific variable, but leaves other
(global) variables with the same name unchanged

COMP519 Web Programming Lecture 27 Slide L27 – 19


Functions Scope of Variables

PHP Functions and Global Variables


1 function m o d i f y _ o r _de stroy _var ( $arg ) {
2 global $x , $y ;
3 if ( is_bool ( $arg ) && ! $arg ) { $x = $x * $y ; }
4 if ( is_bool ( $arg ) && $arg ) { unset ( $x ); echo $x ; }
5 }
6 $x = 2; $y = 3; $z = 4;
7 echo " 1: \ $x = $x , \ $y = $y , \ $z = $z \ n " ;
8 unset ( $z );
9 echo " 2: \ $x = $x , \ $y = $y , \ $z = $z \ n " ;
10 m od ify_ o r _ d e s t r o y _ va r ( false );
11 echo " 3: \ $x = $x , \ $y = $y \ n " ;
12 m od ify_ o r _ d e s t r o y _ va r ( true );
13 echo " 4: \ $x = $x , \ $y = $y \ n " ;
1: $x = 2 , $y = 3 , $z = 4
PHP Notice : Undefined variable : z in script on line 9
2: $x = 2 , $y = 3 , $z =
3: $x = 6 , $y = 3
PHP Notice : Undefined variable : x in script on line 4
4: $x = 6 , $y = 3

COMP519 Web Programming Lecture 27 Slide L27 – 20


Functions Scope of Variables

PHP Functions and Static Variables

• A variable is declared to be static using the keyword static and should


be combined with the assignment of an initial value (initialisation)
function counter () { static $count = 0; return $count ++; }

; static variables are initialised only once


function counter () { static $count = 0; return $count ++; }
$count = 5;
echo " 1: global \ $count = $count \ n " ;
echo " 2: static \ $count = " , counter () , " \ n " ;
echo " 3: static \ $count = " , counter () , " \ n " ;
echo " 4: global \ $count = $count \ n " ;
echo " 5: static \ $count = " , counter () , " \ n " ;
1: global $count = 5
2: static $count = 0
3: static $count = 1
4: global $count = 5
5: static $count = 2

COMP519 Web Programming Lecture 27 Slide L27 – 21


Functions Functions and HTML

Functions and HTML

• It is possible to include HTML markup in the body of a


function definition
• The HTML markup can in turn contain PHP scripts
• A call of the function will execute the PHP scripts, insert the output
into the HTML markup, then output the resulting HTML markup
<? php
function print_form ( $fn , $ln ) {
?>
< form action = " process_form . php " method = POST " >
< label > First Name : < input type = " text " name = " f " value = " <? php echo $fn ? > " > </ label > < br >
< label > Last Name <b >* </ b >: < input type = " text " name = " l " value = " <? php echo $ln ? > " > </ label > < br >
< input type = " submit " name = " submit " value = " Submit " > < input type = reset >
</ form >
<? php
}
print_form ( " Ullrich " ," Hustadt " );
?>
< form action = " process_form . php " method = POST " >
< label > First Name : < input type = " text " name = " f " value = " Ullrich " > </ label > < br >
< label > Last Name <b >* </ b >: < input type = " text " name = " l " value = " Hustadt " > </ label > < br >
< input type = " submit " name = " submit " value = " Submit " > < input type = reset >
</ form >

COMP519 Web Programming Lecture 27 Slide L27 – 22


Functions Variable-length Argument Lists

Functions with Variable Number of Arguments


The number of arguments in a function call is allowed to exceed the
number of parameters of the function
; the parameter list only specifies the minimum number of arguments
• int func_num_args()
returns the number of arguments passed to a function
• mixed func_get_arg(arg_num)
returns the specified argument, or FALSE on error
• array func_get_args()
returns an array with copies of the arguments passed to a function
function sum () { // no minimum number of arguments
if ( func_num_args () < 1) return null ;
$sum = 0;
foreach ( func_get_args () as $value ) { $sum += $value ; }
return $sum ;
}

COMP519 Web Programming Lecture 27 Slide L27 – 23


Functions Variable-length Argument Lists

Functions with Variable Number of Arguments

• 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

function sum (... $numbers ) {


if ( count ( $numbers ) < 1) return null ;
$sum = 0;
foreach ( $numbers as $value ) { $sum += $value ; }
return $sum ;
}
echo sum (0 , TRUE , " 2 " ,3 e0 ) , " \ n " ;
6

COMP519 Web Programming Lecture 27 Slide L27 – 24


Functions Closures and Anonymous Functions

Closures and Anonymous Functions

• PHP supports anonymous functions as objects of the closure class


• Via a use clause, anonymous functions can gain access to external
variables

$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

COMP519 Web Programming Lecture 27 Slide L27 – 25


Functions Type Declarations

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

COMP519 Web Programming Lecture 27 Slide L27 – 26


PHP libraries Include/Require

Including and Requiring Files

• It is often convenient to build up libraries of function definitions,


stored in one or more files, that are then reused in PHP scripts
• PHP provides the commands include, include_once, require, and
require_once to incorporate the content of a file into a PHP script
include ’ mylibrary . php ’;

• 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

COMP519 Web Programming Lecture 27 Slide L27 – 27


PHP libraries Include/Require

Including and Requiring Files

• Several include or require commands for the same library file


results in the file being incorporated several times
; defining a function more than once results in an error
• Several include_once or require_once commands for the same
library file results in the file being incorporated only once
• If a library file requested by include and include_once cannot be
found, PHP generates a warning but continues the execution of the
requesting script
• If a library file requested by require and require_once cannot be
found, PHP generates a error and stops execution of the requesting
script

COMP519 Web Programming Lecture 27 Slide L27 – 28


PHP libraries Include/Require

PHP Libraries: Example


mylibrary.php
<? php
function bubble_sort ( $array ) {
... swap ( $array , $j , $j +1); ...
return $array ;
}

function swap (& $array , $i , $j ) {


...
}
?>
example.php
<? php
require_once ’ mylibrary . php ’;
$array = array (2 ,4 ,3 ,9 ,6 ,8 ,5 ,1);
$sorted = bubble_sort ( $array );
?>

COMP519 Web Programming Lecture 27 Slide L27 – 29


Revision and Further Reading

Revision and Further Reading


Read
• Language Reference: Control Structures
http://uk.php.net/manual/en/language.control-structures.php
including if, else, elseif, while, do-while, for, foreach, break,
continue, switch, return, require, require_once, include,
include_once
• Language Reference: Functions
http://uk.php.net/manual/en/language.functions.php
of M. Achour, F. Betz, A. Dovgal, et al: PHP Manual. The PHP Group,
2017. http://uk.php.net/manual/en [accessed 28 Nov 2017]

COMP519 Web Programming Lecture 27 Slide L27 – 30


COMP519 Web Programming
Lecture 28: PHP (Part 4)
Handouts

Ullrich Hustadt

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
91 Web Applications
Overview
HTML Forms
92 Available Information and Input
Overview
PHP Environment
Server Variables
Form Data
93 PHP Sessions
Start a PHP Session
Maintain Session Data
End a PHP Session
Session Management
Example
94 Authentication
Overview
Example
COMP519 Web Programming Lecture 28 Slide L28 – 1
Web Applications Overview

Web Applications using PHP

IBM: Build Ajax-based Web sites with PHP, 2 Sep 2008.


https://www.ibm.com/developerworks/library/wa-aj-php/ [accessed 6 Mar 2013]
COMP519 Web Programming Lecture 28 Slide L28 – 2
Web Applications HTML Forms

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

Information Available to PHP Scripts

• Information on the PHP environment


• Information on the web server and client request
• Form data
• Cookie/Session data
• Miscellaneous
• string date(format)
returns the current date/time presented according to format
for example, date(’H:i l, j F Y’)
results in 12:20 Thursday, 8 March 2012
(See http://www.php.net/manual/en/function.date.php)
• int time()
returns the current time measured in the number of seconds
since January 1 1970 00:00:00 GMT

COMP519 Web Programming Lecture 28 Slide L28 – 4


Available Information and Input PHP Environment

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

Manipulating the PHP Configuration


The following functions can be used to access and change the
configuation of PHP from within a PHP script:
• array ini_get_all()
• returns all the registered configuration options

• string ini_get(option)
• returns the value of the configuration option on success

• string ini_set(option, value)


• sets the value of the given configuration option to a new value
• the configuration option will keep this new value during the script’s
execution and will be restored afterwards

• void ini_restore(option)
• restores a given configuration option to its original value

COMP519 Web Programming Lecture 28 Slide L28 – 6


Available Information and Input Server Variables

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

Forms in PHP: Example (1)

• 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

COMP519 Web Programming Lecture 28 Slide L28 – 9


Available Information and Input Form Data

Forms in PHP: Example (1)


extract_names.php
<! DOCTYPE html >
< html > < head > < title > Name Extraction </ title > </ head > < body >
<? php
require_once ’ extraction . php ’;
if ( isset ( $_SERVER [ ’ REQUEST_METHOD ’ ]) &&
$_SERVER [ ’ REQUEST_METHOD ’] == ’ POST ’ &&
isset ( $_REQUEST [ ’ url ’ ])) {
$extracted_names = extract_names ( $_REQUEST [ ’ url ’ ]);
echo " <div > The names occurring in <br > " , htmlspecialchars ( $_REQUEST [ ’ url ’]) ,
" <br > are </ div > $extracted_names \ n " ;
} else {
echo <<< FORM
< form method = " post " >
< label > Enter a URL :
< input type = " text " name = " url " size = " 100 "
value = " http :// cgi . csc . liv . ac . uk / ∼ ullrich / COMP284 / tests / a1test1 . txt " >
</ label > < br > < br >
< input type = " submit " value = " Extract Names " >
</ form >
FORM ;
}
?>
</ body > </ html >
http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/extract_names.php

COMP519 Web Programming Lecture 28 Slide L28 – 10


Available Information and Input Form Data

Forms in PHP: Example (1)


extraction.php
<? php
function extract_names ( $url ) {
$text = file_get_co ntents ( $url );
if ( $text === false )
return " ERROR : INVALID URL ! " ;
else {
$correct = preg_match_all ( " / name ={([^\}]+)}/ " ,
$text , $matches , PRE G_ PA TT ER N_ OR DE R );
if ( $correct == 0) return " ERROR : NO NAMES FOUND " ;
$count = array _c ou nt _v al ue s ( $matches [1]);
arsort ( $count );
foreach ( $count as $name = > $number ) {
$table .= " <tr > < td > $name </ td > < td > $number </ td > </ tr > " ;
}
$table = " < table > < thead > < tr > < th > Name </ th > < th > No of occur " .
" rences </ th > </ tr > </ thead > < tbody > " . $table . " </ tbody > </ table > " ;
return $table ;
} }
?>
http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/extraction.php
COMP519 Web Programming Lecture 28 Slide L28 – 11
Available Information and Input Form Data

Web Applications Revisited


Request • An interaction between a user
App and a server-side web application
onse
Resp often requires a sequence of
Select
Request requests and responses
Item
App • For each request, the application
onse starts from scratch
Resp
Enter • it does not maintain a state
Request
Address between consecutive requests
App
onse • it does not know whether the
Resp
Enter requests come from the same user
Request or different users
Payment
App ;
onse
Resp data needs to be
Confirm
Request transferred from one execution
Order
App of the application to the next

COMP519 Web Programming Lecture 28 Slide L28 – 12


Available Information and Input Form Data

Transfer of Data: Example


• Assume for a sequence of requests we do not care whether they come
from the same user or different users
• Then hidden inputs can be used for the transfer of data from one
request / page to the next
form1.php
< form action = " form2 . php " method = " post " >
< label > Name : < input type = " text " name = " name " > </ label >
</ form >
form2.php
< form action = " process . php " method = " post " >
< label > Address : < input type = " text " name = " address " > </ label >
< input type = " hidden " name = " name "
value = " <? php echo $_REQUEST [ ’ name ’] ? > " >
</ form >
process.php
<? php
echo $_REQUEST [ ’ name ’ ]; echo $_REQUEST [ ’ address ’ ];
?>
COMP519 Web Programming Lecture 28 Slide L28 – 13
PHP Sessions

Sessions

• Assume for a sequence of requests we do care whether they come from


the same user or different users
• Sessions help to solve this problem by associating client requests with a
specific user and maintaining data over a sequence of requests from
that user
• Sessions are often linked to user authentication but are independent of
it, for example, eCommerce websites maintain a ‘shopping basket’
without requiring user authentication first
However, sessions are the mechanism that is typically used to allow or
deny access to web pages based on a user having been authenticated

COMP519 Web Programming Lecture 28 Slide L28 – 14


PHP Sessions

Sessions

• Servers keep track of a user’s sessions by using a session identifier,


which
• is generated by the server when a session starts and
• is then used by the browser when the user requests a page from the server

The session identifier can be sent through a cookie or by passing the


session identifier in client requests
• In addition, one can use session variables for storing information to
relate to a user and her session (session data), for example,
the items of an order
• Sessions only store information temporarily
If one needs to preserve information between visits by the same user,
one needs to consider a method such as using a cookie or a database
to store such information
COMP519 Web Programming Lecture 28 Slide L28 – 15
PHP Sessions

Cookies
Browser −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−→ Server
GET /index.html HTTP/1.1
Host: intranet.csc.liv.ac.uk

Browser ←−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− Server


HTTP/1.0 200 OK
Content-type: text/html
Set-Cookie: name1=value1
Set-Cookie: name2=value2; Expires= Thu, 20 Mar 2014, 14:00 GMT
(content of index.html)

Browser −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−→ Server


GET /teaching.html HTTP/1.1
Host: intranet.csc.liv.ac.uk
Cookie: name1=value1; name2=value2
Accept: */*

Browser ←−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− Server


HTTP/1.0 200 OK
Content-type: text/html
Set-Cookie: name1=value3
Set-Cookie: name2=value4; Expires= Fri, 21 Mar 2014, 14:00 GMT
Set-Cookie: name3=value5; Expires= Fri, 28 Mar 2014, 20:00 GMT
(content of teaching.html)

Wikipedia Contributors: HTTP Cookie. Wikipedia, The Free Encyclopedia, 5 March 2014 20:50.
http://en.wikipedia.org/wiki/HTTP_cookie [accessed 6 Mar 2014]

COMP519 Web Programming Lecture 28 Slide L28 – 16


PHP Sessions

PHP Sessions

Sesssions proceed as follows


1 Start a PHP session
– bool session_start()
– string session_id([id])
– bool session_regenerate_id([delete_old])
2 Maintain session data
– bool session_start()
– $_SESSION array
– bool isset($_SESSION[key])
– (interacting with a database)
3 End a PHP session
– bool session_destroy()
– void session_unset()
– bool setcookie(name, value, expires, path)

COMP519 Web Programming Lecture 28 Slide L28 – 17


PHP Sessions Start a PHP Session

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

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
?>

COMP519 Web Programming Lecture 28 Slide L28 – 19


PHP Sessions Maintain Session Data

Maintain Session Data

• 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

COMP519 Web Programming Lecture 28 Slide L28 – 20


PHP Sessions Maintain Session Data

Maintain Session Data

• 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 " ;
?>

COMP519 Web Programming Lecture 28 Slide L28 – 21


PHP Sessions End a PHP Session

End a PHP Session

• 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 setcookie(name, value, expires, path)


• defines a cookie to be sent along with the rest of the HTTP headers
• must be sent before any output from the script
• the first argument is the name of the cookie
• the second argument is the value of the cookie
• the third argument is time the cookie expires (as a Unix timestamp), and
• the fourth argument is the parth on the server in which the cookie will be
available
COMP519 Web Programming Lecture 28 Slide L28 – 22
PHP Sessions End a PHP Session

End a PHP Session

• 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 ();
?>

Note: Closing your web browser will also end a session


COMP519 Web Programming Lecture 28 Slide L28 – 23
PHP Sessions Session Management

More on Session Management


The following code tracks whether a session is active and ends the session
if there has been no activity for more then 30 minutes
if ( isset ( $_SESSION [ ’ LAST_ACTIVITY ’ ]) &&
( time () - $_SESSION [ ’ LAST_ACTIVITY ’] > 1800)) {
// last request was more than 30 minates ago
session_destroy (); // destroy session data in storage
session_unset (); // unset session variables
if ( session_id () != " " || isset ( $_COOKIE [ session_name ()]))
setcookie ( session_name () , session_id () , time () -2592000 , ’/ ’ );
} else {
// update last activity time stamp
$_SESSION [ ’ LAST_ACTIVITY ’] = time ();
}

The following code generates a new session identifier every 30 minutes


if (! isset ( $_SESSION [ ’ CREATED ’ ])) {
$_SESSION [ ’ CREATED ’] = time ();
} else if ( time () - $_SESSION [ ’ CREATED ’] > 1800) {
// session started more than 30 minates ago
ses sion _ r e g e n e r a t e_ i d ( true );
$_SESSION [ ’ CREATED ’] = time ();
}
http://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session-after-30-minutes

COMP519 Web Programming Lecture 28 Slide L28 – 24


PHP Sessions Example

PHP Sessions: Example


mylibrary.php:
<? php
session_start ();

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 ’ ];
}
?>

COMP519 Web Programming Lecture 28 Slide L28 – 25


PHP Sessions Example

PHP Sessions: Example


page1.php:
<? php
require_once ’ mylibrary . php ’;
echo " < html lang =\" en - GB \" > < head > </ head > < body >\ n " ;
echo " Hello visitor ! < br / > This is your page request no " ;
echo count_requests (). " from this site . < br / >\ n " ;
echo ’ <a href =" page1 . php " > Continue </ a > |
<a href =" finish . php " > Finish </ a > </ body > ’;
?>
finish.php:
<? php
require_once ’ mylibrary . php ’;
d e st r o y _s e s s i o n _ a n d _ d a ta ();
echo " < html lang =\" en - GB \" > < head > </ head > < body >\ n " ;
echo " Goodbye visitor ! < br / >\ n " ;
echo ’ <a href =" page1 . php " > Start again </ a > </ body > ’;
?>

http://cgi.csc.liv.ac.uk/~ullrich/COMP284/examples/page1.php
COMP519 Web Programming Lecture 28 Slide L28 – 26
PHP Sessions Example

PHP and Cookies


Cookies can survive a session and transfer information from one session to
the next
cmylibrary.php:
<? php
session_start ();
function d e s t r o y _ s e s s i o n_ a n d _d a t a () { // unchanged }

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

PHP Sessions and Authentication

• Sessions are the mechanism that is typically used to allow or deny


access to web pages based on a user having been authenticated
• Outline solution:
• We want to protect a page content.php from unauthorised use
• Before being allowed to access content.php, users must first authenticate
themselves by providing a username and password on the page login.php
• The system maintains a list of valid usernames and passwords in a database
and checks usernames and passwords entered by the user against that
database
If the check succeeds, a session variable is set
• The page content.php checks whether this session variable is set
If the session variable is set, the user will see the content of the page
If the session variable is not set, the user is redirected to login.php
• The system also provides a logout.php page to allow the user to log out
again
COMP519 Web Programming Lecture 28 Slide L28 – 28
Authentication Example

PHP Sessions and Authentication: Example


Second part of login.php:
<! DOCTYPE html >
< html lang = " en - GB " >
< head > < title > Login </ title > </ head >
< body >
<h1 > Login </ h1 >
< form action = " " method = " post " >
< label > Username :
< input name = " user " placeholder = " username " type = " text " >
</ label >
< label >
Password :
< input name = " passwd " placeholder = " ** " type = " password " >
</ label >
< input name = " submit " type = " submit " value = " login " >
< span > <? php echo $error ; ? > </ span >
</ form >
</ body >
</ html >
http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/login.php
COMP519 Web Programming Lecture 28 Slide L28 – 29
Authentication Example

PHP Sessions and Authentication: Example


First part of login.php:
<? php
session_start ();

function checkCredentials ( $user , $passwd ) {


// Check whether $user and $passwd are non - empty
// and match an entry in the database
}

$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

PHP Sessions and Authentication: Example


content.php:
<? php
session_start ();
if (! isset ( $_SESSION [ ’ user ’ ])) {
// User is not logged in , redirecting to login page
header ( ’ Location : login . php ’ );
}
?>
<! DOCTYPE html >
< html lang = " en - GB " >
< head > < title > Content that requires login </ title > </ head >
< body >
<h1 > Protected Content </ h1 >
<b > Welcome <i > <? php echo $_SESSION [ ’ user ’] ? > </i > </b > < br / >
<b > < a href = " logout . php " > Log Out </ a > </b >
</ body >
</ html >

http://cgi.csc.liv.ac.uk/~ullrich/COMP284/examples/content.php
COMP519 Web Programming Lecture 28 Slide L28 – 31
Authentication Example

PHP Sessions and Authentication: Example


logout.php:
<? php
session_start ();
$user = $_SESSION [ ’ user ’ ];
session_unset ();
session_destroy ();
?>
<! DOCTYPE html >
< html lang = " en - GB " >
< head >
< title > Logout </ title >
</ head >
< body >
<h1 > Logout </ h1 >
<b > Goodbye <i > <? php echo $user ? > </i > </b > < br / >
<b > < a href = " login . php " > Login </ a > </b >
</ form >
</ body >
http://cgi.csc.liv.ac.uk/~ullrich/COMP284/examples/logout.php
COMP519 Web Programming Lecture 28 Slide L28 – 32
Further Reading

Revision and Further Reading

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

COMP519 Web Programming Lecture 28 Slide L28 – 33


COMP519 Web Programming
Lecture 29: PHP (Part 5)
Handouts

Ullrich Hustadt

Department of Computer Science


School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
96 Classes
Defining and Instantiating a Class
Visibility
Class Constants
Static Properties and Methods
Destructors
Inheritance
Interfaces
Introspection Functions
97 The PDO Class
Introduction
Connections
Queries and Processing of Results
Prepared Statements
Transactions
98 Revision and Further Reading
COMP519 Web Programming Lecture 29 Slide L29 – 1
Classes Defining and Instantiating a Class

Defining and Instantiating a Class

• PHP is an object-oriented language with classes


• A class can be defined as follows:
class identifier {
prope r t y _ d e f i n i tions
funct i o n _ d e f i n i tions
}

• The class name identifier is case-sensitive


• The body of a class consists of property definitions and function definitions
• The function definitions may include the definition of a constructor
• An object of a class is created using
new identifier ( arg1 , arg2 ,...)

where arg1,arg2,... is a possibly empty list of arguments passed to


the constructor of the class identifier

COMP519 Web Programming Lecture 29 Slide L29 – 2


Classes Defining and Instantiating a Class

A Closer Look at Class Definitions


In more detail, the definition of a class
typically looks as follows
class identifier { • Every instance obj of this
# Properties
vis $attrib1
class will have attributes
... attrib1,. . . and methods
vis $attribN = value method1(), . . . accessible
as obj->attrib1 and
# Constructor
function __construct ( p1 ,...) {
obj->method1(a1...)
statements • __construct is the
} constructor of the class and
# Methods
will be called whenever
vis function method1 ( p1 ,...) {
statements new identifier(a1,...)
} is executed
vis function methodN ( p1 ,...) { • vis is a declaration of the
statements
} visibility of each attribute
} and method
COMP519 Web Programming Lecture 29 Slide L29 – 3
Classes Defining and Instantiating a Class

A Closer Look at Class Definitions

• The pseudo-variable $this is available when a method is called from


within an object context and is a reference to the calling object
• Inside method definitions, $this can be used to refer to the properties
and methods of the calling object
• The object operator -> is used to access methods and properties of the
calling object

class Rectangle {
protected $height ;
protected $width ;

function __construct ( $height , $width ) {


$this - > width = $width ;
$this - > height = $height ;
}
}

COMP519 Web Programming Lecture 29 Slide L29 – 4


Classes Visibility

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

• Classes can have their own constants and


constants can be declared to be public, private or protected
; by default, class constants are public
vis const identifier = value ;

• Accessing a private or protected constant outside its visibility is a fatal


error ; execution of the script stops
• Class constants are allocated once per class,
and not for each class instance
• Class constants are accessed using the scope resolution operator ::
class MyClass {
const SIZE = 10;
}
echo MyClass :: SIZE ; # prints 10
$o = new MyClass ();
echo $o :: SIZE ; # prints 10
COMP519 Web Programming Lecture 29 Slide L29 – 6
Classes Static Properties and Methods

Static Properties and Methods


• Class properties or methods can be declared static
• Static class properties and methods are accessed (via the class) using
the scope resolution operator ::
• Static class properties cannot be accessed via an instantiated class
object, but static class methods can
• Static class method have no access to $this
class Employee {
static $totalNumber = 0;
public $name ;

function __construct ( $name ) {


$this - > $name = $name ;
Employee :: $totalNumber ++;
} }
$e1 = new Employee ( " Ada " );
$e2 = new Employee ( " Ben " );
echo Employee :: $totalNumber # prints 2
COMP519 Web Programming Lecture 29 Slide L29 – 7
Classes Destructors

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 ;

function __construct ( $name ) {


$this - > name = $name ;
Employee :: $totalNumber ++;
}
function __destruct () {
Employee :: $totalNumber - -;
}
}
$e1 = new Employee ( " Ada " );
$e2 = new Employee ( " Ben " );
echo Employee :: $totalNumber # prints 2
$e1 = null ;
echo Employee :: $totalNumber # prints 1
COMP519 Web Programming Lecture 29 Slide L29 – 8
Classes Inheritance

Inheritance

• In a class definition it is possible to specify one parent class from which


a class inherits constants, properties and methods:
class identifier1 extends identifier2 { ... }

• The constructor of the parent class is not automatically called it must


be called explicitly from the child class
• Inherited constants, properties and methods can be overridden by
redeclaring them with the same name defined in the parent class
• The declaration final can be used to prevent a method from being
overriden
• Using parent:: it is possible to access overridden methods or static
properties of the parent class
• Using self:: it is possible to access static properties and methods of
the current class

COMP519 Web Programming Lecture 29 Slide L29 – 9


Classes Inheritance

Inheritance
class Rectangle {
protected $height ;
protected $width ;

function __construct ( $height , $width ) {


$this - > width = $width ;
$this - > height = $height ;
}
function area () {
return $this - > width * $this - > height ;
} }

class Square extends Rectangle {


function __construct ( $size ) {
parent :: __construct ( $size , $size );
} }

$rt1 = new Rectangle (3 ,4);


echo " \ $rt1 area = " , $rt1 - > area () , " \ n " ;
$sq1 = new Square (5);
echo " \ $sq1 area = " , $sq1 - > area () , " \ n " ;
$rt1 area = 12
$sq1 area = 15
COMP519 Web Programming Lecture 29 Slide L29 – 10
Classes Interfaces

Interfaces

• Interfaces specify which methods a class must implement without


providing an implementation
• Interfaces are defined in the same way as a class with the keyword
class replaced by interface
• All methods in an interface must be declared public
• A class can declare that it implements one ore more interfaces using the
implements keyword

interface Shape {
public function area ();
}
class Rectangle implements Shape {
...
}

COMP519 Web Programming Lecture 29 Slide L29 – 11


Classes Introspection Functions

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

COMP519 Web Programming Lecture 29 Slide L29 – 12


Classes Introspection Functions

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"]

COMP519 Web Programming Lecture 29 Slide L29 – 13


The PDO Class Introduction

The PDO Class

• The PHP Data Objects (PDO) extension defines an interface for


accessing databases in PHP
• Various PDO drivers implement that interface for specific
database management systems
• PDO_MYSQL implements the PDO interface for MySQL 3.x to 5.x
• PDO_SQLSRV implements the PDO interface for MS SQL Server and SQL
Azure

COMP519 Web Programming Lecture 29 Slide L29 – 14


The PDO Class Connections

Connections

• Before we can interact with a DBMS we need to establish a connection


to it
• A connection is established by creating an instance of the PDO class
• The constructor for the PDO class accepts arguments that specify the
database source (DSN), username, password and additional options
$pdo = new PDO ( dsn , username , password , options );

• Upon successful connection to the database, the constructor returns an


instance of the PDO class
• The connection remains active for the lifetime of that PDO object
• Assigning NULL to the variable storing the PDO object destroys it and
closes the connection
$pdo = NULL

COMP519 Web Programming Lecture 29 Slide L29 – 15


The PDO Class 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 query() method of PDO objects can be used to execute


an SQL query
$result = $pdo->query(statement)
$result = $pdo->query("SELECT * FROM meetings")
• query() returns the result set (if any) of the SQL query as a
PDOStatement object
• The exec() method of PDO objects executes an SQL statement,
returning the number of rows affected by the statement
$rowNum = $pdo->exec(statement)
$rowNum = $pdo->exec("DELETE * FROM meetings")

COMP519 Web Programming Lecture 29 Slide L29 – 17


The PDO Class Queries and Processing of Results

Processing Result Sets


• To get a single row as an array from a result set stored in a
PDOStatement object, we can use the fetch() method
• By default, PDO returns each row as an array indexed by
the column name and 0-indexed column position in the row
$row = $result - > fetch ()
array ( ’ slot ’ = > 1 ,
’ name ’ = > ’ Michael North ’ ,
’ email ’ = > ’M . North@student . liverpool . ac . uk ’ ,
0 => 1,
1 = > ’ Michael North ’ ,
2 = > ’M . North@student . liverpool . ac . uk ’)
• After the last call of fetch() the result set should be released using
$rows = $result - > closeCursor ()

• 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

Processing Result Sets

• We can use a while-loop together with the fetch() method to iterate


over all rows in a result set
while ( $row = $result - > fetch ()) {
echo " Slot : " , $row [ " slot " ] , " <br >\ n " ;
echo " Name : " , $row [ " name " ] , " <br >\ n " ;
echo " Email : " , $row [ " email " ] , " <br > < br >\ n " ;
}

• Alternatively, we can use a foreach-loop


foreach ( $result as $row ) {
echo " Slot : " , $row [ " slot " ] , " <br >\ n " ;
echo " Name : " , $row [ " name " ] , " <br >\ n " ;
echo " Email : " , $row [ " email " ] , " <br > < br >\ n " ;
}

COMP519 Web Programming Lecture 29 Slide L29 – 19


The PDO Class Queries and Processing of Results

Processing Result Sets

• Using bindColumn() we can bind a variable a particular column in the


result set from a query
• columns can be specified by number (starting with 1!)
• columns can be specified by name (matching case)
• Each call to fetch() and fetchAll() will then update all the variables
that are bound to columns
• The binding needs to be renewed after each query execution

$result - > bindColumn (1 , $slot ); # bind by column no


$result - > bindColumn (2 , $name );
$result - > bindColumn ( ’ email ’ , $email ); # bind by column name
while ( $row = $result - > fetch ( PDO :: FETCH_BOUND )) {
echo " Slot : " , $slot , " <br >\ n " ;
echo " Name : " , $name , " <br >\ n " ;
echo " Email : " , $email , " <br > < br >\ n " ;
}

COMP519 Web Programming Lecture 29 Slide L29 – 20


The PDO Class Prepared Statements

Prepared Statements

• The use of parameterised prepared statements is preferable over queries


• Prepared statements are are parsed, analysed, compiled and optimised
only once
• Prepared statements can be executed repeatedly with different
arguments
• Arguments to prepared statements do not need to be quoted and
binding of parameters to arguments will automatically prevent SQL
injection
• PDO can emulate prepared statements for a DBMS that does not
support them
• MySQL supports prepared statements natively, so PDO emulation
should be turned off
$pdo - > setAttribute ( PDO :: ATTR_EMULATE_PREPARES , FALSE );

COMP519 Web Programming Lecture 29 Slide L29 – 21


The PDO Class Prepared Statements

Prepared Statements: SQL Templates

• An SQL template is an SQL query (as a string) possibily containing


either
• named parameters of the form :name, where name is a PHP identifier, or
• question marks ?
for which values will be substituted when the query is executed
$tpl1 = " select slot from meetings where
name =: name and email =: email " ;
$tpl2 = " select slot from meetings where name =? " ;

• The PDO method prepare() turns an SQL template into prepared


statement (by asking the DBMS to do so)
• on success, a PDOStatement object is returned
• on failure, FALSE or an error will be returned

$stmt1 = $pdo - > prepare ( $tpl1 );


$stmt2 = $pdo - > prepare ( " select * from fruit where col =? " );

COMP519 Web Programming Lecture 29 Slide L29 – 22


The PDO Class Prepared Statements

Prepared Statements: Binding

• We can bind the parameters of a PDOStatement object to a value


using the bindValue() method
• Named parameters are bound by name
• Question mark parameters are bound by position (starting from 1!)
• the datatype of the value can optionally be declared
(to match that of the corresponding database field)
• the value is bound to the parameter at the time bindValue() is executed

$stmt1 - > bindValue ( ’: name ’ , ’ Ben ’ , PDO :: PARAM_STR );


$email = ’ bj1@liv . ac . uk ’;
$stmt1 - > bindValue ( ’: email ’ , $email );
$stmt2 - > bindValue (1 ,20 , PDO :: PARAM_INT );

COMP519 Web Programming Lecture 29 Slide L29 – 23


The PDO Class Prepared Statements

Prepared Statements: Binding

• We can bind the parameters of a PDOStatement object to a variable


using the bindParam() method
• Named parameters are bound by name
• Question mark parameters are bound by position (starting from 1!)
• the datatype of the value can optionally be declared
(to match that of the corresponding database field)
• the variable is bound to the parameter as a reference
• a value is only substituted when the statement is executed

$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 );

• It is possible to mix bindParam() and bindValue()


COMP519 Web Programming Lecture 29 Slide L29 – 24
The PDO Class Prepared Statements

Prepared Statements: Execution

• Prepared statements are executed using execute() method


• Parameters must
• previously have been bound using bindValue() or bindParam(), or
• be given as an array of values to execute
; take precedence over previous bindings
; are bound using bindValue()
• execute() returns TRUE on success or FALSE on failure
• On success, the PDOStatement object stores a result set (if appropriate)

$stmt1 - > execute ();


$stmt1 - > execute ( array ( ’: name ’ = > ’ Eve ’ , ’: email ’ = > $email ));
$stmt2 - > execute ( array (10));

COMP519 Web Programming Lecture 29 Slide L29 – 25


The PDO Class Transactions

Transactions

• There are often situations where a single ‘unit of work’ requires a


sequence of database operations
; e.g., bookings, transfers
• By default, PDO runs in ”auto-commit” mode
; successfully executed SQL statements cannot be ‘undone’
• To execute a sequence of SQL statements whose changes are
• only committed at the end once all have been successful or
• rolled back otherwise,
PDO provides the methods
• beginTransaction()
• commit()
• rollBack()

COMP519 Web Programming Lecture 29 Slide L29 – 26


The PDO Class 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

COMP519 Web Programming Lecture 29 Slide L29 – 27


The PDO Class Transactions

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;

// Query 1: Attempt to insert a payment record


$sql = " INSERT INTO payments ( user_id , amount ) VALUES (? , ?) " ;
$stmt = $pdo - > prepare ( $sql );
$stmt - > execute ( array ( $userId , $paymentAmount ));

// Query 2: Attempt to update the user ’s account


$sql = " UPDATE accounts SET balance = balance + ? WHERE id = ? " ;
$stmt = $pdo - > prepare ( $sql );
$stmt - > execute ( array ( $paymentAmount , $userId ));

// Commit the transaction


$pdo - > commit ();
} catch ( Exception $e ){
echo $e - > getMessage ();
// Rollback the transaction
$pdo - > rollBack ();
}
Based on http://thisinterestsme.com/php-pdo-transaction-example/
COMP519 Web Programming Lecture 29 Slide L29 – 28
Revision and Further Reading

Revision and Further Reading


Read
• Language Reference: Classes and Objects
http://php.net/manual/en/language.oop5.php
• The PDO Class
http://php.net/manual/en/class.pdo.php
of M. Achour, F. Betz, A. Dovgal, et al: PHP Manual. The PHP Group,
2017. http://uk.php.net/manual/en [accessed 07 Dec 2017]

COMP519 Web Programming Lecture 29 Slide L29 – 29

You might also like