comp519 web programming - handoutscgi.csc.liv.ac.uk/~ullrich/comp519/notes/comp519.pdf · web...

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

Upload: others

Post on 13-Aug-2020

13 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 1: Overview of COMP519

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 2: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

1 OverviewInformationLearning Outcomes

2 BackgroundInternet and WWW: A First DefinitionInternet and WWW: HistoryInternet and WWW: A Modern DefinitionDistributed Systems: Fundamental QuestionsDistributed Systems: Model-View-ControllerExamplesWeb Programming versus App Programming

COMP519 Web Programming Lecture 1 Slide L1 – 1

Page 3: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 4: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 5: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Overview Learning Outcomes

Learning Outcomes

By the end of this module, a student should

1 have an understanding of the range of programming techniques andlanguages available to organisations and businesses and be able tochoose an appropriate architecture for a web application;

2 be able to demonstrate abilities to design and implement maintainableweb sites;

3 be able to make informed and critical decisions regarding clientdevelopment using HTML and JavaScript;

4 be able to design and implement reasonably sophisticated server-sideapplications 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

Page 6: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 7: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Background Internet and WWW: A First Definition

Web 6= Internet

Internet

A physical network of networks connecting billions of computers and otherdevices using common protocols (TCP/IP) for sharing and transmittinginformation

World Wide Web [Old]

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

Key distinction:

• The internet is hardware plus protocols while the world wide web issoftware plus protocols

• The world wide web is an application using the internet to transmitinformation, just like many others, for example, email, SSH, FTP

COMP519 Web Programming Lecture 1 Slide L1 – 6

Page 8: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 9: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Background Internet and WWW: History

History (2)

• mid 1980s: Janet (UK network between research institutionswith 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 forfull 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

Page 10: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 11: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Background Internet and WWW: A Modern Definition

Web 6= Internet

World Wide Web [New]

An infrastructure that allows to easily develop, deploy, and use distributedsystems

Distributed systems

A system in which components located on networked computerscommunicate and coordinate their actions by passing messages in order toachieve a common goal

COMP519 Web Programming Lecture 1 Slide L1 – 10

Page 12: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Background Internet and WWW: A Modern Definition

Web 6= Internet

World Wide Web [New]

An infrastructure that allows to easily develop, deploy, and use distributedsystems

Key points:

• The internet already eased the development of distributed systems byproviding an appropriate infrastructure for that

• The world wide web eases the development and deployment ofinterfaces to such system via a combination of web pages andubiquitous web browers

• The world wide web then allows every (authorised) person toinstantaneously interact with such systems

• Search engines allow users to easily find distributed systems that areuseful to them

COMP519 Web Programming Lecture 1 Slide L1 – 11

Page 13: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 14: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Background Distributed Systems: Model-View-Controller

Distributed Systems: Model-View-Controller

We use the Model-View-Controller software design patternto discuss some of these questions in more detail:

• The model manages the behaviour anddata

• The view renders the model into a formsuitable for interaction

• The controller receives user input andtranslates it into instructions for themodel

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

Page 15: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Background Distributed Systems: Model-View-Controller

Distributed Systems: Model-View-Controller

We use the Model-View-Controller software design patternto discuss some of these questions in more detail:

• The model manages the behaviour anddata

• The view renders the model into a formsuitable for interaction

• The controller receives user input andtranslates it into instructions for themodel

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

Page 16: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Background Distributed Systems: Model-View-Controller

Distributed Systems: Model-View-Controller

We use the Model-View-Controller software design patternto discuss some of these questions in more detail:• The model manages the behaviour and

data

• The view renders the model into a formsuitable for interaction

• The controller receives user input andtranslates it into instructions for themodel

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

Page 17: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 18: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Background Examples

NLS

• 1960ies: Computer terminals start to be usedto interact with computers

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

A ‘networked’ computer system withGUI, off-line mode, ‘e-mail’,collaborative word processing,hypertext, video conferencingand mouse is demonstrated

(The picture shows one of several terminals connected toa mainframe computer)

Videos of the demo are available athttp://www.youtube.com/watch?v=JfIgzSoTMOs

COMP519 Web Programming Lecture 1 Slide L1 – 17

Page 19: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Background Examples

Thin clients, fat clients and cloud clients

• 1970ies: Computer terminals continue to dominate

• 1978: DEC VT100

Intel 8080 processor3 kb main memoryMonochrome graphics

Like NLS, this is a terminal connected to amainframe computer via serial lines

Key points:

• The data is stored on the mainframe computer which also computes thebehaviour 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

Page 20: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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: HyperStudioHyperCard clone for MS Windows

• 1991: Instant UpdateCollaborative 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

Page 21: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Background Examples

The Post-PC Era

• 1992: IBM Simon Personal Communicator (First smartphone)

• 1996: Nokia 9000 Communicator

• 2007: Apple iPhoneSamsung 32-bit RISC ARM128MB main memory4-16GB flash memory‘Apps’ / Web browser

• 2011: Google ChromebookIntel Atom processor2GB main memory16GB SSDWeb-based applications

In effect the Chromebook is a ’terminal’ connected toGoogle’s servers and others via a wireless network

COMP519 Web Programming Lecture 1 Slide L1 – 20

Page 22: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Background Examples

The Post-PC Era

• 2011: Google ChromebookIntel Atom processor2GB main memory16GB SSDWeb-based applications

Key points:

• The data is stored on a server farm (the ‘cloud’) which also computesthe 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

Page 23: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Background Examples

Thin clients, fat clients and cloud clients

• The Google Chromebook gives very similar answers to the fundamentalquestions 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

Page 24: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Background Web Programming versus App Programming

Web Programming versus App Programming

• Web Programming relies on web browsers as means to renderuser interfaces that are coded in HTML/CSS

• Web Programming relies on HTTP as the main protocol to exchangeinformation 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 aper-user basis

• App Programming relies on directly coded ‘native’ interfaces(Swift/Java)

• App Programming can rely on arbitrary protocols to exchangeinformation 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 situationCOMP519 Web Programming Lecture 1 Slide L1 – 23

Page 25: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 2: HTML (HTTP and HTML5 Basics)

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 26: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

3 HTTPIntroductionHistoryRequestsCharacter Encodings

4 HTMLIntroductionHistoryElements, Attributes and Values

5 Further Reading

COMP519 Web Programming Lecture 2 Slide L2 – 1

Page 27: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTTP Introduction

HTTP

• Web clients (web browsers) and web servers useHTTP (Hypertext Transfer Protocol) to communicate with each other

• More generally, HTTP is an application-layer protocol for distributedsystems

COMP519 Web Programming Lecture 2 Slide L2 – 2

Page 28: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTTP History

HTTP: History

• 1991 – HTTP 0.9first documented version of the protocol

• 1996 – HTTP/1.0first 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 forevery resource request

• 1997 – HTTP/1.1first 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 resourcesfrom the same server

• 1997-2014

• 2015

COMP519 Web Programming Lecture 2 Slide L2 – 3

Page 29: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTTP History

HTTP: History

• 1991 – HTTP 0.9

• 1996 – HTTP/1.0

• 1997 – HTTP/1.1

• 1997-2014Minor 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 arerequested

• HTTP/2 puts more emphasis on encrypted connections

COMP519 Web Programming Lecture 2 Slide L2 – 4

Page 30: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTTP Requests

HTTP Requests

Browser/Client −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−→ ServerGET /index.html HTTP/1.1

Host: www.example.com

Browser/Client ←−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− ServerHTTP/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:26https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol. [accessed 13 Sep 2017]

COMP519 Web Programming Lecture 2 Slide L2 – 5

Page 31: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 bitsTo retrieve a text, a sequence of bits needs to be decoded back to asequence 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

Page 32: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 bitsto 4x8 bits

• Within UTF-8, ANSI characters retain their encoding

Char ASCII ANSI UTF-8 Mac OS Roman

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

• When two systems exchange texts, then they need to agree whichencoding 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

Page 33: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Introduction

Hypertext and HTML

• The Hypertext Markup Language is the language for specifying thestatic part of a web page / elements of an interface

• The terms ‘hypertext’ and ‘hypermedia’ were coined by Ted Nelson in1963 as part of a model he developed for creating and using linkedcontent

• The idea of hypertext is attributed to Vannevar Bush who in in 1945described a hypothetical hypertext device called Memex in a magazinearticle

• 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 toplain text to provide additional information about document structure,content type, formatting, etc

COMP519 Web Programming Lecture 2 Slide L2 – 8

Page 34: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML History

HTML: Chronology

• 1989, Berners-Lee HTML 1Very basic, limited integration of multimedia added in 1993,web browser Mosaic supported many additional features

• 1994, IETF HTML 2.0Tried to standardize these additional features, but during 1994–96,web browsers Netscape and IE supported many new, divergent features

• 1995, IETF HTML 3.0Proposed, but never received approval

• 1996, W3C HTML 3.2Again attempted to unify all features into a single standardbut also dropped some tags that were in HTML 2.0

COMP519 Web Programming Lecture 2 Slide L2 – 9

Page 35: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML History

HTML: Chronology

• 1997, W3C HTML 4.0Tried 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.01Minor 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

Page 36: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML History

HTML: Chronology

• 2000, W3C XHTML 1.0Reformulation of all three HTML 4.01 variations in XMLUnlike HTML, anyone can define their own tags and attributesUnlike HTML, XHTML requires strict adherence to coding rules

• 2001, W3C XHTML 1.1Based on XHTML 1.0 Strict, introduces modules

COMP519 Web Programming Lecture 2 Slide L2 – 11

Page 37: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML History

HTML: Chronology

• 2014, W3C HTML5Shifts the focus from ‘semantically describing scientific documents’ to‘supporting web applications’

• 2016, W3C HTML 5.1Adds features for more responsive web apps and improved navigation

• 2017, W3C HTML 5.1 2nd Edition

COMP519 Web Programming Lecture 2 Slide L2 – 12

Page 38: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements, Attributes and Values

Elements, Attributes and Values

• The HTML5 specification defines a set of elements, attributes, andattribute values and their meanings (semantics)(there are more than 100 different elements alone)

• Authors of HTML documents should not use elements, attributes, orattribute 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 overlapsas little as possible; in HTML5 semantics and presentation are (mostly) separated

• For the full specification of the most recent version seeS. 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

Page 39: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 andvalue1,. . . ,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

Page 40: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 41: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 42: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements, Attributes and Values

Non-ASCII Characters

• The HTML5 specification defines a large number of named characterswith the general format &name;; allows access to non-ASCII and reserved characters

Exa

mp

les Named char Rendered as

&acirc; a&auml; a&alpha; α

Named char Rendered as

&lt; <

&gt; >

&amp; &

• Arbitrary characters can also be accessed using &#dec; and &#xhex;

where dec and hex are decimal and hexadecimal encodings for acharacter

Exa

mp

les Named char Rendered as&#x000E2; a&#x000E4; a&#x003B1; α

Named char Rendered as

&#x0003C; <

&#x0003E; >

&#x00026; &

COMP519 Web Programming Lecture 2 Slide L2 – 17

Page 43: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 orE-book http://library.liv.ac.uk/record=b2174141

COMP519 Web Programming Lecture 2 Slide L2 – 18

Page 44: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 3: HTML (HTLM5 Elements: Part 1)

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 45: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

6 HTMLHTML5 DocumentsThe head-elementThe body-element

7 HTML Elements for the BodyStructureHeadingsListsParagraphsDiv- and Span-elementAddressHyperlinks

8 Further Reading

COMP519 Web Programming Lecture 3 Slide L3 – 1

Page 46: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 thelanguage used in the document

<html lang="en-GB">

COMP519 Web Programming Lecture 3 Slide L3 – 2

Page 47: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 48: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML The body-element

Body

• The body-element contains the content that is to be displayed by aweb browser including• Articles, sections, footers, and navs

• Headings

• Paragraphs

• Lists and tables

• Images

• The body-element may contain PHP code that is executed by theweb server, producing HTML markup, that is then merged with theother content before being send to a web browser

• The body-element may contain JavaScript code that reacts to events inthe web browser and can dynamically change the content

COMP519 Web Programming Lecture 3 Slide L3 – 4

Page 49: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements for the Body Structure

Structuring the Body

• An article-element contains text that makessense on its own

• A section-element contains text on the sametheme

• A header-element contains introductory textfor a document, article, or section

• A footer-element typically contains theauthor of the document, copyright information,links to terms of use, contact information, etc

• A nav-element contains a set of navigationhyperlinks

• An aside-element contains related butindependent content to the articles/sections

header-element

nav-element

section-elements aside-article- elementelements

footer-element

Several of these could be

in one body-element

The elements are seman-

tic, not layout related

COMP519 Web Programming Lecture 3 Slide L3 – 5

Page 50: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements for the Body Structure

Structuring the Body

article-elements and section-elementsare typically nested inside each other:

• In an HTML document corresponding to ascientific paper one expects severalsection-elements (for introduction,conclusion, etc) inside one article-element

• In an HTML document corresponding to anewspaper one expects severalarticle-elements (one for each report/story)inside one section-element

The whole newspaper would consist of severalsection-elements (sport, business, etc)

header-element

nav-element

section-elements aside-article- elementelements

footer-element

COMP519 Web Programming Lecture 3 Slide L3 – 6

Page 51: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 sectionat the corresponding level, with h1 being the highest level andh6 the lowest

• Web browsers typically use font-size and font-weight to distinguishbetween 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

Page 52: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 53: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 54: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 55: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

COMP519 Web Programming Lecture 3 Slide L3 – 11

Page 56: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements for the Body Div- and Span-element

Div and Span

• The div-element and the span-element are used as containers for agroup of consecutive elements

• A common semantics or a common style can then be applied to allelements 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

Page 57: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 58: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 59: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements for the Body Address

Address

• The address element represents contact information for a personorganization

• It is one of the few elements in which the use of a br element makessense though paragraph, span or div could also be used

<address >

Dr Ullrich Hustadt <br >

Department of Computer Science <br>

University of Liverpool <br>

Email: [email protected]

</address >

COMP519 Web Programming Lecture 3 Slide L3 – 15

Page 60: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 isthe URL of a web page / resource that the web browser would visit ifthe user clicks on text

• The a-element has an optional attribute targetPossible values include• _blank:

Opens the linked web page in a new window or tabWith HTML5 alone it is not possible to force whether a window or a tab isopened

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

Page 61: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements for the Body Hyperlinks

Hyperlinks

• Instead of a whole document, a URL can also refer to a particularelement 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, uniquewithin 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 withid ID

COMP519 Web Programming Lecture 3 Slide L3 – 17

Page 62: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements for the Body Hyperlinks

Hyperlinks

http://w3.f.org/f.html<!DOCTYPE html >

<html lang="en -GB">

<head >

<title >Document A</title >

</head >

<body >

<h1 >Fruit </h1 >

<h2 id="a">Apples </h2 >

<h3 >Colour </h3 >

<h3 >Taste </h3 >

<h2 id="o">Oranges </h2 >

<h3 >Colour </h3 >

<h3 >Taste </h3 >

</body >

</html >

http://www.cb.com/b.html<!DOCTYPE html >

<html lang="en -GB">

<head >

<title >Document B</title >

</head >

<body >

<h1>Fruit </h1 >

<h2 id="p">Peaches <h2>

<h3 >Colour </h3 >

<h3 >Taste </h3 >

<h2 id="o">Other </h2>

<a href="http ://w3.f.org/f.html#a">

Apples </a>,

<a href="http ://w3.f.org/f.html#o">

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

Page 63: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 orE-book http://library.liv.ac.uk/record=b2174141

COMP519 Web Programming Lecture 3 Slide L3 – 19

Page 64: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 4: HTML (HTLM5 Elements: Part 2)

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 65: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

9 HTML Elements for the BodyText-level ElementsImagesFiguresTables

10 Further Reading

COMP519 Web Programming Lecture 4 Slide L4 – 1

Page 66: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements for the Body Text-level Elements

Text-level Elements

• A strong-element represents strong importance, seriousness, or urgencyfor its contentCan be used in a heading, caption, or paragraph to distinguish the mostimportant parts<strong >Beware of the dog </strong >

• A b-element highlights its content without marking it as importantYour <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

Page 67: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements for the Body Text-level Elements

Text-level elements

• A code-element represents a fragment of computer codeThe <code >begin </code > keyword indicates the start of a block

• The pre-element represents a block of preformatted text (structure inthe 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, orfunction

• The sup-element represents a superscript and the sub-elementrepresents 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

Page 68: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 69: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 100px ,

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

Page 70: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

• The figcaption-element represents a caption or legend for the figurein 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

Page 71: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 easilydistinguishable

COMP516 COMP517 COMP518 COMP5192015-16 66.0 66.3 73.0 71.92016-17 66.5 75.9 70.9 75.92017-18 66.2 69.6 70.9 66.4

Average marks on 1st Semester CSMS Modules

COMP519 Web Programming Lecture 4 Slide L4 – 7

Page 72: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements for the Body Tables

Tables

A table-element representsa whole table, including thecaption, consisting of

• a caption-element(optional)

• zero or morecolgroup-elements

• a thead-element(optional)

• zero or moretbody-elements or one ormore tr-elements

• a tfoot-element(optional) th td tdtfoot tr

th td tdtr

th td tdtr

th td tdtr

tbody

th th thtrthead

colgroup

caption

table

COMP519 Web Programming Lecture 4 Slide L4 – 8

Page 73: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements for the Body Tables

Tables

<table >

<caption >Average marks on 1st 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 rowsCell content is left-aligned

COMP519 Web Programming Lecture 4 Slide L4 – 9

Page 74: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements for the Body Tables

Tables

<table >

<caption >Average marks on 1st 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 rowsCell content is left-aligned

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

COMP519 Web Programming Lecture 4 Slide L4 – 10

Page 75: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements for the Body Tables

Table and Cell Attributes

• table-elements have a border attributeValue can be "" or "1"(browsers typically draw a border around table cells for both)

• td- and th-elements have attributes rowspan and colspan that specifyhow 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

Page 76: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 77: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 orE-book http://library.liv.ac.uk/record=b2174141

COMP519 Web Programming Lecture 4 Slide L4 – 13

Page 78: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 5: Cascading Style Sheets: Part 1

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 79: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

11 Style SheetsPrincipleHistoryOverview

12 Inline StylesOverviewProperties and Values

13 Further Reading

COMP519 Web Programming Lecture 5 Slide L5 – 1

Page 80: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Style Sheets Principle

Style Sheets

• HTML5 follows the separation of concerns design principle:a system should be divided into parts with functionality that overlapsas little as possible; in HTML5 semantics and presentation are (mostly) separated

• Concerns of presentation are dealt with usingCascading Style Sheets (CSS)

COMP519 Web Programming Lecture 5 Slide L5 – 2

Page 81: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Style Sheets History

CSS: History

• 1996, W3C CSS Level 1 (CSS1)Covers properties of fonts, texts, boxes; colours, pseudo classesVery 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, etcBrowser support still patchy

• 2011, W3C CSS Level 2 Revision 1 (CSS2.1)Fixes errors, removes features from CSS2 with insufficient browsersupports, adds others

• 2011 onwards, W3C CSS Level 3Follows a modular specification approach (lots of smaller specificationsinstead 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

Page 82: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Style Sheets Overview

Cascading Style Sheet

• Cascading Style Sheet are called cascading since they can be defined atdifferent levels:

1 Inline styles apply to a single HTML element2 Document style sheets (aka embedded styles aka internal style sheets)

apply to all elements within the body-element of an HTML document3 External style sheets can be linked and applied to numerous HTML

documents

• Lower-level (that is, lower-numbered) style sheets can typically overridehigher-level style sheets

• Style sheets can specify how HTML elements should be presented ondifferent screen types and/or in print

• Web users can specify personalised style sheets that can override thestyles associated with an HTML document

This can be useful, for example, to specify larger font sizes for visuallyimpaired users

COMP519 Web Programming Lecture 5 Slide L5 – 4

Page 83: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Style Sheets Overview

Cascading Style Sheet

Cascading Style Sheet cover three aspects of style and layout:

• Styling textDeals with fonts, text colors, list item style, etc

• Styling boxesDeals 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 boxesDeals with the relative position of boxes to each other

COMP519 Web Programming Lecture 5 Slide L5 – 5

Page 84: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Inline Styles Overview

Inline Styles

Using the style attribute, one can specify the presentation stylefor a single HTML element:Within the value of the style attribute, list a sequence ofproperty: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 seeMozilla 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

Page 85: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 86: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Inline Styles Properties and Values

CSS Values: Lengths

Relative Length Units

em current font-sizeex x-height of the current fontch width of ”0” (zero) in the current fontrem font-size of the root element (typically 16px)vw 1% of the width of the viewportvh 1% of the height of the viewportvmin 1% of viewport’s smaller dimensionvmax 1% of viewport’s larger dimension

The viewport is the user’s visible area of a web page, typically determinedby the size of the browser window

COMP519 Web Programming Lecture 5 Slide L5 – 8

Page 87: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Inline Styles Properties and Values

CSS Values: Lengths

Absolute Length Units

cm ‘centimeter’mm ‘millimeter’in ‘inch’ (1in = 96px = 25.4mm)

px pixel (1px = 1/96 in)pt point (1pt = 1/72 1in)pc pica (1pc = 12pt)

• A CSS pixel is the visual angle of onepixel on a device with a pixel density of96dpi and a distance from the reader of28in (0.2646mm).

• A web client choosed the number ofphysical pixels that best approximates aCSS pixel

• The multipliers between two absolutelength units are always as indicated above

COMP519 Web Programming Lecture 5 Slide L5 – 9

Page 88: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 89: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 90: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 blueR (red), G (green), B (blue) are hexadecimal characters (0-9, A-F)representing three numbers between 0 and 255, which in turn, specifythe 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 blueR (red), G (green), B (blue) are either decimal numbers between 0 and255 or percentages 0% to 100% that again specify the intensity of thatcolour

COMP519 Web Programming Lecture 5 Slide L5 – 12

Page 91: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Inline Styles Properties and Values

Inline Styles: Properties and Values

font-family: Courier, monospace

font-style: italic

font-size: 12pt | largerfont-weight: bold

color: AliceBlue | #F0F8FFbackground-color: AliceBlue | #F0F8FFtext-decoration: underline | nonetext-align: left | right | center | justifytext-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

Page 92: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Inline Styles Properties and Values

Inline Styles: Properties and Values

list-style-type: disc | circle | square | nonelist-style-type: decimal | lower-alpha | upper-romanmargin-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

Page 93: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Inline Styles Properties and Values

Inline Styles: Properties and Values

list-style-type: disc | circle | square | nonelist-style-type: decimal | lower-alpha | upper-romanmargin-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: 20px;">

<li style=" background -color:# ff9999; padding: 5px; margin: 5px">

one thing </li >

<li style=" background -color:# ff9999; padding: 5px; margin: 5px">

or another </li >

</ul >

COMP519 Web Programming Lecture 5 Slide L5 – 15

Page 94: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Inline Styles Properties and Values

Inline Styles: Properties and Values

border-width thin | thick | 5border-color Blue | #0000FFborder-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

Page 95: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 orE-book http://library.liv.ac.uk/record=b2174141

COMP519 Web Programming Lecture 5 Slide L5 – 17

Page 96: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 6: Cascading Style Sheets: Part 2

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 97: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

14 Document Style SheetsOverviewSelectors: Basic FormsInheritanceSpecificityMultiple ClassesRelative Selectors

15 Further Reading

COMP519 Web Programming Lecture 6 Slide L6 – 1

Page 98: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 mightend 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 moreproperty:value pairs separated by semi-colons and enclosed inside braces

• Selectors allow us to apply style definitions to all elements, a subclass ofelements, or individual elements throughout the document

COMP519 Web Programming Lecture 6 Slide L6 – 2

Page 99: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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;

text -align: center;

font -style: italic; }

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

</style >

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

The h1 selector means that the stylewill be applied to all h1-elements

The p.indented selector meansthat the style will only be applied top-elements of class indented

COMP519 Web Programming Lecture 6 Slide L6 – 3

Page 100: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Document Style Sheets Selectors: Basic Forms

Selectors: Basic Forms

• Selectors allow us to apply style definitions to all elements, a subclass ofelements, or individual elements throughout the document

• The basic forms of selectors are:

Selector ExampleSelects

* * All elementselement h1 All h1-elementselement, element h1, h2 All h1- and h2-elements.class .indented All elements with

class="indented"

element.class p.indented All p-elements withclass="indented"

#id #name The element with id="name"

COMP519 Web Programming Lecture 6 Slide L6 – 4

Page 101: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 3px of extra

bottom padding to make the underlining more visible */

.alert { text -decoration: underline;

padding -bottom: 3px;

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

Page 102: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Document Style Sheets Selectors: Basic Forms

Selectors, Classes and Inheritance

The style directive.alert { text -decoration: underline; padding -bottom: 10px;

background -color: orange; font -weight: bold; }

creates a style for the class “alert” that can (in principle) be applied toany 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

Page 103: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Document Style Sheets Selectors: Basic Forms

Selectors, Classes and Inheritance

The style directive.alert { text -decoration: underline; padding -bottom: 10px;

background -color: orange; font -weight: bold; }

creates a style for the class “alert” that can (in principle) be applied toany 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 stylewhile the second item is unaffected

• Note the vertical space between the first and second item due topadding-bottom

COMP519 Web Programming Lecture 6 Slide L6 – 7

Page 104: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Document Style Sheets Selectors: Basic Forms

Selectors, Classes, and Inheritance

The style directive.alert { text -decoration: underline; padding -bottom: 10px;

background -color: orange; font -weight: bold; }

creates a style for the class “alert” that can (in principle) be applied toany 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 thereis extra padding below the list

• The li-elements have inherited text decoration, font weight and backgroundcolour from the ol-element, but not padding-bottom

COMP519 Web Programming Lecture 6 Slide L6 – 8

Page 105: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Document Style Sheets Inheritance

Inheritance

• In CSS, inheritance controls what happens when no value is explicitlyspecified for a property of an element

• CSS distinguishes between inherited properties and non-inheritedproperties

• When no value for an inherited property has been specified for anelement, 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

Page 106: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Document Style Sheets Inheritance

Inheritance

• In CSS, inheritance controls what happens when no value is explicitlyspecified for a property of an element

• CSS distinguishes between inherited properties and non-inheritedproperties

• When no value for a non-inherited property has been specified for anelement, the property is given the initial, default value for that property

COMP519 Web Programming Lecture 6 Slide L6 – 10

Page 107: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Document Style Sheets Inheritance

Inheritance

• CSS distinguishes between inherited properties and non-inheritedproperties

• When no value for an inherited property has been specified for anelement, it inherits the value of that property from its parent element

• When no value for a non-inherited property has been specified for anelement, 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 listconstruct) while padding-bottom gets the initial value 0

COMP519 Web Programming Lecture 6 Slide L6 – 11

Page 108: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Document Style Sheets Inheritance

Inheritance

Consider the style directivetable { background -color: yellow;

border: 1px solid black; padding: 10px; margin: 10px; }

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

Page 109: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Document Style Sheets Inheritance

Inheritance

We can change what properties are inherited as follows:table { background -color: yellow;

border: 1px solid black; padding: 10px; margin: 10px; }

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 tdCOMP519 Web Programming Lecture 6 Slide L6 – 13

Page 110: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Document Style Sheets Inheritance

Debugging CSS

Google Chrome and Mozilla Firefox allow you to inspect individualHTML elements and can tell you how its properties come about

COMP519 Web Programming Lecture 6 Slide L6 – 14

Page 111: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Document Style Sheets Specificity

Specificity

• It is possible to have more than one kind of style directive that apply tothe same HTML element

• It is also possible that these style directives assign different values to thesame property

Example: Consider the style directivesh1 { 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 determinesbackground-color

• For other properties, the heading inherits from all three directivesCOMP519 Web Programming Lecture 6 Slide L6 – 15

Page 112: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Document Style Sheets Specificity

Specificity

• It is possible to have more than one kind of style directive that apply tothe same HTML element

• It is also possible that these style directives assign different values to thesame property

• For such ‘conflicting’ assignments, CSS uses specificity to determinewhich assignment applies to an element:

COMP519 Web Programming Lecture 6 Slide L6 – 16

Page 113: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Document Style Sheets Multiple Classes

Multiple Classes

• It is possible to declare that an HTML element belongs to more thanone class:

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

Example: Consider the style directivesp.alert { text -decoration: underline; padding -bottom: 10px;

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 andfrom p.blue

COMP519 Web Programming Lecture 6 Slide L6 – 17

Page 114: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Document Style Sheets Multiple Classes

Multiple Classes

Consider the style directives.red1 { color: red; background -color: yellow; margin: 5px; }

.blue { color: blue; margin: 5px; }

.red2 { color: red; background -color: yellow; margin: 5px; }

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 tothe same element, the assignment that comes last in the style sheet isapplied; problematic, as the style sheet might change

COMP519 Web Programming Lecture 6 Slide L6 – 18

Page 115: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Document Style Sheets Multiple Classes

Multiple Classes: Resolving ‘conflicts’

• ‘Conflicts’ between multiple classes can be resolved in advance bydefining 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: 5px; }

.blue { color: blue; margin: 5px; }

.red2 { color: red; background -color: yellow; margin: 5px; }

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

Page 116: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Document Style Sheets Relative Selectors

Relative Selectors

• It is possible to specify selectors that take into account the context inwhich a matching HTML element occurs:

Selector ExampleSelects

element element ol a All a elements inside ol elementselement>element ol>li All li elements where the parent

is an ol elementelement+element p+ol All ol elements placed immedi-

ately after a p elementelement∼element p∼ol All ol elements preceded by a

p element

COMP519 Web Programming Lecture 6 Slide L6 – 20

Page 117: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Document Style Sheets Relative Selectors

Relative Selectors: ExampleConsider the style directivesol 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

Page 118: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 determinewhat style to apply, e.g., relative selectors and attribute selectors

COMP519 Web Programming Lecture 6 Slide L6 – 22

Page 119: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 orE-book http://library.liv.ac.uk/record=b2174141

COMP519 Web Programming Lecture 6 Slide L6 – 23

Page 120: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 7: Cascading Style Sheets: Part 3

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 121: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

16 Document Style SheetsAttribute SelectorsPseudo ClassesPseudo Elements

17 External Style SheetsOverviewMedia Attribute and Adaptive Design

18 Further Reading

COMP519 Web Programming Lecture 7 Slide L7 – 1

Page 122: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Document Style Sheets Attribute Selectors

Attribute Selectors

• It is possible to specify selectors based on the presence or value of anattribute in HTML elements:

Selector Example Selects

[attr] [title] All elements witha title attribute

[attr=val] [target=_blank] All elements withtarget="_blank"

COMP519 Web Programming Lecture 7 Slide L7 – 2

Page 123: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Document Style Sheets Attribute Selectors

Attribute Selectors

• It is possible to specify selectors based on the presence or value of anattribute in HTML elements:

Selector Example Selects

[attr|=val] [lang|=en] All elements whose lang

attribute value begins withthe word "en" (delim " and -)

[attr^=val] [href^="https"] All elements whose href

attribute value begins withthe 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

Page 124: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Document Style Sheets Attribute Selectors

Attribute Selectors

• It is possible to specify selectors based on the presence or value of anattribute in HTML elements:

Selector Example Selects

[attr$=val] [href$=".pdf"] All elements whose href

attribute value ends withthe string ".pdf"

[attr*=val] [href*="csc"] All elements whose href

attribute value containsthe substring "csc"

[attr∼=val] [class∼=alert] All elements whose class

attribute value containsthe word "alert"

COMP519 Web Programming Lecture 7 Slide L7 – 4

Page 125: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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: 20px;

padding -bottom: 5px;

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

Page 126: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Document Style Sheets Pseudo Classes

Pseudo Classes

• A CSS pseudo class is a keyword added to a selector thatindicates 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

Page 127: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Document Style Sheets Pseudo Classes

Pseudo Classes

• A CSS pseudo class is a keyword added to a selector thatindicates 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

Page 128: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Document Style Sheets Pseudo Classes

Pseudo Classes

• A CSS pseudo class is a keyword added to a selector thatindicates a particular state of the selected element

• Pseudo classes include

Pseudo Class / Example Selects

:nth-child(n) Every p element that is thep:nth-child(1) first child of its parent

:nth-last-child(n) Every p element that is thep:nth-last-child(2) second last child of its parent

:nth-of-type(n) Every p element that is thep:nth-of-type(1) first p element of its parent

:nth-last-of-type(n) Every p-element that is thep:nth-last-of-type(2) second last p element of its parent

• There are a number of additional pseudo classes that relate to the stateof form elements

COMP519 Web Programming Lecture 7 Slide L7 – 8

Page 129: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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: 20px; }

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 intowhen the mousehovers overtext

COMP519 Web Programming Lecture 7 Slide L7 – 9

Page 130: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Document Style Sheets Pseudo Elements

Pseudo Elements

• A CSS pseudo element is a keyword added to a selector thatlets 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 ofevery p element

::first-line p::first-line Selects the first line ofevery p element

::selection ::selection Selects the portion of anelement that is selected bythe user

COMP519 Web Programming Lecture 7 Slide L7 – 10

Page 131: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Document Style Sheets Pseudo Elements

Pseudo Elements

• A CSS pseudo element is a keyword added to a selector thatlets 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 everyul element (experimental)

::before h1::before Creates a pseudo element as firstchild of every h1 element

::after h1::after Creates a pseudo element as lastchild of every h1 element

COMP519 Web Programming Lecture 7 Slide L7 – 11

Page 132: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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: 0px;

margin -left: 0px; }

.custom -counter li { counter -increment: step -counter;

padding -bottom: 10px; }

.custom -counter li:: before {

content: counter(step -counter ); margin -right: 5px;

background -color: gold; color: white;

font -weight: bold; padding: 3px 8px;

border -radius: 17px;

}

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

Page 133: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 propagatesautomatically to all HTML documents that use that style sheet

• External style sheets represent the best separation of content andpresentation

COMP519 Web Programming Lecture 7 Slide L7 – 13

Page 134: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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: 2em; }

COMP519 Web Programming Lecture 7 Slide L7 – 14

Page 135: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

External Style Sheets Overview

External Style Sheets

• Ideally, the developers of a website will place all style directives in one ormore external style sheets

• All web pages of that website will then link to those style sheets in orderto 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 andsemantic markup of the pages,the presentation is left to the pre-defined styles

COMP519 Web Programming Lecture 7 Slide L7 – 15

Page 136: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 commonto use one that specifies styles for a web browser and another forprinting

• The media attribute of the link element allows to selectwhich 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/stylesdepending on media features

COMP519 Web Programming Lecture 7 Slide L7 – 16

Page 137: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

External Style Sheets Media Attribute and Adaptive Design

The Media Attribute

• The value of the media-attribute is a string that specificies a booleancombination 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 |max-resolution

resolution in dpi

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

Page 138: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 139: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 orE-book http://library.liv.ac.uk/record=b2174141

COMP519 Web Programming Lecture 7 Slide L7 – 19

Page 140: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 8: Cascading Style Sheets: Part 4

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 141: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

19 Layout Via DivisionsRelevant Properties

20 CSS Grid LayoutOverviewDefining a Grid LayoutPlacing Elements on a GridExample

21 CSS Flexbox LayoutOverviewDefining a Flexbox LayoutExample

22 Adaptive versus Responsive Design

23 Further Reading

COMP519 Web Programming Lecture 8 Slide L8 – 1

Page 142: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Layout Via Divisions

Layout Via Divisions: Overview

• For a long time, web page layout was based on the extensive use ofdiv elements

• A web page would typically consist of roughly a handful of div elementsas 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

Page 143: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Layout Via Divisions Relevant Properties

Divisions and Properties (1)

• By default, a div element takes up the whole width of a browserwindow 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 element1000px

90% 90% of the width of the containing element

height Height of an element200px

10% 10% of the height of the containing element

margin All four margins of an elementauto centre horizontally within containing element

COMP519 Web Programming Lecture 8 Slide L8 – 3

Page 144: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Layout Via Divisions Relevant Properties

Divisions and Properties (1)

• By default, a div element takes up the whole width of a browserwindow 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 floatleft element floats to the left of its containerright element floats to the right of its container

clear Whether and how an element must be (cleared)below floating elemntsleft element moves down to clear past left floatsright element moves down to clear past right floatsboth element moves down to clear past all floats

COMP519 Web Programming Lecture 8 Slide L8 – 4

Page 145: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Layout Via Divisions Relevant Properties

Layout Via Divisions: Example (1)

A common layout of the top-leveldiv elements is the following

with the width of header, nav,main, footer fixed to a valuebetween 900px and 1000px

<body >

<div id=" header">

header

</div >

<div id="nav">

nav

</div >

<div id="main">

<div id=" content">

content

</div >

<div id="ads">

ads

</div >

</div >

<div id=" footer">

footer

</div >

</body >

COMP519 Web Programming Lecture 8 Slide L8 – 5

Page 146: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Layout Via Divisions Relevant Properties

Layout Via Divisions: Example (1)

A common layout of the top-leveldiv elements is the following

with the width of header, nav,main, footer fixed to a valuebetween 900px and 1000px

#header { width: 1000px;

height: 100px;

background -color: blue;

margin: auto; }

#nav { width: 1000px;

height: 50px;

background -color: green;

margin: auto; }

#main { width: 1000px;

margin: auto; }

#content { width: 800px;

height: 400px;

background -color: yellow;

float: left; }

#ads { width: 200px;

height: 400px;

background -color: orange;

float: right; }

#footer { width: 1000px;

height: 50px;

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

Page 147: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Layout Via Divisions Relevant Properties

Layout Via HTML5 Elements

• In the example, we assigned unique a id to each div element andassociated 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 elementslike header, nav, etc instead of div elements

• We would then associate a style directive with eachof those elements

header { width: 1000px;

height: 100px;

background -color: blue;

margin: auto; }

nav { width: 1000px;

height: 50px;

background -color: green;

margin: auto; }

<body >

<article >

<header >

</header >

<nav >

</nav >

<section >

</section >

<aside >

</aside >

<footer >

</footer >

</article >

</body >

COMP519 Web Programming Lecture 8 Slide L8 – 7

Page 148: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 canmove 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 documentfixed The element is removed from the

normal document flow;no space is created for the element in thepage layout;it is positioned relative to the screen’sviewport using properties top, bottom left,right and does not move when scrolled

COMP519 Web Programming Lecture 8 Slide L8 – 8

Page 149: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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, specifiesthe distance between the element’s top edge and the topedge of its containing block10px 10px off top edge

bottom Analogous to top for the element’s bottom edge and thebottom edge of its containing block20% 20% of the width of the containing block

left Analogous to top for the element’s left edge and the leftedge of its containing blockauto

right Analogous to right for the element’s left edge and theleft edge of its containing blockinherit inherit from parent element

COMP519 Web Programming Lecture 8 Slide L8 – 9

Page 150: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Layout Via Divisions Relevant Properties

Fixed Positioning: Example

We want to achieve the same lay-out as before but with header, navand footer fixed in position

Wo do so with slightly differentapproaches used in the style direc-tives for each of these three ele-ments

header { width: 1000px;

height: 100px;

background -color: blue;

position: fixed;

top: 0px;

left: 50%;

margin -left: -500px; }

nav { width: 1000px;

height: 50px;

background -color: green;

position: fixed;

top: 100px;

left: 0px;

right: 0px;

margin: auto; }

article { width: 1000px;

padding -top: 142px;

margin: 0 auto; }

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

COMP519 Web Programming Lecture 8 Slide L8 – 10

Page 151: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Layout Via Divisions Relevant Properties

Fixed Positioning: Example

We want to achieve the same lay-out as before but with header, navand footer fixed in position

Wo do so with slightly differentapproaches used in the style direc-tives for each of these three ele-ments

section { width: 800px;

height: 1000px;

background -color: yellow;

float: left;

}

aside { width: 200px;

height: 1000px;

background -color: orange;

float: right;

}

footer { width: 1000px;

height: 50px;

background -color: blue;

position: fixed;

bottom: 0px;

left: 50%;

transform: translate ( -50% ,0%);

}

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

COMP519 Web Programming Lecture 8 Slide L8 – 11

Page 152: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Layout Via Divisions Relevant Properties

Adaptive Design Revisited

• One fixed, rigid layout is unlikely to be suitable for every medium that auser might use to access an HTML document

• We have seen that the media-attribute of the link element allows us toselect 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 arelargely 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

Page 153: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Layout Via Divisions Relevant Properties

Importing CSS style files

• The @import CSS at-rule is used to import style directivesfrom other style sheets

@import url;

@import url list-of-media-queries;

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 directivesexcept @charset rules

• A @charset CSS at-rule specifies the character encodingused 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 charactersCOMP519 Web Programming Lecture 8 Slide L8 – 13

Page 154: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Layout Via Divisions Relevant Properties

Media Rules and Media Queries

• Within a style sheet, @media at-rules can used to conditionally applystyles to a document depending on the result of media queries

@media list-of-media-queries { 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: 10pt; }

}

@media screen and (resolution > 150 dpi) {

body { font-size: 13px; }

}

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

COMP519 Web Programming Lecture 8 Slide L8 – 14

Page 155: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Layout Via Divisions Relevant Properties

Feature Queries

• Within a style sheet, @support at-rules can be used to conditionallapply 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 browserused to process the style sheet supports this specific CSS featureand 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

Page 156: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 mostweb layouts can be seen as grids where elements are placed on one ormore grid cells

• Height and width of grid columns and grid rows will in general vary

Sample page layout Underlying grid andallocation 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

Page 157: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

These properties allow to specify a grid, including the size of each columnand each row

COMP519 Web Programming Lecture 8 Slide L8 – 17

Page 158: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 numbername name of a column / rowspan number number of tracks coveredspan name span until name is reachedauto automatic

COMP519 Web Programming Lecture 8 Slide L8 – 18

Page 159: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 160: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

CSS Grid Layout Example

CSS Grid Layout: ExampleWe want to replicate the same

layout as before:<body >

<article >

<header > </header >

<nav > </nav >

<section > </section >

<aside > </aside >

<footer > </footer >

</article >

</body >

article { display: grid;

grid -template -rows: 100px 50px auto 50px;

grid -template -columns: auto 800px 200px 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.htmlCOMP519 Web Programming Lecture 8 Slide L8 – 20

Page 161: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

CSS Flexbox Layout Overview

CSS Flexbox Layout

• CSS Flexbox Layout is a simpler layout system, typically used for partsof a web page, not the whole page

• Flexbox distinguishes between flex containers and flex items withinthose containers

• Unlike Grid, Flexbox distinguishes between a primary main axisand a secondary cross axis

• The main axis is not necessarily horizontal, its direction is determinedby flex-direction

COMP519 Web Programming Lecture 8 Slide L8 – 21

Page 162: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

CSS Flexbox Layout Defining a Flexbox Layout

Defining a Flexbox LayoutCSS properties of Flexbox include

• display: flex

defines an element as a flexbox container

• flex-direction: row | row-reverse |

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

Page 163: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 164: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 165: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 >

CSSa { text -align: center }

nav {

background -color: LightGreen;

display: flex;

flex -direction: row;

justify -content: space -around;

}

/* Narrow screen width */

@media all and (max -width: 900px) {

nav {

flex -direction: column;

}

}

Width = 1000px

Width = 900px

http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/layout4.htmlCOMP519 Web Programming Lecture 8 Slide L8 – 25

Page 166: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Adaptive versus Responsive Design

Adaptive versus Responsive Design

Adaptive Design

Uses a limited number of different web pages and/or different stylesdepending 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

Page 167: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Adaptive versus Responsive Design

Adaptive versus Responsive Design

Adaptive Design

Uses a limited number of different web pages and/or different stylesdepending 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 anymedia device with any media attributes at any time

• There are no generally agreed definitions of adaptive design andresponsive 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 effectCOMP519 Web Programming Lecture 8 Slide L8 – 27

Page 168: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 ofcolour-blindness; avoid red/green colour combinations

• Remember that some people use screen readers to read the content ofweb pages; always include alt properties for images

COMP519 Web Programming Lecture 8 Slide L8 – 28

Page 169: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 linksas they can slow down the download of your page

• Do not rely on specific window size or specific font size for layout as theuser might change those; use an adaptive or responsive design

• Break a large web page into several smaller ones or provide a menu fornavigation

• Utilise style sheets to make changes to style and layout easy and ensureconsistency across a set of web pages

• Stick to standard features and test several browsers

COMP519 Web Programming Lecture 8 Slide L8 – 29

Page 170: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 171: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 9: HTML (HTML5 Elements: Part 3)

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 172: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

24 HTML Elements for the BodyFormsForm Controls

25 Further Reading

COMP519 Web Programming Lecture 9 Slide L9 – 1

Page 173: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements for the Body Forms

Forms

• A form is an element that contains form controls, such astext fields, buttons, checkboxes, range controls, or color pickers

• Forms allow users to enter data which can then be sent to a web serverfor 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 theform controls will be send to the URL in action using the HTTPrequest method in method with encoding type enctype

COMP519 Web Programming Lecture 9 Slide L9 – 2

Page 174: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements for the Body Forms

Forms

• A form is an element that contains form controls, such astext fields, buttons, checkboxes, range controls, or color pickers

• HTML5 introduced a number of additional form controls and attributesfor 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

Page 175: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements for the Body Forms

Label

• In order for a form to be usable, each form control needs be beaccompanied by an indication of what it is for or how it should be usedExample: ‘Surname’ or ‘Enter your surname’ next to a field into whichyou 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 eitherusing its for attribute or by putting the form control inside the labelelement 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

Page 176: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements for the Body Form Controls

Input

• The input element represents a ‘field’ that allows the user to enterdata of a certain type

• The type attribute of an input element determine what type of datacan be entered and in what form

Value of Data Formtype type control

text Text with no line breaks Text fieldtel Phone number Text fielddate Date (Year/Month/Day) Date controlemail E-mail address Text fieldfile Zero or more files Button and file selectorcolor sRGB color Button and color pickernumber Floating-point number Text field or spinnerpassword Password Text field with obscured input

COMP519 Web Programming Lecture 9 Slide L9 – 5

Page 177: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements for the Body Form Controls

Input

• The input element represents a ‘field’ that allows the user to enterdata of a certain type

• The type attribute of an input element determine what type of datacan be entered and in what form

Value of Data Formtype type control

checkbox A set of zero or more valuesfrom a predefined list

Checkbox

radio An enumerated value Radio buttonbutton Buttonsubmit Initiates form submission Buttonreset Resets form Button

• Depending on the value of the type attribute, an input element willhave additional attributes that define its behaviour

COMP519 Web Programming Lecture 9 Slide L9 – 6

Page 178: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements for the Body Form Controls

Input

• The input element represents a ‘field’ that allows the user to enterdata of a certain type

• Depending on the value of the type attribute, an input element willhave 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

Page 179: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 wherename is the value of the name attribute of one of the form controls andvalue 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.phpCOMP519 Web Programming Lecture 9 Slide L9 – 8

Page 180: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 orby 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 thespecified min and max values; 1.9e8 is accepted and studentid=1.9e8 send to process.php

COMP519 Web Programming Lecture 9 Slide L9 – 9

Page 181: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 182: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 buttonsends level=UG and comment=None to process-comments.php

• Activating the hyperlink underlying ‘the first form’ focuses input onthe form with id c1

• Entering ‘None’ into the second form and activating the submit buttonsends level=PG and comment=None to process-comments.php

• Activating the hyperlink underlying ‘the second form’ focuses input onthe form with id c2

; name and id serve different purposesstill, programmers often use the same value for bothunless this is not possible (as in the example above)

COMP519 Web Programming Lecture 9 Slide L9 – 11

Page 183: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements for the Body Form Controls

Input: Submit

• An input element with type=submit represents a button that, whenactivated, 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

Page 184: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 bothName and Essay have been filled in; if so, the text entered will be sendto 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 operationsdepending on the value of action

COMP519 Web Programming Lecture 9 Slide L9 – 13

Page 185: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 bothName and Essay have bene filled in; if so, the text entered will be sendto 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 specificallyto perform the respective function

COMP519 Web Programming Lecture 9 Slide L9 – 14

Page 186: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements for the Body Form Controls

Input: Number

• An input element with type=number represents a one line plain textfield 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

Page 187: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements for the Body Form Controls

Input: Text

• An input element with type=text represents a one line plain text fieldfor 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

Page 188: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements for the Body Form Controls

Input: Password

• An input element with type=password represents a one line plaintext field for the element’s value

• Same as an input element with type=text, except that thw webbrowser 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

Page 189: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 onwhich checkboxes have been checked

COMP519 Web Programming Lecture 9 Slide L9 – 18

Page 190: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements for the Body Form Controls

Input: Radio

• A set of input elements with type=radio represents a radio buttongroup 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

Page 191: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements for the Body Form Controls

Input: Radio

• If no radio button within a group is selected when the associated form issubmitted, 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 issubmitted, 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

Page 192: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 activatethe submit button right away, no values will be send to process.php

; if we want to pre-select a button, then we shouldset the checked attribute for one of the elements

• If we select the first button and then activate the button, thencontact=email will be send to process.php

COMP519 Web Programming Lecture 9 Slide L9 – 21

Page 193: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 194: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements for the Body Form Controls

Select

• A select element represents a drop-down menu with pre-definedoptions between which the user must select

• The content of a select element consists of a list of option elementsthat 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

Page 195: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

HTML Elements for the Body Form Controls

Select

• A select element represents a drop-down menu with pre-definedoptions 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 elementsthat 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

Page 196: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 197: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 198: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 notdesirable ; the user does not need to make a conscious choice• Adding a default option with empty value and adding the attributerequired to the select element forces the user to make a consciouschoice

COMP519 Web Programming Lecture 9 Slide L9 – 27

Page 199: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 orE-book http://library.liv.ac.uk/record=b2174141

COMP519 Web Programming Lecture 9 Slide L9 – 28

Page 200: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 10: JavaScript (Part 1)

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 201: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

26 JavaScriptMotivationOverviewExampleScriptsType System

27 Further Reading

COMP519 Web Programming Lecture 10 Slide L10 – 1

Page 202: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

JavaScript Motivation

JavaScript: Motivation

• HTML/CSS is sufficient for HTML documents aimed atdisseminating information that does not change too frequently

• Web pages documents that remain the same each time they areaccessed are called static web pages; HTML/CSS is sufficient for static web pages

• In order to develop interactive/reactive web pages we must integrateprogramming 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 orlinked 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

Page 203: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

JavaScript Motivation

Scripting languages

Script

A user-readable and user-modifiable program that performs simpleoperations and controls the operation of other programs

Scripting language

A programming language for writing scripts

COMP519 Web Programming Lecture 10 Slide L10 – 3

Page 204: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 representationsmay be performed ‘behind the scenes’ as an optimisation

• Presence of a suitable runtime environment is required for the executionof 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 thathas been fully pre-compiled to machine code

COMP519 Web Programming Lecture 10 Slide L10 – 4

Page 205: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

JavaScript Motivation

Scripting languages: Properties

• Variables, functions, and methodstypically 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 timethrough 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

Page 206: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

JavaScript Motivation

Scripting languages: Properties

• The evolution of a scripting language typically startswith 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 constructsas it is used for a wider range of purposes

• These additional language constructs may or may not fit well togetherwith the original core and/or may duplicate existing language constructs

• During this evolution of the language, backward compatibilitymay or may not be preserved

; Language design of scripting languages is often sub-optimal

COMP519 Web Programming Lecture 10 Slide L10 – 6

Page 207: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 andexecuted by the user’s web browser; code is visible to the user/client

• allows for better interactivity compared to server-side scripting as reactiontime is improved and data exchange with the server can be minimised

• a web browser may not support JavaScript orthe 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 andthe client’s computing power

COMP519 Web Programming Lecture 10 Slide L10 – 7

Page 208: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 209: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

JavaScript Overview

JavaScript: History

• originally developed by Brendan Eich at Netscapeunder the name Mocha

• first shipped together with Netscape browser in September 1995under the name LiveScript

• obtained its current name in December 1995 under a deal betweenNetscape 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 ownpeculiarities

• is a dialect of ECMAScript, a scripting language standardised in theECMA-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

Page 210: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

JavaScript Overview

JavaScript: Use

Website Client-Side Server-Side Database

Google JavaScript C, C++, Go, Java,Python, PHP

BigTable, MariaDB

Facebook JavaScript Hack, PHP, Python,C++, Java, . . .

MariaDB, MySQL,HBase Cassandra

YouTube Flash,JavaScript

C, C++, Python, Java,Go

BigTable, MariaDB

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

Page 211: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 notenabled or supported by the web browser, can be specified in anoscript-element

• File must be stored in a directory accessible by the web server, forexample $HOME/public_html, and be readable by the web server

COMP519 Web Programming Lecture 10 Slide L10 – 11

Page 212: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

JavaScript Scripts

JavaScript scripts

• JavaScript scripts are embedded into HTML documents and areenclosed 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

Page 213: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 operationsthat 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 operationto refer to an argument of the operation

COMP519 Web Programming Lecture 10 Slide L10 – 13

Page 214: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Type

Variable Value Type

must match

• 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

Page 215: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 216: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 qndthe 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 adjustedautomatically (if possible)

COMP519 Web Programming Lecture 10 Slide L10 – 16

Page 217: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 andthe 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 adjustedautomatically (if possible)

add(519, 1.9e3) // returns the number 2419 = 519+1900

add(’519’,"1.9e3") // returns the string ’5191.9e3 ’

add(519, ’1.9e3 ’) // returns the string ’5191.9e3 ’

add(true , 1.9e3) // returns the number 1901

; makes programming easier; potentially leads to more bugs

COMP519 Web Programming Lecture 10 Slide L10 – 17

Page 218: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 orE-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 orE-book http://library.liv.ac.uk/record=b2238913

COMP519 Web Programming Lecture 10 Slide L10 – 18

Page 219: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 11: JavaScript (Part 2)

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 220: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

28 Primitive Data TypesBooleansNumbersStrings

29 Arrays Literals

30 Storing ValuesVariablesAssignmentsConstants

31 Determining the Type of a Value

32 Further Reading

COMP519 Web Programming Lecture 11 Slide L11 – 1

Page 221: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Types

Data Type / Datatype / Type

A set of computer represented values together with a set of operationsthat 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

Page 222: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Primitive Data Types Booleans

Booleans

• JavaScript has a boolean datatypewith 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)

true true B (true)true false B (false)false true A (false)false false A (false)

A B (A || B)

true true A (true)true false A (true)false true B (true)false false B (false)

A (! A)

true false

false true

COMP519 Web Programming Lecture 11 Slide L11 – 3

Page 223: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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) onlyas far as is necessary to determine the overall truth value of theexpression

(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

Page 224: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 includingMath.PI (case sensitive) 3.14159265358979323846NaN (case sensitive) ‘not a number’Infinity (case sensitive) ‘infinity’

COMP519 Web Programming Lecture 11 Slide L11 – 5

Page 225: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 additionalmathematical functionsMath.abs(number) absolute valueMath.ceil(number) round fractions upMath.floor(number) round fractions downMath.round(number) round fractionsMath.log(number) natural logarithmMath.random() random number between 0 and 1Math.sqrt(number) square root

COMP519 Web Programming Lecture 11 Slide L11 – 6

Page 226: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Primitive Data Types Numbers

Beware of Rounding

• Rounding is an arithmetic operation commonly included inprogramming 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 arecaused by log(0), sqrt(-1), 1/0, 0/0(we’ll do that in another lecture)

COMP519 Web Programming Lecture 11 Slide L11 – 7

Page 227: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Primitive Data Types Strings

Strings

• In JavaScript a string literal is a sequence of characters surrounded bysingle-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 insingle-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 sensein the context of HTML

\b (backspace) \f (form feed) \n (newline)

\r (carriage return) \t (tab)

COMP519 Web Programming Lecture 11 Slide L11 – 8

Page 228: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 229: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 230: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Arrays Literals

Array Literals

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

[2,3,5,7,11]

Each element of that list has an index positiongiven 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.1e1,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

Page 231: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Arrays Literals

Operators on Array Literals

• It is possible to access an element of an array literal via its indexposition: 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 arrayliteral: 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

Page 232: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Storing Values Variables

Variables

• A JavaScript identifier may consist ofletters, 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

Page 233: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 declarationby 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 variableonly assigning a value of a certain type gives a variable a type

COMP519 Web Programming Lecture 11 Slide L11 – 14

Page 234: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Storing Values Variables

Variables

• In JavaScript, the use of the value of a variable that is neither declarednor 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

Page 235: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 236: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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–10and does not have the desired effect in Safari before version 5.1.7nor Opera before version 12

COMP519 Web Programming Lecture 11 Slide L11 – 17

Page 237: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 238: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 orE-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 orE-book http://library.liv.ac.uk/record=b2238913

COMP519 Web Programming Lecture 11 Slide L11 – 19

Page 239: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 12: JavaScript (Part 3)

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 240: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

33 Type ConversionType CoercionType Casting

34 Comparison OperatorsEqualityLess and Greater ThanNumbers Revisited: NaN and InfinityEquality and Program Behaviour

35 ArraysDefinitionforEach-methodArray functions

COMP519 Web Programming Lecture 12 Slide L12 – 1

Page 241: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Type Conversion Type Coercion

Type Coercion

• JavaScript automatically converts a value to the appropriate type asrequired 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

Page 242: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 243: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 244: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 245: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 coercionexpr1 != 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 anumber

• 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 thevalueOf and toString methods of the objects to produce a primitivevalue for the object

• If two objects are compared, then the equality test is true only if bothrefer to the same object

COMP519 Web Programming Lecture 12 Slide L12 – 6

Page 246: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 notequal

TRUE iff expr1 is not equal to expr2,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

Page 247: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Comparison Operators Less and Greater Than

Comparison Operators

JavaScript’s comparison operators also apply type coercion to theiroperands and do so following the same rules as equality ==:

expr1 < expr2 Less than true iff expr1 is strictly less than expr2

after type coercionexpr1 > expr2 Greater than true iff expr1 is strictly greater than expr2

after type coercionexpr1 <= expr2 Less than

or equal totrue iff expr1 is less than or equal to expr2

after type coercionexpr1 >= expr2 Greater than

or equal totrue iff expr1 is greater than or equal to expr2

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

Page 248: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Comparison Operators Numbers Revisited: NaN and Infinity

Numbers Revisited: NaN and Infinity

• JavaScript’s number type includes constantsNaN (case sensitive) ‘not a number’Infinity (case sensitive) ‘infinity’

• The constants NaN and Infinity are used as return values forapplications 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

Page 249: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Comparison Operators Numbers Revisited: NaN and Infinity

Numbers Revisited: NaN and Infinity

• Equality and comparison operators need to be extended to coverNaN 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 numbersdo 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

Page 250: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 251: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 trueCOMP519 Web Programming Lecture 12 Slide L12 – 12

Page 252: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 equalCOMP519 Web Programming Lecture 12 Slide L12 – 13

Page 253: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Comparison Operators Equality and Program Behaviour

Equality

Note: The way in which more complex data structures are comparedis 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

Page 254: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 performedon 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 moreelements to an array

• Accessing an element of an array that has not been assigned a value yetreturns undefined

COMP519 Web Programming Lecture 12 Slide L12 – 15

Page 255: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 theoriginal 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 indicesbetween start and end

COMP519 Web Programming Lecture 12 Slide L12 – 16

Page 256: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 257: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 258: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Arrays forEach-method

forEach-method

• The recommended way to iterate over all elements of an array is afor-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) anda 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

Page 259: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 260: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 261: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 orE-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 orE-book http://library.liv.ac.uk/record=b2238913

COMP519 Web Programming Lecture 12 Slide L12 – 22

Page 262: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 13: JavaScript (Part 4)

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 263: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

36 Control StructuresConditional statementsSwitch statementsWhile- and Do While-loopsFor-loops

37 FunctionsDefining a FunctionCalling a functionVariable-length Argument ListsStatic VariablesExampleNested Function Definitions

38 JavaScript Libraries

COMP519 Web Programming Lecture 13 Slide L13 – 1

Page 264: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 265: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Control Structures Conditional statements

Control structures: conditional statements

JavaScript conditional statements do not allow for elsif- orelseif-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 onlya 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

Page 266: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Control Structures Switch statements

Control structures: switch statement

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

switch (expr) {

case expr1:

statements

break;

case expr2:

statements

break;

default:

statements

break;

}

• there can be arbitrarily many case-clauses

• the default-clause is optional but there can beat most one

• expr is evaluated only once and then comparedto expr1, expr2, etc using (loose) equality ==

• once two expressions are found to be equal thecorresponing clause is executed

• 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

Page 267: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 268: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 onestatement

Example:

// Compute the factorial of a given number

factorial = 1;

do {

factorial *= number --;

} while (number > 0);

COMP519 Web Programming Lecture 13 Slide L13 – 6

Page 269: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 270: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Control Structures For-loops

Control structures: for-loops

• In JavaScript, initialisation and increment can consist of morethan 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 declaredusing 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

Page 271: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Control Structures For-loops

Control Structures: break and continue

• The break command can also be used in while-, do while-, and for-loopsand 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 aloop 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

Page 272: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Functions Defining a Function

Functions

Function definitions can take several different forms in JavaScriptincluding:

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

statements }

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

statements }

• Such function definitions are best placed in the head sectionof 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 todetermine the number of parameters

COMP519 Web Programming Lecture 13 Slide L13 – 10

Page 273: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Functions Defining a Function

Functions

Function definitions can take several different forms in JavaScriptincluding:

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

statements }

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

statements }

• The return statementreturn value

can be used to terminate the execution of a function and to makevalue 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

Page 274: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Functions Calling a function

Calling a Function

A function is called by using the function name followed by a list ofarguments in parentheses

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

...

}

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

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

• If it is shorter, then any parameter without corresponding argumentwill 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

Page 275: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Functions Calling a function

‘Default Values’ for Parameters

• JavaScript does not allow to specify default values forfunction parameters

• Instead a function has to check whether an argument hasthe 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

Page 276: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 argumentspassed to a function

• As for any JavaScript array, arguments.length can be used todetermine 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

Page 277: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Functions Variable-length Argument Lists

Functions and Scope (1)

$x = "Hello"

function func1 () {

document.writeln ("1: "+$x)

}

function func2 () {

document.writeln ("2: "+$x)

$x = "Bye"

document.writeln ("3: "+$x)

}

func1 ()

func2 ()

document.writeln ("4: "+$x)

1: Hello

2: Hello

3: Bye

4: Bye

• A variable defined outside anyfunction is global

• A global variable can be accessedfrom any part of the script,including inside a function

COMP519 Web Programming Lecture 13 Slide L13 – 15

Page 278: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Functions Variable-length Argument Lists

Functions and Scope (2)

$x = "Hello"

function func1 () {

document.writeln ("1: "+$x)

}

function func2 () {

document.writeln ("2: "+$x)

var $x = "Bye"

document.writeln ("3: "+$x)

}

func1 ()

func2 ()

document.writeln ("4: "+$x)

1: Hello

2: undefined

3: Bye

4: Hello

• A variable defined outside anyfunction is global

• A global variable can be accessedfrom any part of the script,including inside a function

• To create a local variable inside afunction we need to declare it(and optionally initialise it)

COMP519 Web Programming Lecture 13 Slide L13 – 16

Page 279: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Functions Static Variables

JavaScript Functions and Static Variables

• JavaScript does not have a static keyword to declare a variable to bestatic 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 effortCOMP519 Web Programming Lecture 13 Slide L13 – 17

Page 280: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 281: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 282: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 283: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 giventhe 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 orat the end of the body section (see next slide)

• Web browers typically cache librariesCOMP519 Web Programming Lecture 13 Slide L13 – 21

Page 284: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 pageuntil 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 andexecute 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 inorder after parsing is finished

COMP519 Web Programming Lecture 13 Slide L13 – 22

Page 285: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

JavaScript Libraries

JavaScript Libraries: Example

~ullrich/public_html/sort.jsfunction 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

Page 286: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 orE-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 orE-book http://library.liv.ac.uk/record=b2238913

COMP519 Web Programming Lecture 13 Slide L13 – 24

Page 287: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 14: JavaScript (Part 5)

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 288: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

39 (User-defined) ObjectsObject LiteralsObject ConstructorsPrototype PropertyPublic and Private Static VariablesInheritanceClasses as Syntactic Sugar

40 Pre-defined ObjectsRegular ExpressionsStringDate

41 Further Reading

COMP519 Web Programming Lecture 14 Slide L14 – 1

Page 289: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 290: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 291: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 292: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

(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 objectCOMP519 Web Programming Lecture 14 Slide L14 – 5

Page 293: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

(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

Page 294: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

(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 areproperties (instance variables, members) of SomeObj

• The only difference is that instVar1 to instVar3 store strings whilemethod1 to method4 store functions

; every object stores its own copy of the methodsCOMP519 Web Programming Lecture 14 Slide L14 – 7

Page 295: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

(User-defined) Objects Prototype Property

Objects: Prototype Property

• All functions have a prototype property that can holdshared 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

Page 296: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

(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

Page 297: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

(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

Page 298: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 299: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

(User-defined) Objects Public and Private Static Variables

Private Static Variables

In order to create private static variables shared between objectswe can use a self-executing anonymous functionvar 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

Page 300: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 301: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

(User-defined) Objects Inheritance

Inheritance

• The prototype property can also be used to establishan 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

Page 302: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

(User-defined) Objects Classes as Syntactic Sugar

Classes as Syntactic Sugar

• ECMAScript 2015 introduced classes as syntactic sugar forprototype-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

Page 303: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 304: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 305: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Pre-defined Objects Regular Expressions

Pre-defined Objects: RegExp

• There is a range of special characters that match characters other thanthemselves 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 ofcharacters, special characters and ranges of characters

[^set] Matches any character not in set

/^[a-z]+$/ matches "abc", "x"

but not "0abc", "abc1", " ab", "AB", ""

/^\s*[a-z]+\s*$/ matches "abc", "x", " ab"

but not "0abc", "abc1", "AB", ""

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

but not "abc", "x", "0abc"COMP519 Web Programming Lecture 14 Slide L14 – 18

Page 306: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 307: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Pre-defined Objects String

Pre-defined Objects: String and RegExp

• JavaScript supports (Perl-like) regular expressions and the Stringobjects have methods that use regular expressions:• search(regexp)

matches regexp with a string and returns the start position of the firstmatch if found, -1 if not

• match(regexp)

– without g modifier returns the matching groups for the first matchor if no match is found returns null

– with g modifier returns an array containing all the matches forthe 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

Page 308: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 millisecondssince midnight of 1 January 1970

COMP519 Web Programming Lecture 14 Slide L14 – 21

Page 309: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 orE-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 orE-book http://library.liv.ac.uk/record=b2238913

COMP519 Web Programming Lecture 14 Slide L14 – 22

Page 310: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 15: JavaScript (Part 6)

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 311: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

42 Dynamic Web Pages Using JavaScriptWindow and Document ObjectsWindow Object: Properties and MethodsDialog BoxesInput Validation

43 Further Reading

COMP519 Web Programming Lecture 15 Slide L15 – 1

Page 312: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Dynamic Web Pages Using JavaScript Window and Document Objects

Window and Document Objects

JavaScript provides two objects that are essential to the creation ofdynamic 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 orframeset element

• allows properties of a window to be accessed and manipulated

• also allows new window objects to be created and manipulatedExample: window.open(’http://www.csc.liv.ac.uk’,’Home’)

• whenever an object method or property is referenced in a script withoutan object name and dot prefix it is assumed by JavaScript to be aproperty of the window object

Example: We can write alert() instead of window.alert()

COMP519 Web Programming Lecture 15 Slide L15 – 2

Page 313: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 314: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 315: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 316: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 317: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 318: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 319: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 320: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 321: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Dynamic Web Pages Using JavaScript Dialog Boxes

Window Object: Dialog boxes

• string prompt(message_string, default)

• creates a dialog boxdisplaying message_string

and an input field

• if a second argument defaultis given, default will beshown in the input field

• the box contains two buttons‘Cancel’ and ‘OK’

• if the user selects ‘OK’ thenthe current value entered inthe input field is returned as astring, otherwise null isreturned

Example:

var userName =

prompt ("What is your name?",

"")

COMP519 Web Programming Lecture 15 Slide L15 – 11

Page 322: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 323: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 324: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Dynamic Web Pages Using JavaScript Input Validation

User Input Validation

• A common use of JavaScript is the validation of user inputin an HTML form before it is processed:• check that required fields have not been left empty

• check that fields only contain allowed characters orcomply 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

Page 325: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 }

910 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

Page 326: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 orE-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 orE-book http://library.liv.ac.uk/record=b2238913

COMP519 Web Programming Lecture 15 Slide L15 – 16

Page 327: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 16: JavaScript (Part 7)

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 328: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

44 Dynamic Web Pages Using JavaScriptDocument Object and Document Object ModelAccessing and Manipulating HTML Elements

45 Event-driven ProgramsIntroductionEvents

46 Extended Example

47 Further Reading

COMP519 Web Programming Lecture 16 Slide L16 – 1

Page 329: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 ofdynamic web pages and interactive web applications:

document object

• an object-oriented representation of a web page (HTML document) thatis 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 andscripts to dynamically access and update the content, structure and styleof HTML, XHTML and XML documents

COMP519 Web Programming Lecture 16 Slide L16 – 2

Page 330: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Dynamic Web Pages Using JavaScript Document Object and Document Object Model

Document Object Model

Example:

The HTML table below<table >

<tbody >

<tr >

<td>Shady Grove </td >

<td>Aeolian </td >

</tr >

<tr >

<td>Over the River , Charlie </td >

<td>Dorian </td >

</tr >

</tbody >

</table >

is parsed into the following DOM

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

Page 331: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 mySecondTrElement = myTbodyElement.childNodes [1];

// remove its first td element

mySecondTrElement.removeChild(mySecondTrElement.firstChild );

// change the text content of the remaining td element

mySecondTrElement.firstChild.firstChild.data = "Peter ";

COMP519 Web Programming Lecture 16 Slide L16 – 4

Page 332: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 333: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 withinthe 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 adiv element between form and text field, we would now need to usedocument.form1.cdiv.celsius

COMP519 Web Programming Lecture 16 Slide L16 – 6

Page 334: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 335: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 changeBackgroundBlue(id) {

document.getElementById(id).style.background = "#00f";

document.getElementById(id). innerHTML = "blue";

}

function changeBackgroundRed(cell) {

cell.className = "RedBG ";

cell.innerHTML = "red";

}

</script ></head ><body >

<table border ="1"><tr >

<td id="0" onclick =" changeBackgroundBlue (’0’);">white </td >

<td id="1" onclick =" changeBackgroundRed(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

Page 336: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Event-driven Programs Introduction

Event-driven JavaScript Programs

• The JavaScript programs we have seen so farwere 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

Page 337: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 338: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 elementsfor 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 anHTML 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 sameelement for the same event

COMP519 Web Programming Lecture 16 Slide L16 – 11

Page 339: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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.removeEventListener) {

window.removeEventListener ("load", Hello)

} else {

window.detachEvent (" onload", Hello)

}

COMP519 Web Programming Lecture 16 Slide L16 – 12

Page 340: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 341: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Event-driven Programs Events

Events: Focus / Change

• A focus event occurs when a form field receives input focus by tabbingwith the keyboard or clicking with the mouse; onFocus attribute

• A change event occurs when a select, text, or textarea field loses focusand 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

Page 342: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Event-driven Programs Events

Events: Focus / Change

• A focus event occurs when a form field receives input focus by tabbingwith the keyboard or clicking with the mouse; onFocus attribute

• A change event occurs when a select, text, or textarea field loses focusand 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 =

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

Page 343: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 344: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 movesover an HTML element from outside that element; onMouseOver attribute

• A select event occurs when a user selects some of the text within a textor textarea field; onSelect attribute

• A submit event occurs when a user submits a form; onSubmit attribute

COMP519 Web Programming Lecture 16 Slide L16 – 17

Page 345: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 346: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Extended Example

Example: Two-Player Board Game

• We want to develop a two-player board gamealong the lines of Tic-Tac-Toe

• The full code is available athttp://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/jsBoard.html

• The interface will consist of a 3x3 table representing the board and asection 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

Page 347: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Extended Example

Example: Two-Player Board Game

• Following the Model-View-Controller paradigm we need a model of thegame, 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 board1 to represent a position taken by player 12 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

Page 348: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Extended Example

Example: Two-Player Board Game

• We need a function to show a message to the userand 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

Page 349: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 theHTML element / table cell on which it was triggered

COMP519 Web Programming Lecture 16 Slide L16 – 22

Page 350: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 thecurrent values of i and y

COMP519 Web Programming Lecture 16 Slide L16 – 23

Page 351: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Extended Example

Example: Two-Player Board Game

• Finally, we add some CSS directives to improve the visual appearanceof the game

<style >

td { border: 1px solid black;

width: 2em;

height: 2em;

text -align: center;

vertical -align: middle;

}

div.RedBG {

background -color: #f00;

}

div.GreenBG {

background -color: #0f0;

}

</style >

COMP519 Web Programming Lecture 16 Slide L16 – 24

Page 352: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

computerMove ();

processing = false

} } }

function sleep(ms) {

return new Promise(resolve => setTimeout(resolve , ms)) }

COMP519 Web Programming Lecture 16 Slide L16 – 25

Page 353: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Extended Example

Example: Two-Player Board Game

Possible improvements:

• We should detect that the board is full (free == 0) andend 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

Page 354: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 orE-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 orE-book http://library.liv.ac.uk/record=b2238913

COMP519 Web Programming Lecture 16 Slide L16 – 27

Page 355: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 17: Python (Part 1)

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 356: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

48 PythonOverviewExampleBasic SyntaxType System

49 Primitive Data TypesIntegersFloating-Point NumbersComplex NumbersStringsBooleans

50 Further Reading

COMP519 Web Programming Lecture 17 Slide L17 – 1

Page 357: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Python Overview

Python: History

• The implementation of Python was started in December 1989by 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 ofPython; it maintans the CPython reference implementation of Python

• Python 2.0 was released in October 2000

• Python 3.0 was released in October 2008with 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-orientedprogramming, design by contract, and logic programming

• There exist interpreters as well as compilers for Python

COMP519 Web Programming Lecture 17 Slide L17 – 2

Page 358: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Python Example

Python: Hello World

1 #!/ usr/bin/python3

2 # HelloWorld.py

3 # Our first Python script

45 print(" Hello World")

• On Unix/Linux systems, Python scripts begin with #! (called ‘hashbang’ 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

Page 359: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Python Basic Syntax

Basic Python Syntax

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

• 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

Page 360: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 361: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Python Type System

Python: Type System

• Python is both• a dynamically typed language:

a variable declaration does not include a type anda 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 appliedto a number

COMP519 Web Programming Lecture 17 Slide L17 – 6

Page 362: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Python Type System

Types

Data Type / Datatype / Type

A set of computer represented values together with a set of operationsthat 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

Page 363: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 00 2012 40 1263978

• Binary literals (base 2):A sequence of digits 0–1 prefixed by 0b or 0B0b10 0b01 0b0 0b11011011

• Octal literals (base 8):A sequence of digits 0–7 prefixed by 0o or 0O0o10 0O20 0o40 0o1263978

• Hexadecimal literals (base 16):A sequence of characters A–F and digits 0–9 prefixed by 0x or 0X0x10 0X20 -0xFF -0x1236A7F

• Negative integers are obtained by applying the unary - operation to apositive integer

COMP519 Web Programming Lecture 17 Slide L17 – 8

Page 364: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Primitive Data Types Integers

Integers

• Python 2 distinguishes betweenint (32-bit integers) andlong (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 ofarbitrary 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 0xCAFE_F00D 0b_0011_1111_0100

1_2_3_4_50 0xC0_F_F_EE 0b_00_11_1_0_01_0

• Python has no auto-increment ++ nor auto-decrement -- operator

COMP519 Web Programming Lecture 17 Slide L17 – 9

Page 365: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Primitive Data Types Floating-Point Numbers

Floating-point Numbers and Arithmetic Operators

• The Python immutable datatype float covers(64-bit) floating-point numbers1.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 intCOMP519 Web Programming Lecture 17 Slide L17 – 10

Page 366: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 allfunction 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 themavailable without the need for a prefix

from math import factorial

print factorial (5)

COMP519 Web Programming Lecture 17 Slide L17 – 11

Page 367: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Primitive Data Types Floating-Point Numbers

Additional Arithmetic Operators

• Additional arithmetic operators are available from the math module:math.fabs(number) absolute valuemath.ceil(number) round fractions upmath.floor(number) round fractions downmath.log(number) natural logarithmmath.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 modulerandom.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

Page 368: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Primitive Data Types Complex Numbers

Complex Numbers

• The Python immutable datatype complex covers complex numbers ofthe form

real + imagJ

where real and imag are floating-point numbersand J (or j) represents the square root of -1

• The cmath module provides additional arithmetic operators includingmath.log(number) natural logarithmmath.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

Page 369: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 370: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 ordinarycharacter

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

Page 371: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Primitive Data Types Strings

Strings

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

len(string)

Returns the length of a string as integerlen("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

Page 372: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 373: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 374: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 orE-book http://library.liv.ac.uk/record=b2174141

COMP519 Web Programming Lecture 17 Slide L17 – 19

Page 375: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 18: Python (Part 2)

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 376: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

51 Complex DatatypesListsSetsRangesList and Set Comprehension

52 Equality and Comparison Operators

53 Special Valuesnan and infNone

54 Determining the Type of a Value

55 Type Conversion

56 Further Reading

COMP519 Web Programming Lecture 18 Slide L18 – 1

Page 377: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 squarebrackets and it is of the mutable type list

• Each element of that list has an index position given by the number ofother 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.1e1, [True , 1.3+2j]]

| | | | | |

0 1 2 3 4 5

-6 -5 - 4 -3 -2 -1

COMP519 Web Programming Lecture 18 Slide L18 – 2

Page 378: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 anerror

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

Page 379: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 valueoccurs 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 occurrencesof an object in a list (using equality ==)

[2,3,2,4,2,5]. count (2) # returns 3

[2e0 ,3 ,2.0 ,2.0+0j,5]. count (2) # returns 3

COMP519 Web Programming Lecture 18 Slide L18 – 4

Page 380: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Complex Datatypes Lists

Operators on List Literals

• Operators min and max return the minimal and maximal element of alist 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 listliteral 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

Page 381: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Complex Datatypes Sets

The Set Type

• Python 3 has a mutable set type for unordered collections with noduplicate elements

• A set literal is a comma-separated list of values enclosed incurly 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, 1e0, 1.0+0j, 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

Page 382: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 383: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Complex Datatypes Ranges

The Range Type

• Python 3 has an immutable range type for sequencesof 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), andafter 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 rangesCOMP519 Web Programming Lecture 18 Slide L18 – 8

Page 384: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 andset comprehension to construct lists and sets

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

Page 385: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Complex Datatypes List and Set Comprehension

Equality and Comparison Operators

• Python provides the following equality and comparison operators

Op Meaning

== equal!= not equalis object identityis not negated object identity

Op Meaning

< strictly less than<= less than or equal> strictly greater than>= greater than or equal

• Objects of different types, except different numeric types,never compare equal

• The <, <=, > and >= operators will raise a TypeError when comparing acomplex number with another built-in numeric type or when the objectsare of different types that cannot be compared1.23e2 <= 12.3e1 + 0j ; TypeError

"123" < 124 ; TypeError

False < 1 ; True

COMP519 Web Programming Lecture 18 Slide L18 – 10

Page 386: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 wherea boolean expression is involved (e.g. conditional statements)

(9) contradicts that ”” will ‘evaluate’ to False in all situationswhere a boolean expression is involved

COMP519 Web Programming Lecture 18 Slide L18 – 11

Page 387: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Special Values nan and inf

nan and inf

• Since Python 3.5, the math module provides constantsmath.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 asarguments will return one of these constantsmath.inf + 1 ; math.inf math.inf / math.inf ; math.nan

math.nan + 1 ; math.nan 1 / math.inf ; 0.0

• For comparisons we getnan == 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

Page 388: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Special Values None

None

• The Python equivalent to JavaScript’s ‘undefined’ valueand 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

Page 389: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 390: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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") ; TypeErrorCOMP519 Web Programming Lecture 18 Slide L18 – 15

Page 391: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Type Conversion

Type Conversion

• Python has several functions for type conversion

• bool(value) converts value to an element of bool usingthe 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 ofcomplex

• 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

Page 392: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 orE-book http://library.liv.ac.uk/record=b2174141

COMP519 Web Programming Lecture 18 Slide L18 – 17

Page 393: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 19: Python (Part 3)

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 394: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

57 Storing ValuesVariablesAssignmentsConstants

58 Complex Datatypes Revisited

59 Control StructuresConditional StatementsWhile-loops

60 Further Reading

COMP519 Web Programming Lecture 19 Slide L19 – 1

Page 395: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Storing Values Variables

Variables / Names

• Strictly speaking, Python does not have variables,it has names

• A Python (variable) name may consist ofletters, 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

Page 396: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Storing Values Variables

Variables / Names

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

# 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 sensibleinitialisation value for it, None can be used

student_id = None

COMP519 Web Programming Lecture 19 Slide L19 – 3

Page 397: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 398: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Storing Values Assignments

Assignments

• The assignment of a name var to a value can be removed bydel(var)

; the variable reverts to being undefined andattempts 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

Page 399: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 400: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Storing Values Constants

Constants

• Python has no straightforward way of defining constants

COMP519 Web Programming Lecture 19 Slide L19 – 7

Page 401: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 onlists• 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 byspecifying 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 listCOMP519 Web Programming Lecture 19 Slide L19 – 8

Page 402: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 403: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Storing Values Constants

Lists

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

• sequence does not have to be a list, sorted can be applied to anysequence

• 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

Page 404: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Complex Datatypes Revisited

Lists

• The function zip(sequence1,...,sequenceN)returns a sequence of tuples, where the i-th tuple contains the i-thelement 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

Page 405: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Complex Datatypes Revisited

Tuples

• A tuple literal is a comma-separated list of values enclosed inparentheses and it is of type tuple

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

• Tuple literals can be assigned to variables

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

• 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

Page 406: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 pairsconsisting of a key and a value separated by a colon :surrounded by curly brackets

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

• 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 ’: ’185cm ’ }

print(dct[’name ’]) # prints ’Dave ’

dct[’height ’] = ’190cm ’ # ’height ’ now maps to ’190cm ’

dct[’age ’] += 1 # ’age ’ now maps to 24

dct[’surname ’] = ’Shield ’ # ’surname ’ maps to ’Shield ’

COMP519 Web Programming Lecture 19 Slide L19 – 13

Page 407: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Complex Datatypes Revisited

Dictionaries

• Accessing a key that is not in a dictionary results in an error:

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

print(dct[’job ’])

KeyError: ’job ’

• The operators in and not in can be used to check whether a key isin 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

Page 408: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 409: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 410: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 411: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 resultif_true_expr or if_false_expr are evaluated and returned

COMP519 Web Programming Lecture 19 Slide L19 – 18

Page 412: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Control Structures Conditional Statements

Switch Statements

• Python has no switch statement instead a conditional statementhas to be used

switch (expr) {

case expr1:

statements1

break;

case expr2:

statements2

break;

case expr3:

statements3

break;

default:

statements4

break;

}

if expr == expr1:

statements1

elif expr == expr2:

statements2

elif expr == expr3:

statements3

else:

statements4

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

COMP519 Web Programming Lecture 19 Slide L19 – 19

Page 413: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 discontinuesthe execution of the loop

• The continue command can be used to stop the execution of thecurrent iteration of a loop and to move to the next iteration

• A while-loop can have an optional else-clause that is executed if theloop 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

Page 414: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Control Structures While-loops

While-loops

• A while-loop can have an else-clause that is executed if the loop is notterminated 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

1

2

Loop stopped with 3

Statement after Loop

Output for value = 0

Break

Statement after Loop

COMP519 Web Programming Lecture 19 Slide L19 – 21

Page 415: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 orE-book http://library.liv.ac.uk/record=b2174141

COMP519 Web Programming Lecture 19 Slide L19 – 22

Page 416: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 20: Python (Part 4)

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 417: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

61 Control StructuresFor-loopsTry Statements

62 FunctionsDefining a FunctionCalling a FunctionVariable-length Argument ListsStatic VariablesNested Function Definitions

63 Further Reading

COMP519 Web Programming Lecture 20 Slide L20 – 1

Page 418: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 tovar1, . . . , varN: var1, ..., varN = E

; if there is more than one variable, then E must itself bea sequence with a matching number of elements

• The optional else-clause is executed after the last iteration of the loopunless the loop is left via a break, exception, or error

COMP519 Web Programming Lecture 20 Slide L20 – 2

Page 419: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Control Structures For-loops

For-loops

for i in range (3):

print(i)

0

1

2

for i in range (0,7,3):

print(i)

0

3

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

Page 420: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 421: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Control Structures For-loops

Break and Continue

• The break command be used in while- and for-loops and discontinuesthe execution of the loop

while value < 100:

if value == 0:

break;

value += 1

• The continue command stops the execution of the current iteration of aloop 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

Page 422: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Control Structures Try Statements

Try Statements

Python offers try statements to deal with exceptions(errors other than SyntaxErrors)

try:

suite

except exception:

suite

except exception:

suite

...

except:

suite

finally:

suite

• First, the try-clause is executed

• If no exception occurs, all except-clausesare skipped

• If an exception occurs, execution of thetry-clause stops and a matchingexcept-clause (if it exists) is executed

• An except-clause without exceptionmatches any exception

• The optional finally-clause is alwaysexecuted

COMP519 Web Programming Lecture 20 Slide L20 – 6

Page 423: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Control Structures Try Statements

Try Statements

import math

try:

z = x / y

except NameError:

# Either x or y was not inialised

z = None

except ZeroDivisionError:

# 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

Page 424: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Control Structures Try Statements

Else Clause Revisited

The example below illustrates the usefulness of else-clausesin 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

Page 425: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 takea variable number of arguments

• docstring is a string describing the function and will be returned byhelp(identifier) or identifier.__doc__

• suite is a non-empty sequence of statements

COMP519 Web Programming Lecture 20 Slide L20 – 9

Page 426: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

can be used to terminate the execution of a function and to make theoptional 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

Page 427: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Functions Calling a Function

Calling a Function

A function is called by using the function name followed by a list ofarguments in parentheses

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

suite

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

• Arguments are passed by assignmentparam1 = 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) # TypeErrorCOMP519 Web Programming Lecture 20 Slide L20 – 11

Page 428: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Functions Calling a Function

Calling a Function

A function is called by using the function name followed by a list ofarguments 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 8COMP519 Web Programming Lecture 20 Slide L20 – 12

Page 429: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 430: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Functions Variable-length Argument Lists

Variable-length Argument Lists

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

suite

• For a parameter **param2, param2 is initialised to a dictionary mappingany 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 enabledprintFile(’python1.py’,orientation=’landscape’) – Landscape option enabledprintFile(’python1.py’,duplex=’True’) – Duplex option enabledprintFile(’python1.py’,orientation=’landscape’, – Both Landscape and

duplex=’True’) Duplex option enabled

COMP519 Web Programming Lecture 20 Slide L20 – 14

Page 431: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Functions Variable-length Argument Lists

Variable-length Argument Lists

• When mixing ordinary parameters / arguments, keyword arguments andvariable-length argument lists, parameters and arguments need to occurin a particular order to work correctly• In a function definition we have

1 ‘Normal’ parameters2 *param1

3 **param2

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

• In a function call we have

1 ‘Normal’ (positional) arguments2 Keyword arguments

applyFunc(lambda x: 2*x,’list ’,1,2,3,debug=True)

COMP519 Web Programming Lecture 20 Slide L20 – 15

Page 432: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Functions Static Variables

JavaScript Functions and Static Variables

• Python does not have a static keyword to declare a variable to bestatic 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 publicCOMP519 Web Programming Lecture 20 Slide L20 – 16

Page 433: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Functions Nested Function Definitions

Nested Function Definitions

• Function definitions can be nested in Python

• By default, inner functions can not be invoked from outsidethe 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

Page 434: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 orE-book http://library.liv.ac.uk/record=b2174141

COMP519 Web Programming Lecture 20 Slide L20 – 18

Page 435: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 21: Python (Part 5)

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 436: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

64 FunctionsVariable Scope and FunctionsStatic Variables

65 ClassesDefining and Instantiating a ClassClass and Instance AttributesDeleting InstancesClass MethodsInheritanceMagic Methods

66 Further Reading

COMP519 Web Programming Lecture 21 Slide L21 – 1

Page 437: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 programin which we can validly refer to that variable (occurrence)

public class Test {

int x;

void method1 () {

... Code A...

int x;

int y;

... Code B...

}

void method2 () {

... Code C...

}

int z;

}

Where in this Java class can we validly referto the variables x, y and z, for example, printthem out?

• Can we refer to x, y, and z in method2()?Which occurrence of x do we refer to?

• Which occurrence of x would we refer to inmethod1() either in Code ...A... or...B...?

Such questions become even more complicatedwhen function definitions can be nested as inJavaScript and Python

COMP519 Web Programming Lecture 21 Slide L21 – 2

Page 438: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Functions Variable Scope and Functions

A Look Back to JavaScript

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

document.writeln(s+’: ’+a+’=’+k+’, ’+

b+’=’+l+’, ’+c+’=[’+m+’]<br >’)

}

function outer(x,y,z) {

function inner () {

state(’Inner(1)’,’x’,x,’y’,y,’z’,z)

x = 3

z[1] = 3

state(’Inner(2)’,’x’,x,’y’,y,’z’,z)

}

state(’Outer(1)’,’x’,x,’y’,y,’z’,z)

inner()

y = 4

z[2] = 4

state(’Outer(2)’,’x’,x,’y’,y,’z’,z)

}

u = 1; v = 2; w = [0,1,2]

state(’Main(1)’,’u’,u,’v’,v,’w’,w)

outer(u,v,w)

state(’Main(2)’,’u’,u,’v’,v,’w’,w)

Main(1):

u=1, v=2, w=[0,1,2]

Outer(1):

x=1, y=2, z=[0,1,2]

Inner(1):

x=1, y=2, z=[0,1,2]

Inner(2):

x=3, y=2, z=[0,3,2]

Outer(2):

x=3, y=4, z=[0,3,4]

Main(2):

u=1, v=2, w=[0,3,4]

x, y, z are local variables of outerx, y, z in inner are those of outerx, y, z are accessible in inner

COMP519 Web Programming Lecture 21 Slide L21 – 3

Page 439: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Functions Variable Scope and Functions

Variable Scope in Python: Example

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

print(s+’: ’+a+’=’+str(k)+’, ’+

b+’=’+str(l)+’, ’+c+’=’+str(m))

def outer(x,y,z):

def inner ():

state(’Inner(1)’,’x’,x,’y’,y,’z’,z)

x = 3

z[1] = 3

state(’Inner(2)’,’x’,x,’y’,y,’z’,z)

state(’Outer(1)’,’x’,x,’y’,y,’z’,z)

inner()

y = 4

z[2] = 4

state(’Outer(2)’,’x’,x,’y’,y,’z’,z)

u, v, w = 1, 2, [0,1,2]

state(’Main(1)’,’u’,u,’v’,v,’w’,w)

outer(u,v,w)

state(’Main(2)’,’u’,u,’v’,v,’w’,w)

Main(1):

u=1, v=2, w=[0,1,2]

Outer(1):

x=1, y=2, z=[0,1,2]

Traceback (most recent call last):

line 20, in <module>

outer(u,v,w)

line 13, in outer

inner()

line 8, in inner

state(’Inner(1)’,’x’,x,’y’,...)

UnboundLocalError:

local variable ’x’

referenced before assignment

x in inner is a local variabe of innerx in inner is not the same as x in outery in inner is the same as y in outerz in inner is the same as z in outer

COMP519 Web Programming Lecture 21 Slide L21 – 4

Page 440: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Functions Variable Scope and Functions

Variable Scope in Python: Analysis

• By default, any assignment to a variable within a functioncreates 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

Page 441: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Functions Variable Scope and Functions

Variable Scope in Python

• A variable that is a function parameter or defined inside a functionis 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 thenearest enclosing scope excluding globals

COMP519 Web Programming Lecture 21 Slide L21 – 6

Page 442: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Functions Variable Scope and Functions

Global vs Local Variables in Python

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

print(s+’: ’+a+’=’+str(k)+’, ’+

b+’=’+str(l)+’, ’+c+’=’+str(m))

def outer(x,y,z):

def inner ():

nonlocal x

state(’Inner(1)’,’x’,x,’y’,y,’z’,z)

x = 3

z[1] = 3

state(’Inner(2)’,’x’,x,’y’,y,’z’,z)

state(’Outer(1)’,’x’,x,’y’,y,’z’,z)

inner()

y = 4

z[2] = 4

state(’Outer(2)’,’x’,x,’y’,y,’z’,z)

u, v, w = 1, 2, [0,1,2]

state(’Main(1)’,’u’,u,’v’,v,’w’,w)

outer(u,v,w)

state(’Main(2)’,’u’,u,’v’,v,’w’,w)

Main(1):

u=1, v=2, w=[0,1,2]

Outer(1):

x=1, y=2, z=[0,1,2]

Inner(1):

x=1, y=2, z=[0,1,2]

Inner(2):

x=3, y=2, z=[0, 3, 2]

Outer(2):

x=3, y=4, z=[0, 3, 4]

Main(2):

u=1, v=2, w=[0, 3, 4]

x in inner is now the same as x in outery in inner is the same as y in outerz in inner is the same as z in outer

COMP519 Web Programming Lecture 21 Slide L21 – 7

Page 443: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Functions Static Variables

Python Functions and Static Variables

• Python does not have a static keyword to declare a variable to bestatic 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/publicCOMP519 Web Programming Lecture 21 Slide L21 – 8

Page 444: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 functionsas arguments or used as values in complex data structures

COMP519 Web Programming Lecture 21 Slide L21 – 9

Page 445: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

• An object of a class is created using

identifier(arg1 ,arg2 ,...)

where arg1,arg2,... is a possibly empty list of arguments passed tothe constructor of the class identifier

COMP519 Web Programming Lecture 21 Slide L21 – 10

Page 446: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Classes Defining and Instantiating a Class

A Closer Look at Class Definitions

In more detail, the definition of a classtypically looks as follows

class id:

docstring

# Class Attributes

cAttrib = value1

# Constructor

def __init__(self ,p1 ,p2 ,...):

# Instance Attribute

self.iAttrib = value2

suite1

# Methods

def method2(self ,p1 ,p2 ,...):

suite2

def methodN(self ,p1 ,p2 ,...):

suiteN

• Every instance obj of thisclass will have an attributeiAttrib accessible asobj.iAttrib

• cAttrib is a class attributeaccessible as id.cAttrib orobj.cAttrib

• __init__ is the constructorof the class and will be calledwhenever id(a1,a2,...)is executed• Via self the constructor

receives a reference to thenewly created object

• p1,p2,... will beinstantiated by a1,a2,...

COMP519 Web Programming Lecture 21 Slide L21 – 11

Page 447: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Classes Defining and Instantiating a Class

A Closer Look at Class Definitions

In more detail, the definition of a classtypically looks as follows

class id:

docstring

# Class Attributes

cAttrib = value1

# Constructor

def __init__(self ,p1 ,p2 ,...):

# Instance Attribute

self.iAttrib = value2

suite1

# Methods

def method2(self ,p1 ,p2 ,...):

suite2

def methodN(self ,p1 ,p2 ,...):

suiteN

• Every instance obj of thisclass will have methodsmethod2 to methodN

• For an instance obj of thisclass, method calls will takethe formobj.method2(a1,a2,...) toobj.methodN(a1,a2,...)

• p1,p2,... will beinstantiated by a1,a2,... inthe normal way for functioncalls

• Via self each methodreceives a reference to obj asadditional argument

COMP519 Web Programming Lecture 21 Slide L21 – 12

Page 448: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

r2 = Rectangle (5,2)

print(’Area of r2:’,r2.area ())

r3 = Rectangle(width=5,height =2)

print(’Area of r3:’,r3.area ())

Area of r1: 0

Area of r2: 10

Area of r3: 10

COMP519 Web Programming Lecture 21 Slide L21 – 13

Page 449: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Classes Class and Instance Attributes

Class and Instance Attributes

• Class attributes are owned by the class itself and shared by all instancesof 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 newinstance variable

• For an instance obj, obj.__dict__ returns a dictionary of all instancevariable 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

Page 450: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 underscoreshould be ‘considered’ private

• Python supports this convention by name mangling:Within the definition of a class id an attribute __attrib is textuallyreplaced by _id__attrib

class Hide:

__cHide = 1

def __init__(self):

self.__iHide = 2

h1 = Hide()

print(" Class: ",Hide.__dict__)

print(" Instance:",h1.__dict__)

print(" Value of __iHide for h1:",

h1._Hide__iHide)

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

Page 451: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 452: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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:

totalNumber = 0;

def __init__(self ,name):

self.name = name

type(self). totalNumber += 1

def __del__(self):

type(self). totalNumber -= 1

e1 = Employee ("Ada")

e2 = Employee ("Ben")

print("A: #employees: ",

Employee.totalNumber)

del e1

print("B: #employees: ",

Employee.totalNumber)

e2 = None

print("C: #employees: ",

Employee.totalNumber)

A: #employees: 2

B: #employees: 1

C: #employees: 0

COMP519 Web Programming Lecture 21 Slide L21 – 17

Page 453: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Classes Class Methods

Static Methods (Class Methods)

• The Pythonic way is to define getterand setter method only for ‘private’class and instance attributes

• For ‘private’ instance variables this isdone in the standard way

• For ‘private’ class variables we needto declare the getter / setter methodto be static

e3 = Employee ("Ada")

e4 = Employee ("Ben")

print (" Number of employees: ",

Employee.getNumber ())

print (" Number of employees: ",

e3.getNumber ())

Number of employees: 2

Number of employees: 2

class Employee:

__tNum = 0;

def __init__(self ,name):

self.__name = name

type(self). __tNum += 1

def __del__(self):

type(self). __tNum -= 1

def getName(self):

return self.__name

def setName(self ,name):

self.__name = name

@staticmethod

def getNumber ():

return Employee.__tNum

COMP519 Web Programming Lecture 21 Slide L21 – 18

Page 454: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Classes Class Methods

Static Methods (Class Methods)

• A static declaration should also be used for methods that areindependant of specific instances

class Circle:

PI = 3.14159265359

def __init__(self ,radius ):

self.r = radius

def area(self):

return round(Circle.PI * \

self.r * self.r,5)

@staticmethod

def max(cx ,cy):

if cx.r > cy.r:

return cx

else:

return cy

c1 = Circle (1.2)

c2 = Circle (1.0)

print ("c1 radius:",c1.r)

print ("c1 area: ",c1.area ())

print ("c2 radius:",c2.r)

print ("c2 area: ",c2.area ())

bg = Circle.max(c1,c2)

print ("bg radius:",bg.r)

c1 radius: 1.2

c1 area: 4.52389

c2 radius: 1.0

c2 area: 3.14159

bg radius: 1.2

COMP519 Web Programming Lecture 21 Slide L21 – 19

Page 455: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Classes Inheritance

Inheritance

• In a class definition it is possible to specify one or more superclassesfrom 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

self.height = height

def area(self):

return self.height * self.width

class Square(Rectangle ):

type = ’Square ’

def __init__(self ,size):

super (). __init__(size ,size)

sq1 = Square (5)

print ("The type of sq1 is",

sq1.type )

print ("The area of sq1 is",

sq1.area() )

The type of sq1 is Square

The area of sq1 is 25

COMP519 Web Programming Lecture 21 Slide L21 – 20

Page 456: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Classes Magic Methods

Magic Methods

• __init__ and __del__ are examples of magic methods:Methods that are invoked when a certain language constructs is used ora 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 astring 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(), shouldreturn 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

Page 457: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 458: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Classes Magic Methods

Magic Methods: Iterators

• A for-loop starts by calling the __iter__() on an object to obtain aniterator 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 __init__(self , max = 0):

self.max = max

def __iter__(self):

self.n = 0

return self

def __next__(self):

if self.n <= self.max:

result = 2 ** self.n

self.n += 1

return result

else:

raise StopIteration

for x in PowTwo (2):

print(x)

1 # 2 ** 0

2 # 2 ** 1

4 # 2 ** 2COMP519 Web Programming Lecture 21 Slide L21 – 23

Page 459: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 460: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 22: Python (Part 6)

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 461: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

67 Regular Expressions and Regular Expression SearchMotivationThe re moduleCharactersCharacter Classes

68 Further Reading

COMP519 Web Programming Lecture 22 Slide L22 – 1

Page 462: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Regular Expressions and Regular Expression Search Motivation

Regular Expressions

• Many programming languages support the use of regular expressionseither• 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

Page 463: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Regular Expressions and Regular Expression Search Motivation

Regular expressions: Motivation

Suppose you are testing the performance of a new sorting algorithm bymeasuring its runtime on randomly generated arrays of numbersof 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 ofthe 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 extractionCOMP519 Web Programming Lecture 22 Slide L22 – 3

Page 464: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Regular Expressions and Regular Expression Search Motivation

Regular expressions: Motivation

Suppose you have recently taken over responsibility for a company’swebsite. You note that their HTML files contain a large number ofURLs 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 withequivalent 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 modificationCOMP519 Web Programming Lecture 22 Slide L22 – 4

Page 465: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 466: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 stringreturns a match object when regexp is found and None otherwisere.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 otherwisere.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 matchesfor regexp in string

COMP519 Web Programming Lecture 22 Slide L22 – 6

Page 467: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 matchesfor 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 performedre.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

Page 468: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 469: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 ofregular expression strings

• Instead the regular expression objects themselves support thefollowing 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

Page 470: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 471: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Regular Expressions and Regular Expression Search Characters

Match Objects: Basics

• Detailed information about a match is provided by the match objectmObj returned by operations such as re.search:mObj.group(0): the substring matchedmObj[0]: the substring matchedmObj.start(0): the index position at which the match startsmObj.end(0): the index position after which the match endsmObj.span(0): start and end index as a tuplemObj.re: regular expression that was matchedmObj.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

Page 472: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Regular Expressions and Regular Expression Search Characters

Regular Expressions: Special Escapes

There are various special escapes and metacharacters that match morethen one character:

. Matches any character except \n

\w Matches a ‘word’ character (alphanumericplus ‘_’, plus other connector punctuationcharacters 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

Page 473: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Regular Expressions and Regular Expression Search Character Classes

Regular Expressions: Character Class

• A character class, a list of characters, special escapes, andmetacharacters 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

Page 474: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 orE-book http://library.liv.ac.uk/record=b2174141

COMP519 Web Programming Lecture 22 Slide L22 – 14

Page 475: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 23: Python (Part 7)

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 476: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

69 Regular Expressions and Regular Expression SearchQuantifiersCapture GroupsAlternationsAnchorsFlags and Inline Flags

70 Regular Expression Split

71 Regular Expression SubstitutionSubstitution OperatorsCapture GroupsFlags and Inline FlagsFunctions as Replacement

72 Revision and Further Reading

COMP519 Web Programming Lecture 23 Slide L23 – 1

Page 477: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Regular Expressions and Regular Expression Search Quantifiers

Regular Expressions: Quantifiers

• The constructs for regular expressions that we have so far are notsufficient to match, for example, natural numbers of arbitrary size

• Also, writing a regular expressions for, say, a nine digit numberwould be tedious

This is made possible with the use of quantifiers

regexp* Match regexp 0 or more timesregexp+ Match regexp 1 or more timesregexp? Match regexp 1 or 0 times as many timesregexp{n,} Match regexp at least n times as possibleregexp{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 sequenceof characters possible

COMP519 Web Programming Lecture 23 Slide L23 – 2

Page 478: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Regular Expressions and Regular Expression Search Quantifiers

Regular Expressions: Quantifiers

regexp* Match regexp 0 or more timesregexp+ Match regexp 1 or more timesregexp? Match regexp 1 or 0 times as many timesregexp{n,} Match regexp at least n times as possibleregexp{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

Page 479: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 480: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Regular Expressions and Regular Expression Search Quantifiers

Regular Expressions: Non-greedy Quantifiers

For every greedy quantifier there is a non-greedy quantifier that isobtained by adding the quantifier ? to it:

regexp*? Match regexp 0 or more timesregexp+? Match regexp 1 or more timesregexp?? Match regexp 1 or 0 times as few timesregexp{n,}? Match regexp at least n times as possibleregexp{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

Page 481: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Regular Expressions and Regular Expression Search Capture Groups

Regular Expressions: Capture Groups and Backreferences

• We often encounter situations where we want to identify the repetitionof 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 aboveusing 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

Page 482: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

# |

# 1COMP519 Web Programming Lecture 23 Slide L23 – 7

Page 483: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 forcapture group N starts

mObj.end(N): the index position after which the match forcapture group N ends

mObj.span(N): start and end index for capture group N

as a tuplemObj.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

Page 484: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 485: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 matchedby the capture groups

mObj.groupdict(): a dictionary contained all the substrings matchedby named captures groups using their namesas 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: bCOMP519 Web Programming Lecture 23 Slide L23 – 10

Page 486: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 487: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Regular Expressions and Regular Expression Search Alternations

Regular Expressions: Alternations

• The regular expression regexp1|regexp2 matchesif either regexp1 or regexp2 matchesThis type of regular expression is called an alternation

• Within a larger regular expression we need to enclose alternationsin 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

Page 488: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Regular Expressions and Regular Expression Search Alternations

Regular Expressions: Alternations

• The regular expression regexp1|regexp2 matchesif either regexp1 or regexp2 matchesThis type of regular expression is called an alternation

• Within a larger regular expression we need to enclose alternationsin 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

Page 489: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Regular Expressions and Regular Expression Search Alternations

Regular Expressions: Alternations

• The order of expressions in an alternation only mattersif 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

Page 490: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 491: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 thebehaviour of those functions

• Inline flags, added to regular expressions, modify the behaviour of thoseregular expressions

re.A (?a) Make \w, \W, \b, \B, \d, \D, \s, \S

perform ASCII-only matching instead ofUnicode 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 newlinere.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

Page 492: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 andmake ’$’ 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 matchingre.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

Page 493: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 thebehaviour of those functions

• Inline flags, added to regular expressions, modify the behaviour of thoseregular 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

Page 494: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Regular Expressions and Regular Expression Search Flags and Inline Flags

Finditer and Findall Revisited

finditer and findall return all non-overlapping matchesfor 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

Page 495: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 496: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Regular Expression Substitution Substitution Operators

Regular Expression Substitution

re.sub(regexp, repl, string, count, flags)

returns the string obtained by replacing the leftmost non-overlappingoccurrences 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 regexpoccurrences 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

Page 497: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Regular Expression Substitution Substitution Operators

Regular Expression Substitution

re.subn(regexp, repl, string, count, flags)

returns a tuple consisting of the result ofre.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

Page 498: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 499: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Regular Expression Substitution Capture Groups

Substitution: Capture Groups

In a replacement string we can refer back to substrings matched bycapture 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

Page 500: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 501: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 502: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Revision and Further Reading

Regular Expressions and the Chomsky Hierarchy

• In Computer Science, formallanguages are categorisedaccording to the type ofgrammar needed to generatethem (or the type of automatonneeded to recognise them)

• Python regular expressions canat least recognise all regularlanguages Chomsky Hiearchy of Formal Languages

• The regex library is intended to replace the re module at some pointand will be more powerful

• There are libraries specifically for parsing context free languages ordealing with specific languages, e.g. HTML, CSV

COMP519 Web Programming Lecture 23 Slide L23 – 27

Page 503: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 orE-book http://library.liv.ac.uk/record=b2174141

• Read• Section 6.2: re — Regular expression operationshttps://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

Page 504: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 24: Python (Part 8)

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 505: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

73 CGIOverviewCGI I/O

74 CGI ProgramsMotivationLocal Setup

75 Python CGI ProgramsAccessing and Processing Environment Variables: The os ModuleAccessing and Processing Form Data: The cgi ModuleInput Checks and Code InjectionDebugging Python CGI Scripts

76 Opening URLs: The urllib ModuleFunctionsExample

77 Revision and Further Reading

COMP519 Web Programming Lecture 24 Slide L24 – 1

Page 506: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

CGI Overview

Common Gateway Interface — CGI

The Common Gateway Interface (CGI) is a standard methodfor 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 andthe server passes the program’s response back to the client

COMP519 Web Programming Lecture 24 Slide L24 – 2

Page 507: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

CGI CGI I/O

Client requests

In the following we focus on client requests that are generatedusing 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

Page 508: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

CGI CGI I/O

Client requests

In the following we focus on client requests that are generatedusing 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

Page 509: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

CGI CGI I/O

Encoding of input data

• Input data from an HTML form is sent URL-encoded as sequence ofkey-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

Page 510: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

CGI CGI I/O

Request methods: GET versus POST

The two main request methods used with HTML formsare 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

Page 511: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

CGI CGI I/O

Request methods: GET versus POST

The two main request methods used with HTML formsare 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

Page 512: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 physicalpath

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

Page 513: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 physicalpath

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%60n+d%2Bt+e+s%27t&fullname=Peter+Newton

QUERY_STRING username =2%60n+d%2Bt+e+s%27t&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

Page 514: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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%60n+d%2Bt+e+s%27t&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%60n+d%2Bt+e+s%27t&fullname=Peter+Newton

COMP519 Web Programming Lecture 24 Slide L24 – 10

Page 515: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

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

SERVER_SOFTWARE The name and version of the server software

COMP519 Web Programming Lecture 24 Slide L24 – 11

Page 516: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

CGI Programs Motivation

CGI programs and Python

• CGI programs need to process input data from environment variablesand 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 moduleto access environment variables

• print statements to produce HTML markup

COMP519 Web Programming Lecture 24 Slide L24 – 12

Page 517: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 518: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 519: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Python CGI Programs

User-Defined Functions for an HTML Wrapper

It makes sense to define functions that print out theinitial (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

Page 520: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Python CGI Programs Accessing and Processing Environment Variables: The os Module

Accessing Environment Variables

• The environ dictionary of the os module allows us to accessenvironment 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

Page 521: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Python CGI Programs Accessing and Processing Environment Variables: The os Module

Accessing Environment Variables

COMP519 Web Programming Lecture 24 Slide L24 – 17

Page 522: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Python CGI Programs Accessing and Processing Environment Variables: The os Module

Processing Environment Variables: HTTP USER AGENT

• The environment variable HTTP_USER_AGENT contains informationabout the user agent (browser) and operating system from which therequest 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

Page 523: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 524: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Python CGI Programs Accessing and Processing Environment Variables: The os Module

Processing Environment Variables: REMOTE ADDRimport 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

Page 525: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 526: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 HTMLforms in a two step process:

1 Create an instance of the FieldStorage class and assign it to avariable

variable = cgi.FieldStorage ()

This reads the form data from standard input or the environmentvariable 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

Page 527: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 528: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 529: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 530: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 531: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 532: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 533: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 534: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Python CGI Programs Debugging Python CGI Scripts

Debugging Python CGI Scripts

• The web server will report an ‘Internal Server Error’ if scripts containsyntax 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 serverconfiguration what information is passed on

• The cgitb module provides a special exception handler for Pythonscripts; 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

Page 535: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Opening URLs: The urllib Module Functions

Opening a URL from a Python Script

The urllib.request module provides functions that retrieve datafrom 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 objectaccording to the encoding enc,examples of encodings are ’utf-8’, ’ascii’

COMP519 Web Programming Lecture 24 Slide L24 – 31

Page 536: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 537: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 orE-book http://library.liv.ac.uk/record=b2174141

• Read• 21.2. cgi — Common Gateway Interface supporthttps://docs.python.org/3/library/cgi.html#module-cgi

• 21.6. urllib.request — Extensible library for opening URLshttps://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

Page 538: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 25: PHP (Part 1)

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 539: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

78 PHPMotivation

79 OverviewFeaturesApplications

80 Types and VariablesTypesVariablesType juggling and Type castingComparisons

81 Further Reading

COMP519 Web Programming Lecture 25 Slide L25 – 1

Page 540: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

PHP Motivation

Common Gateway Interface — CGI

The Common Gateway Interface (CGI) is a standard method for webservers to use external applications, a CGI program, to dynamicallygenerate web pages

1 A web client generates a client request, for example, from a HTMLform, 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 passesthe program’s response back to the client

COMP519 Web Programming Lecture 25 Slide L25 – 2

Page 541: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

PHP Motivation

Disadvantages of CGI Programming

• A distinction is made between static web pages anddynamic web pages created by an external program

• Using CGI programs it is difficult to add ‘a little bit’ ofdynamic 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

Page 542: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 543: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 fora HTML page containing PHP code

3 The server executes the PHP code, substitutes outputinto 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

Page 544: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Overview Applications

PHP: Applications

• Applications written using PHP• activeCollab – Project Collaboration Softwarehttp://www.activecollab.com/

• Drupal – Content Management System (CMS)http://drupal.org/home

• Magento – eCommerce platformhttp://www.magentocommerce.com/

• MediaWiki – Wiki softwarehttp://www.mediawiki.org/wiki/MediaWiki

• Moodle – Virtual Learning Environment (VLE)http://moodle.org/

• Sugar – Customer Relationship Management (CRM) platformhttp://www.sugarcrm.com/crm/

• WordPress – Blogging tool and CMShttp://wordpress.org/

COMP519 Web Programming Lecture 25 Slide L25 – 6

Page 545: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Overview Applications

PHP: Websites

• Websites using PHP:• Delicious – social bookmarkinghttp://delicious.com/

• Digg – social news websitehttp://digg.com

• Facebook – social networkinghttp://www.facebook.com

• Flickr – photo sharinghttp://www.flickr.com

• Frienster – social gaminghttp://www.frienster.com

• SourceForge – web-based source code repositoryhttp://sourceforge.net/

• Wikipedia – collaboratively built encyclopediahttp://www.wikipedia.org

COMP519 Web Programming Lecture 25 Slide L25 – 7

Page 546: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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, forexample $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

Page 547: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 contextCOMP519 Web Programming Lecture 25 Slide L25 – 9

Page 548: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 549: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Overview Applications

PHP Scripts

• PHP scripts are typically embedded into HTML documents and areenclosed 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

Page 550: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Types and Variables Types

Types

PHP has eight datatypes

• Four primitive types:• bool – booleans

• int – integers

• float – floating-point numbers

• string – strings

• Two compound types:• array – arrays

• object – objects

• Two special types:• resource

• NULL

• Integers, floating-point numbers, and booleans do not differ significantlyfrom the corresponding JavaScript types

• Strings differ from those in JavaScript and Python

COMP519 Web Programming Lecture 25 Slide L25 – 12

Page 551: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 552: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Types and Variables Variables

Assignments

• Just like Java, JavaScript and Python, PHP uses the equality sign = forassignments

$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

Page 553: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 554: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 (InPHP 7, expr can also be an array)

• case_insensitive is an optional boolean argument, indicatingwhether 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

Page 555: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 556: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 557: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Types and Variables Type juggling and Type casting

Type juggling and Type casting

• PHP automatically converts a value to the appropriate type as requiredby 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

Page 558: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 jugglingexpr1 != expr2 Not equal TRUE iff expr1 is not equal to expr2

after type jugglingexpr1 <> 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 numbersand 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 ; FALSECOMP519 Web Programming Lecture 25 Slide L25 – 20

Page 559: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 jugglingexpr1 > expr2 Greater than TRUE iff expr1 is strictly greater than expr2

after type jugglingexpr1 <= expr2 Less than

or equal toTRUE iff expr1 is less than or equal to expr2

after type jugglingexpr1 >= expr2 Greater than

or equal toTRUE iff expr1 is greater than or equal to expr2

after type juggling

Note: For >, >=, <, and <= numerical strings are converted to numbersand 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

Page 560: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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’ ; 0TRUE <=> FALSE ; 1 0.0 <=> FALSE ; 05 <=> TRUE ; 0 ’FALSE’ <=> TRUE ; 0

COMP519 Web Programming Lecture 25 Slide L25 – 22

Page 561: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 orE-book http://library.liv.ac.uk/record=b2174141

COMP519 Web Programming Lecture 25 Slide L25 – 23

Page 562: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 26: PHP (Part 2)

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 563: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

82 Primitive DatatypesIntegers and Floating-point numbersExceptions and error handlingBooleansStrings

83 ArraysBasicsForeach-loopsArray Operators

84 Special typesNULLResources

85 Printing

86 Revision and Further Reading

COMP519 Web Programming Lecture 26 Slide L26 – 1

Page 564: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 functionsabs(number) absolute valueceil(number) round fractions upfloor(number) round fractions downround(number [,prec,mode]) round fractionslog(number [,base]) logarithmrand(min,max) generate an integer random numbersqrt(number) square root

• PHP provides a range of pre-defined number constants includingM_PI 3.14159265358979323846NAN ‘not a number’INF ‘infinity’

COMP519 Web Programming Lecture 26 Slide L26 – 2

Page 565: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 566: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 567: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 568: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 functionturn errors into exceptions

function exception_error_handler($errno , $errstr ,

$errfile , $errline ) {

throw new ErrorException($errstr , $errno ,

0, $errfile , $errline ); }

set_error_handler("exception_error_handler");

http://www.php.net/manual/en/class.errorexception.php

COMP519 Web Programming Lecture 26 Slide L26 – 6

Page 569: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Primitive Datatypes Booleans

Booleans

• PHP has a boolean datatypewith constants TRUE and FALSE (case insensitive)

• PHP offers the same short-circuit boolean operators as Java andJavaScript:

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

Page 570: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 571: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 572: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

’don\’t’ ; don’t

’"hello"’ ; "hello"

’backslash\\’ ; backslash\

’glass\\table’ ; glass\table

’glass\table’ ; glass\table

"hello" ; hello

"don’t" ; don’t

"\"hello\"" ; "hello"

"backslash\\" ; backslash\

"glass\\table" ; glass\table

"glass\table" ; glass able

COMP519 Web Programming Lecture 26 Slide L26 – 10

Page 573: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 574: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 575: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 thenatural numbers 0, 1, . . .

• All the keys of an array can be retrieved usingarray_keys($array1)

; returns a natural number-indexed array containingthe keys of $array1

• All the values of an array can be retrieved usingarray_values($array1)

; returns a natural number-indexed array containingthe values stored in $array1

COMP519 Web Programming Lecture 26 Slide L26 – 13

Page 576: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Arrays Basics

Arrays

• An individual array element can be accessed via its key

• Accessing an undefined key produces an error messageand 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 checkwhether 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

Page 577: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 578: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Arrays Foreach-loops

Arrays: foreach-loop

• PHP provides a foreach-loop construct to ‘loop’ through the elementsof 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 inarray at each iteration of the foreach-loop

• foreach iterates through an array in the order in which elements weredefined

COMP519 Web Programming Lecture 26 Slide L26 – 16

Page 579: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 580: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 581: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Arrays Foreach-loops

Arrays: foreach-loop

• In order to modify array elements within a foreach-loop we need use areference

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

Page 582: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 583: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Arrays Foreach-loops

Array Assignments

• In JavaScript and Python, arrays were objects and as a consequencearray 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("%6d",$mem2 -$mem1)," more bytes\n";

$array2 = $array1;

$mem3 = memory_get_usage ();

echo "(2) ",sprintf("%6d",$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("%6d",$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 assignmentsCOMP519 Web Programming Lecture 26 Slide L26 – 21

Page 584: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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, thenwe need to use a reference

$array1 = range(1, 1000);

$mem2 = memory_get_usage ();

$array2 = &$array1;

$mem3 = memory_get_usage ();

echo "(2) ",sprintf("%6d",$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("%6d",$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

Page 585: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 586: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

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

Page 587: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 588: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 589: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Special types Resources

Resources

• bool fclose(resource)

• Closes the resource

• Returns TRUE on success

• string fgets(resource [, length])

• Returns a line read from resource andreturns FALSE if there is no more data to be read

• With optional argument length, reading ends when length− 1 byteshave 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

Page 590: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 orthe 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 theplatform dependent newline ; use PHP_EOL instead

COMP519 Web Programming Lecture 26 Slide L26 – 28

Page 591: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 argumentOnly one argument is allowed!

• Returns value 1

• Parentheses can be omitted

COMP519 Web Programming Lecture 26 Slide L26 – 29

Page 592: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 theplace of a list of arguments

printf("%2d apples %2d oranges\n",array (5 ,7));

produces an error message

COMP519 Web Programming Lecture 26 Slide L26 – 30

Page 593: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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("%2d apples %2d oranges\n",array (5 ,7));

5 apples 7 oranges

COMP519 Web Programming Lecture 26 Slide L26 – 31

Page 594: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Revision and Further Reading

Revision and Further Reading

Read

• Language Reference: Types: Booleanshttp://uk.php.net/manual/en/language.types.boolean.php

• Language Reference: Types: Integershttp://uk.php.net/manual/en/language.types.integer.php

• Language Reference: Types: Floating Point Numbershttp://uk.php.net/manual/en/language.types.float.php

• Language Reference: Types: Stringshttp://uk.php.net/manual/en/language.types.string.php

• Language Reference: Types: Arrayshttp://uk.php.net/manual/en/language.types.array.php

• Language Reference: Control Structures: foreachhttp://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

Page 595: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 27: PHP (Part 3)

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 596: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

87 Control StructuresConditional StatementsSwitch StatementsWhile- and Do While-loopsFor-loops

88 FunctionsDefining and Calling a FunctionScope of VariablesFunctions and HTMLVariable-length Argument ListsClosures and Anonymous FunctionsType Declarations

89 PHP librariesInclude/Require

90 Revision and Further Reading

COMP519 Web Programming Lecture 27 Slide L27 – 1

Page 597: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 598: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Control Structures Conditional Statements

Conditional Statements

The general format of conditional statements is very similar but notidentical 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 oneNote: 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 onlya single statement in a clause

COMP519 Web Programming Lecture 27 Slide L27 – 3

Page 599: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Control Structures Conditional Statements

Conditional Statements/Expressions

• PHP allows to replace curly brackets with a colon : combined with anendif 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 parsewhen 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

Page 600: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Control Structures Switch Statements

Switch Statement

A switch statement in PHP takes the following form

switch (expr) {

case expr1:

statements

break;

case expr2:

statements

break;

default:

statements

break;

}

• there can be arbitrarily many case-clauses

• the default-clause is optional but there can beat most one

• expr is evaluated only once and then comparedto expr1, expr2, etc using (loose) equality ==

• once two expressions are found to be equal thecorresponing clause is executed

• 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

Page 601: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 602: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 603: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 onestatement

Example:

// Compute the factorial of $number

$factorial = 1;

do {

$factorial *= $number --;

} while ($number > 0);

COMP519 Web Programming Lecture 27 Slide L27 – 8

Page 604: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 onlyconsists of a single statement

• In PHP initialisation and increment can consist of more than onestatement, 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

Page 605: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Control Structures For-loops

Break and Continue

• The break command can also be used in while-, do while-, and for-loopsand 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 aloop and moves the execution to the next iteration

for ($x = -2; $x <= 2; $x++) {

if ($x == 0) continue;

printf("10 / %2d = %3d\n",$x ,(10/ $x));

}

10 / -2 = -5

10 / -1 = -10

10 / 1 = 10

10 / 2 = 5

COMP519 Web Programming Lecture 27 Slide L27 – 10

Page 606: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 theyshould 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 ofany parameters without defaults

COMP519 Web Programming Lecture 27 Slide L27 – 11

Page 607: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Functions Defining and Calling a Function

Functions

Functions are defined as follows in PHP:

function identifier($param1 ,&$param2 , ...) {

statements

}

• The return statementreturn value

can be used to terminate the execution of a function and to makevalue 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

Page 608: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Functions Defining and Calling a Function

Calling a Function

A function is called by using the function name followed by a list ofarguments in parentheses

function identifier($param1 , &$param2 , ...) {

...

}

... identifier(arg1 , arg2 ,...) ...

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

• If it is shorter, then default values must have been specified for theparameters 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

Page 609: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Functions Scope of Variables

Variables

PHP distinguishes three categories of variables:

• Local variables are only accessible in the part of the code in which theyare introduced

• Global variables are accessible everywhere in the code

• Static variables are local variables within a function that retain theirvalue between separate calls of the function

By default, variables in PHP are local but not static

COMP519 Web Programming Lecture 27 Slide L27 – 14

Page 610: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 nestedCOMP519 Web Programming Lecture 27 Slide L27 – 15

Page 611: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 612: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 outerfunction

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

Page 613: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Functions Scope of Variables

Functions and Scope

$x = "hello";

function func1 () {

echo "1:",$x,"\n";

}

func1 ();

function func2 () {

echo "2:",$x,"\n";

$x = "Bye";

echo "3:",$x,"\n";

}

func2 ();

echo "4:",$x,"\n";

1:PHP Notice:

Undefined variable: x

2:PHP Notice:

Undefined variable: x

3:Bye

4: hello

• A variable defined outside any function isglobal

• A global variable can be accessed from anypart of the script that is not inside afunction

• A variable within a PHP function is bydefault local and can only be accessedwithin that function

COMP519 Web Programming Lecture 27 Slide L27 – 18

Page 614: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 normalscope using global

; all global variables with the same name refer to the samestorage 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

Page 615: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Functions Scope of Variables

PHP Functions and Global Variables

1 function modify_or_destroy_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 modify_or_destroy_var(false );

11 echo "3: \$x = $x, \$y = $y\n";

12 modify_or_destroy_var(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

Page 616: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Functions Scope of Variables

PHP Functions and Static Variables

• A variable is declared to be static using the keyword static and shouldbe 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

Page 617: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Functions Functions and HTML

Functions and HTML

• It is possible to include HTML markup in the body of afunction definition

• The HTML markup can in turn contain PHP scripts

• A call of the function will execute the PHP scripts, insert the outputinto 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

Page 618: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Functions Variable-length Argument Lists

Functions with Variable Number of Arguments

The number of arguments in a function call is allowed to exceed thenumber 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

Page 619: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 denotethat 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" ,3e0), "\n";

6

COMP519 Web Programming Lecture 27 Slide L27 – 24

Page 620: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 externalvariables

$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

Page 621: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

1: 5

2: 5 // not 8 nor 10

PHP Fatal error:

Uncaught TypeError

// with strict_types =1

1: 5

PHP Fatal error:

Uncaught TypeError

PHP Fatal error:

Uncaught TypeError

COMP519 Web Programming Lecture 27 Slide L27 – 26

Page 622: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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, andrequire_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 aninclude 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

Page 623: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

PHP libraries Include/Require

Including and Requiring Files

• Several include or require commands for the same library fileresults 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 samelibrary file results in the file being incorporated only once

• If a library file requested by include and include_once cannot befound, PHP generates a warning but continues the execution of therequesting script

• If a library file requested by require and require_once cannot befound, PHP generates a error and stops execution of the requestingscript

COMP519 Web Programming Lecture 27 Slide L27 – 28

Page 624: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 625: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Revision and Further Reading

Revision and Further Reading

Read

• Language Reference: Control Structureshttp://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: Functionshttp://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

Page 626: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 28: PHP (Part 4)

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 627: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents91 Web Applications

OverviewHTML Forms

92 Available Information and InputOverviewPHP EnvironmentServer VariablesForm Data

93 PHP SessionsStart a PHP SessionMaintain Session DataEnd a PHP SessionSession ManagementExample

94 AuthenticationOverviewExample

95 Further ReadingCOMP519 Web Programming Lecture 28 Slide L28 – 1

Page 628: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 629: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Web Applications HTML Forms

HTML Forms

When considering Python CGI programming we have used HTML formsthat generated a client request that was handled by a Python CGIprogram:

<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 webserver, for example $HOME/public_html, and be readable by the webserver

• The PHP script file name must have the extension .php, e.g. demo.phpCOMP519 Web Programming Lecture 28 Slide L28 – 3

Page 630: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 secondssince January 1 1970 00:00:00 GMT

COMP519 Web Programming Lecture 28 Slide L28 – 4

Page 631: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Available Information and Input PHP Environment

PHP Environment

• phpinfo() displays information about the PHP installation andEGPCS 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 directivesINFO_MODULES Loaded modulesINFO_VARIABLES All EGPCS data

COMP519 Web Programming Lecture 28 Slide L28 – 5

Page 632: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Available Information and Input PHP Environment

Manipulating the PHP Configuration

The following functions can be used to access and change theconfiguation 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’sexecution 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

Page 633: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Available Information and Input Server Variables

Server Variables

The $_SERVER array stores information about the web serverand 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 keysCOMP519 Web Programming Lecture 28 Slide L28 – 7

Page 634: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 toaccessing the ‘dictionary’ of a cgi.FieldStorage instance inPython

<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

Page 635: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 filecontaining 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 ofnames and their frequency, ordered from most frequent to least frequent

COMP519 Web Programming Lecture 28 Slide L28 – 9

Page 636: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 637: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Available Information and Input Form Data

Forms in PHP: Example (1)

extraction.php

<?php

function extract_names($url) {

$text = file_get_contents($url);

if ($text === false)

return "ERROR: INVALID URL!";

else {

$correct = preg_match_all("/name ={([^\}]+)}/",

$text ,$matches ,PREG_PATTERN_ORDER );

if ($correct == 0) return "ERROR: NO NAMES FOUND";

$count = array_count_values($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

Page 638: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Available Information and Input Form Data

Web Applications Revisited

SelectItem

EnterAddress

EnterPayment

ConfirmOrder

App

App

App

App

App

Request

Response

Request

Response

Request

Response

Request

Response

Request

• An interaction between a userand a server-side web applicationoften requires a sequence ofrequests and responses• For each request, the application

starts from scratch• it does not maintain a state

between consecutive requests

• it does not know whether therequests come from the same useror different users

;data needs to betransferred from one executionof the application to the next

COMP519 Web Programming Lecture 28 Slide L28 – 12

Page 639: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Available Information and Input Form Data

Transfer of Data: Example

• Assume for a sequence of requests we do not care whether they comefrom 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

Page 640: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

PHP Sessions

Sessions

• Assume for a sequence of requests we do care whether they come fromthe same user or different users

• Sessions help to solve this problem by associating client requests with aspecific user and maintaining data over a sequence of requests fromthat user

• Sessions are often linked to user authentication but are independent ofit, for example, eCommerce websites maintain a ‘shopping basket’without requiring user authentication first

However, sessions are the mechanism that is typically used to allow ordeny access to web pages based on a user having been authenticated

COMP519 Web Programming Lecture 28 Slide L28 – 14

Page 641: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 thesession identifier in client requests

• In addition, one can use session variables for storing information torelate 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 databaseto store such information

COMP519 Web Programming Lecture 28 Slide L28 – 15

Page 642: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

PHP Sessions

Cookies

Browser −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−→ ServerGET /index.html HTTP/1.1

Host: intranet.csc.liv.ac.uk

Browser ←−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− ServerHTTP/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 −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−→ ServerGET /teaching.html HTTP/1.1

Host: intranet.csc.liv.ac.uk

Cookie: name1=value1; name2=value2

Accept: */*

Browser ←−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− ServerHTTP/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

Page 643: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 644: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 callsor 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 andsession 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 givenone and the old name returned

COMP519 Web Programming Lecture 28 Slide L28 – 18

Page 645: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 sessioninformation is deleted

; regular use of this function alleviates the risk of a sessionbeing ‘hijacked’

<?php

session_start ();

echo "Session id: ", session_id (), "<br>";

echo "Session name: ",session_name (),"<br>";

session_regenerate_id ();

echo "Session id: ", session_id (), "<br>"; // changed

echo "Session name: ",session_name (),"<br>"; // unchanged

?>

COMP519 Web Programming Lecture 28 Slide L28 – 19

Page 646: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

PHP Sessions Maintain Session Data

Maintain Session Data

• bool session_start()

• resumes the current session based on a session identifierpassed 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 callsor 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

Page 647: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 648: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 beavailable

COMP519 Web Programming Lecture 28 Slide L28 – 22

Page 649: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 sessionCOMP519 Web Programming Lecture 28 Slide L28 – 23

Page 650: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

PHP Sessions Session Management

More on Session Management

The following code tracks whether a session is active and ends the sessionif there has been no activity for more then 30 minutesif (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

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

Page 651: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

PHP Sessions Example

PHP Sessions: Example

mylibrary.php:

<?php

session_start ();

function destroy_session_and_data () {

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

Page 652: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

destroy_session_and_data ();

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

Page 653: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

PHP Sessions Example

PHP and Cookies

Cookies can survive a session and transfer information from one session tothe nextcmylibrary.php:

<?php

session_start ();

function destroy_session_and_data () { // 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.phpCOMP519 Web Programming Lecture 28 Slide L28 – 27

Page 654: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Authentication Overview

PHP Sessions and Authentication

• Sessions are the mechanism that is typically used to allow or denyaccess 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 authenticatethemselves by providing a username and password on the page login.php

• The system maintains a list of valid usernames and passwords in a databaseand checks usernames and passwords entered by the user against thatdatabaseIf the check succeeds, a session variable is set

• The page content.php checks whether this session variable is setIf the session variable is set, the user will see the content of the pageIf 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 outagain

COMP519 Web Programming Lecture 28 Slide L28 – 28

Page 655: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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.phpCOMP519 Web Programming Lecture 28 Slide L28 – 29

Page 656: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 657: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 658: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 659: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 orE-book http://library.liv.ac.uk/record=b2174141

COMP519 Web Programming Lecture 28 Slide L28 – 33

Page 660: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

COMP519 Web ProgrammingLecture 29: PHP (Part 5)

Handouts

Ullrich Hustadt

Department of Computer ScienceSchool of Electrical Engineering, Electronics, and Computer Science

University of Liverpool

Page 661: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Contents

96 ClassesDefining and Instantiating a ClassVisibilityClass ConstantsStatic Properties and MethodsDestructorsInheritanceInterfacesIntrospection Functions

97 The PDO ClassIntroductionConnectionsQueries and Processing of ResultsPrepared StatementsTransactions

98 Revision and Further Reading

COMP519 Web Programming Lecture 29 Slide L29 – 1

Page 662: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 {

property_definitions

function_definitions

}

• 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 tothe constructor of the class identifier

COMP519 Web Programming Lecture 29 Slide L29 – 2

Page 663: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Classes Defining and Instantiating a Class

A Closer Look at Class Definitions

In more detail, the definition of a classtypically looks as followsclass identifier {

# Properties

vis $attrib1

...

vis $attribN = value

# Constructor

function __construct(p1 ,...) {

statements

}

# Methods

vis function method1(p1 ,...) {

statements

}

vis function methodN(p1 ,...) {

statements

}

}

• Every instance obj of thisclass will have attributesattrib1,. . . and methodsmethod1(), . . . accessibleas obj->attrib1 andobj->method1(a1...)

• __construct is theconstructor of the class andwill be called whenevernew identifier(a1,...)

is executed

• vis is a declaration of thevisibility of each attributeand method

COMP519 Web Programming Lecture 29 Slide L29 – 3

Page 664: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Classes Defining and Instantiating a Class

A Closer Look at Class Definitions

• The pseudo-variable $this is available when a method is called fromwithin an object context and is a reference to the calling object

• Inside method definitions, $this can be used to refer to the propertiesand methods of the calling object

• The object operator -> is used to access methods and properties of thecalling 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

Page 665: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Classes Visibility

Visibility

• Properties and methods can be declared aspublic accessible everywhereprivate accessible only within the same classprotected accessible only within the class itself and

by inheriting and parent classes

• For properties, a visibilitydeclaration is required

• For methods, a visibilitydeclaration is optional; by default, methods

are public

• Accessing a private orprotected property /method outside its visibilityis a fatal error

class Vis {

public $public = 1;

private $private = 2;

protected $protected = 3;

protected function proFc() {}

private function priFc() {}

}

$v = new Vis ();

echo $v->public; # prints 1

echo $v->private; # Fatal Error

echo $v->protected; # Fatal Error

echo $v->priFc (); # Fatal Error

echo $v->proFc (); # Fatal Error

COMP519 Web Programming Lecture 29 Slide L29 – 5

Page 666: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Classes Class Constants

Constants

• Classes can have their own constants andconstants 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 fatalerror ; 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

Page 667: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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) usingthe scope resolution operator ::

• Static class properties cannot be accessed via an instantiated classobject, 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

Page 668: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Classes Destructors

Destructors

• A class can have a destructor method __destruct that will be called assoon 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

Page 669: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Classes Inheritance

Inheritance

• In a class definition it is possible to specify one parent class from whicha class inherits constants, properties and methods:

class identifier1 extends identifier2 { ... }

• The constructor of the parent class is not automatically called it mustbe called explicitly from the child class

• Inherited constants, properties and methods can be overridden byredeclaring them with the same name defined in the parent class

• The declaration final can be used to prevent a method from beingoverriden

• Using parent:: it is possible to access overridden methods or staticproperties of the parent class

• Using self:: it is possible to access static properties and methods ofthe current class

COMP519 Web Programming Lecture 29 Slide L29 – 9

Page 670: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 671: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Classes Interfaces

Interfaces

• Interfaces specify which methods a class must implement withoutproviding an implementation

• Interfaces are defined in the same way as a class with the keywordclass replaced by interface

• All methods in an interface must be declared public

• A class can declare that it implements one ore more interfaces using theimplements keyword

interface Shape {

public function area ();

}

class Rectangle implements Shape {

...

}

COMP519 Web Programming Lecture 29 Slide L29 – 11

Page 672: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Classes Introspection Functions

Introspection Functions

There are functions for inspecting objects and classes:

bool class_exists(string class)

returns TRUE iff a class class existsclass_exists(’Rectangle’) # returns TRUE

string get_class(object obj)

returns the name of the class to which an object belongsget_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

Page 673: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 valuesget_object_vars($e2)

# returns ["name" => "Ben"]

get_class_methods(class)

returns an array of method names defined for classget_class_methods(’Square’)

# returns ["__construct", "area"]

COMP519 Web Programming Lecture 29 Slide L29 – 13

Page 674: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

The PDO Class Introduction

The PDO Class

• The PHP Data Objects (PDO) extension defines an interface foraccessing databases in PHP

• Various PDO drivers implement that interface for specificdatabase 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 SQLAzure

COMP519 Web Programming Lecture 29 Slide L29 – 14

Page 675: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

The PDO Class Connections

Connections

• Before we can interact with a DBMS we need to establish a connectionto 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 aninstance 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

Page 676: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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:: ATTR_DEFAULT_FETCH_MODE => PDO:: FETCH_ASSOC ,

PDO:: ATTR_EMULATE_PREPARES => 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

Page 677: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

The PDO Class Queries and Processing of Results

Queries

• The query() method of PDO objects can be used to executean SQL query

$result = $pdo->query(statement)

$result = $pdo->query("SELECT * FROM meetings")

• query() returns the result set (if any) of the SQL query as aPDOStatement 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

Page 678: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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 aPDOStatement object, we can use the fetch() method

• By default, PDO returns each row as an array indexed bythe column name and 0-indexed column position in the row

$row = $result ->fetch ()

array(’slot’ => 1,

’name’ => ’Michael North ’,

’email’ => ’[email protected]’,

0 => 1,

1 => ’Michael North ’,

2 => ’[email protected]’)

• 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 aPDOStatement object, we can use the fetchAll() method$rows = $result ->fetchAll ()

COMP519 Web Programming Lecture 29 Slide L29 – 18

Page 679: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

The PDO Class Queries and Processing of Results

Processing Result Sets

• We can use a while-loop together with the fetch() method to iterateover 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

Page 680: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

The PDO Class Queries and Processing of Results

Processing Result Sets

• Using bindColumn() we can bind a variable a particular column in theresult 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 variablesthat 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

Page 681: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

• Prepared statements can be executed repeatedly with differentarguments

• Arguments to prepared statements do not need to be quoted andbinding of parameters to arguments will automatically prevent SQLinjection

• PDO can emulate prepared statements for a DBMS that does notsupport 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

Page 682: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

The PDO Class Prepared Statements

Prepared Statements: SQL Templates

• An SQL template is an SQL query (as a string) possibily containingeither• 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 preparedstatement (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

Page 683: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

The PDO Class Prepared Statements

Prepared Statements: Binding

• We can bind the parameters of a PDOStatement object to a valueusing 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 = ’[email protected]’;

$stmt1 ->bindValue(’:email’,$email );

$stmt2 ->bindValue (1,20,PDO:: PARAM_INT );

COMP519 Web Programming Lecture 29 Slide L29 – 23

Page 684: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

The PDO Class Prepared Statements

Prepared Statements: Binding

• We can bind the parameters of a PDOStatement object to a variableusing 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 = ’[email protected]’;

$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

Page 685: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

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

Page 686: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

The PDO Class Transactions

Transactions

• There are often situations where a single ‘unit of work’ requires asequence 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

Page 687: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

The PDO Class Transactions

Transactions

To support transactions, PDO provides the methodsbeginTransaction()

– turns off auto-commit mode; changes to the database are notcommitted 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

Page 688: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

The PDO Class Transactions

Transactions: Example$pdo = new PDO(’mysql:host =...; dbname =...’,’...’,’...’,

array(PDO:: ATTR_ERRMODE => PDO:: ERRMODE_EXCEPTION ,

PDO:: ATTR_EMULATE_PREPARES => 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

Page 689: COMP519 Web Programming - Handoutscgi.csc.liv.ac.uk/~ullrich/COMP519/notes/comp519.pdf · Web Programming versus App Programming Web Programmingrelies onweb browsersas means to render

Revision and Further Reading

Revision and Further Reading

Read

• Language Reference: Classes and Objectshttp://php.net/manual/en/language.oop5.php

• The PDO Classhttp://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