COMP284 Scripting Languages
Lecture 1: Overview of COMP284
Handouts
Ullrich Hustadt
Department of Computer Science
School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
1 Introduction
Motivation
Scripting languages
2 COMP284
Aims
Learning outcomes
Delivery
Assessment
COMP284 Scripting Languages Lecture 1 Slide L1 1
Introduction Motivation
How many programming languages should you learn?
1 Academic / Educational viewpoint:
Learn programming language concepts and
use programme languages to gain practical experience with them
imperative / object-oriented C, Java
functional OCaml, Haskell
logic/constraint Prolog, DLV
concurrent Go
then all (other) programming languages can be learned easily
2 An employer’s viewpoint:
Learn exactly those programming languages that the specific employer
needs
3 Compromise: Spend most time on 1 but leave some time for 2 to
allow more than one language from a class/paradigm to be learned
4 Problem: Which additional language do you cover?
; Look what is used/demanded by employers
COMP284 Scripting Languages Lecture 1 Slide L1 2
Introduction Motivation
Our domain
In this module we are particularly interested in scripting languages used
for the development of web-based applications
Web-based applications are client-server systems where
the client software, consisting of user interface and client-side logic,
runs in a web browser
the client software issues HTTP requests to a web server to retrieve
information or to update parts of itself
a web server acts as conduit for the HTTP requests from the client software
and the HTTP responses from the server software
the server software, implementing the server-side logic, handles the request
and produces a HTTP response, in the form of a HTML document or data
the server software often interacts with a database to produce its response
COMP284 Scripting Languages Lecture 1 Slide L1 3
Introduction Motivation
Websites and programming languages
Website Client-Side Server-Side Database
Google JavaScript,
TypeScript
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 MariaDB
Twitter JavaScript C
++
, Java, Scala,
Ruby
MySQL
Bing JavaScript C
++
, C# MS SQL Server
Wikipedia Contributors: Programming languages used in most popular websites. Wikipedia, The Free Encyclopedia,
11 December 2019, at 16:24. https://en.wikipedia.org/wiki/Programming_languages_used_in_most_popular_websites
[accessed 21 December 2019]
COMP284 Scripting Languages Lecture 1 Slide L1 4
Introduction Scripting languages
Scripting languages
PHP and JavaScript are scripting languages
Script
A user-readable and user-modifiable program that performs simple
operations and controls the operation of other programs
Scripting language
A programming language for writing scripts
Classical example: Shell scripts
#!/ bin / sh
for file in *; do
wc -l " $file "
done
Print the number of lines and name for each file in the current directory
COMP284 Scripting Languages Lecture 1 Slide L1 5
Introduction Scripting languages
Scripting languages: Properties
Program code is present at run time and starting point of execution
compilation by programmer/user is not needed
compilation to bytecode or other low-level representations
may be performed ‘behind the scenes’ as an optimisation
Presence of a suitable runtime environment is required for the execution
of scripts
includes an interpreter, or just-in-time compiler, or bytecode compiler plus
virtual machine
typically also includes a large collection of libraries
Executation of scripts is typically slower then the execution of code that
has been fully pre-compiled to machine code
#!/ bin / sh
for file in *; do
wc -l " $file "
done
COMP284 Scripting Languages Lecture 1 Slide L1 6
Introduction Scripting languages
Scripting languages: Properties
Rich and easy to use interface to the underlying operating system,
in order to run other programs and communicate with them
rich input/output capabilities, including pipes, network sockets, file I/O,
and filesystem operations
Easy integration within larger systems
often used to glue other systems together
can be embedded into other applications
#!/ bin / sh
for file in *; do
wc -l " $file "
done
COMP284 Scripting Languages Lecture 1 Slide L1 7
Introduction Scripting languages
Scripting languages: Properties
Variables, functions, and methods
typically do not require type declarations
(automatic conversion between types, e.g. strings and numbers)
Lots of pre-defined functions and libraries
Lots of pre-defined functions for the specific purpose
the language was designed for
Ability to generate, load, and interpret source code at run time
through an eval function
JavaScript:
var x = 2;
var y = 6;
var str = " if (x > 0) { z = y / x } else { z = -1 }";
con sole . log(' z is ', eval ( str )); // Output : z is 3
x = 0;
con sole . log(' z is ', eval ( str )); // Output : z is -1
COMP284 Scripting Languages Lecture 1 Slide L1 8
Introduction Scripting languages
Scripting languages: Properties
The evolution of a scripting language typically starts
with a limited set of language constructs for a specific purpose
Example: PHP started as set of simple ‘functions’
for tracking visits to a web page
The language then accumulates more and more language constructs
as it is used for a wider range of purposes
These additional language constructs may or may not fit well together
with the original core and/or may duplicate existing language constructs
During this evolution of the language, backward compatibility
may or may not be preserved
; Language design of scripting languages is often sub-optimal
COMP284 Scripting Languages Lecture 1 Slide L1 9
COMP284 Aims
Aims
1 To provide students with an understanding of
the nature and role of scripting languages
2 To introduce students to some popular scripting languages
and their applications
3 To enable students to write simple scripts using these languages
for a variety of applications
COMP284 Scripting Languages Lecture 1 Slide L1 10
COMP284 Learning outcomes
Learning Outcomes
At the end of the module students should be able to
1 develop server-side web-based applications
using an appropriate scripting language,
with emphasis on concurrent use of such applications
2 develop computer-based or client-side web-based applications
using an appropriate scripting language
COMP284 Scripting Languages Lecture 1 Slide L1 11
COMP284 Delivery
Delivery of the module (1)
1 Lectures
Structure:
14 lectures
Schedule:
1–2 lectures per week spread over 10 weeks
See your personal timetable and e-mail announcements for details
Lecture notes and screencasts are available at
https://cgi.csc.liv.ac.uk.uk/
~
ullrich/COMP284/notes
Revise the lectures before the corresponding practical
Additional self study using the recommended textbooks
and the on-line material is essential
COMP284 Scripting Languages Lecture 1 Slide L1 12
COMP284 Delivery
Delivery of the module (1)
2 Practicals
Structure:
1 practical to re-familiarise you with Linux
4 practicals with worksheets (2 PHP, 2 JavaScript)
; gain understanding via practice
; get answers to questions about the lecture material
Up to 2 additional practicals for questions about the assignments
Schedule:
1 practical per week for about 10 weeks
Practicals start in week 1
Practicals assume familiarity with the related lecture material
COMP284 Scripting Languages Lecture 1 Slide L1 13
COMP284 Delivery
How to learn a new programming language
Once you know how to program in one programming language,
additional programming languages are best learned by a process of
enquiry and practice guided by existing experience
Typically, the questions that guide you are
What kind of . . . are there?
Example: What kind of control structures are there?
What is the syntax for . . . ?
Example: What is the syntax for conditional statements?
What happens if . . . ?
Example: What happens if 1 is divided by 0?
How do I . . . ?
Example: How do I catch an exception?
Talk to other people who are currently trying to learn the same
language or have already learned it
; Ask what has surprised them most
COMP284 Scripting Languages Lecture 1 Slide L1 14
COMP284 Delivery
How to learn a new programming language
Once you know how to program in one programming language,
additional programming languages are best learned by a process of
enquiry and practice
The best kind of learning is learning by doing
; The questions posed on the previous slide are often best explored
by experimenting with small sample programs (‘toy’ programs)
Work on substantive programs
; You need to convince employers that you have worked on programs
more substantive than ‘toy’ programs
; The assignments are ‘pretend’ substantive programs
but in reality are too small
Employers value experience, in particular, the experience that you get
from overcoming challenges
; Assignments that are not challenging are of limited value
COMP284 Scripting Languages Lecture 1 Slide L1 15
COMP284 Delivery
Delivery of the module (3)
3 Office hours
Wednesday, 14:00 Ashton, Room 1.03
but always arrange a meeting by e-mail first
(U.Hustadt@liverpool.ac.uk)
4 Announcements will be send by e-mail
You should check you university e-mail account at least every other day
Always use your university e-mail account
if you want to contact me or any other member of staff
COMP284 Scripting Languages Lecture 1 Slide L1 16
COMP284 Delivery
Recommended texts
Core reading
R. Nixon:
Learning PHP, MySQL, & JavaScript. Learning PHP. . . , 4th edition.
O’Reilly, 2009. O’Reilly, 2014.
Harold Cohen Library: 518.561.N73 or e-book
Further reading
M. David:
HTML5: designing rich Internet applications.
Focal Press, 2010.
Harold Cohen Library: 518.532.D24 or e-book
N. C. Zakas:
Professional JavaScript for Web Developers.
Wiley, 2009.
Harold Cohen Library: 518.59.Z21 or e-book
COMP284 Scripting Languages Lecture 1 Slide L1 17
COMP284 Assessment
Assessment
This is a coursework-based module
(no exam)
Two assessment tasks need to be completed throughout the semester:
PHP Deadline: Monday, 4 March, 12:00 Deadline:
Monday, 25 March, 12:00
JavaScript Deadline: Thursday, 2 May, 17:00 Deadline:
Monday, 25 March, 12:00
Effort required: about 15 hours each
Available at: https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/
COMP284 Scripting Languages Lecture 1 Slide L1 18
COMP284 Assessment
Academic Integrity
Plagiarism occurs when a student misrepresents, as his/her own work,
the work, written or otherwise, of any other person (including another
student) or of any institution
Collusion occurs where there is unauthorised co-operation between a
student and another person in the preparation and production of work
which is presented as the student’s own
Fabrication of data occurs when a student enhances, exaggerates, or
fabricates data in order to conceal a lack of legitimate data
If you are found to have plagiarised work, colluded with others, or
fabricated data, then you may fail COMP284
Serious ‘offenders’ may be excluded from the University
Do not try to take a ‘shortcut’
You must do the work yourself!
COMP284 Scripting Languages Lecture 1 Slide L1 19
COMP284 Assessment
Academic Integrity: Lab rules
Do not ask another student to see any part of their code for a
COMP284 assignment
; contravention of this leads to collusion
Do not show or make available any part of your code relating for a
COMP284 assignment to any other student
; contravention of this leads to collusion
Do not share (links to) on-line material that might help with a
COMP284 assignment
; contravention of this leads to collusion
Lock your Lab PC when you leave it alone
Where you use any material/code found on-line for a COMP284
assignment, you must add comments to your code indicating its origin
by a proper academic reference
; contravention of this is plagiarism
; acknowledged code re-use may still result in a lower mark
COMP284 Scripting Languages Lecture 1 Slide L1 20
COMP284 Scripting Languages
Lecture 2: CGI Programming
Handouts
Ullrich Hustadt
Department of Computer Science
School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
3 HTML Primer
Forms
Overview
Form Controls
Input
Select
4 CGI
Overview
CGI I/O
5 Python CGI Programs
Motivation
Accessing Environment Variables: The os Module
Accessing Form Data: The cgi Module
Example
6 Revision and Further Reading
COMP284 Scripting Languages Lecture 2 Slide L2 1
HTML Primer
Web-based applications: Interfaces
Web-based applications are client-server application where
the client software, consisting of user interface and client-side logic,
runs in a web browser
static aspects of a user interface are realised using HTML
; form elements with form controls allow a user to enter inputs
the client software incorporates user inputs into an HTTP request it
sends to a web server to retrieve information or to update parts of itself
the web server uses a program or programs, the server software, to
compute an HTTP response that it sends back to the web browser
Web Browser
Client
Software
Web
Server
Server
Software
HTTP Request
HTTP Response
COMP284 Scripting Languages Lecture 2 Slide L2 2
HTML Primer
HTML5 elements
An HTML element is an individual component of an HTML document.
Most elements consist of a start tag and a matching end tag,
with some content in between
The content of an element can consist of other element
; HTML elements can be nested
; HTML documents can be viewed as trees of HTML elements
The general form of a start tag
< tagName attrib1 =" value1 " ... attribN =" valueN " >
where tagName is a non-empty sequence of alphanumeric ASCII chars,
attrib1,. . . ,attribN, N 0, are attributes and
value1,. . . ,valueN, N 0, are attribute values
attribute order is irrelevant
A end tag / closing tag takes the form
</ tagName >
COMP284 Scripting Languages Lecture 2 Slide L2 3
HTML Primer
HTML5 elements
So-called void elements only have a start tag
area base br col embed hr img
input keygen link meta param source track wbr
Since void elements have no content they cannot be nested
The start tags of void elements can be made self-closing by ending the
tag with /> instead of >, optionally preceded by a space
Examples:
<br > <br /> <br />
COMP284 Scripting Languages Lecture 2 Slide L2 4
HTML Primer
HTML5 documents
An HTML5 document has a very simple form:
It consists of a DOCTYPE-declaration and an html-element
<! DOCTYP E html >
html -eleme nt
An html-element has the form
<html >
head -eleme nt
body -eleme nt
</ html >
It is recommended that the start tag of an html-element specifies the
language used in the document
< html lang = ' en-GB ' >
COMP284 Scripting Languages Lecture 2 Slide L2 5
HTML Primer Forms
Forms
A form is an HTML element that contains form controls, such as
text fields, buttons, checkboxes, range controls, or color pickers
Forms allow users to enter data which can then be sent to a web server
for processing
A form element has several (optional) attributes, including
action: URL to use for form submission
method: HTTP method to use for form submission (get or post)
enctype: encoding type to use for form submission
novalidate: form is not validated during submission
< form action = ' https :// sam . csc . liv. ac. uk/ COMP / Calendar .pl '
method = ' post ' enct ype = ' text / plain ' >
</ form >
A form can be submitted and on submission the data entered via the
form controls will be send to the URL in action using the
HTTP request method in method with encoding type enctype
COMP284 Scripting Languages Lecture 2 Slide L2 6
HTML Primer Form Controls
Input
The input element represents a ‘field’ that allows the user to enter
data of a certain type
The input element is void elementx
The type attribute of an input element determine what type of data
can be entered and in what form
Value of Data Form
type type control
text Text with no line breaks Text field
number Floating-point number Text field or spinner
password Password Text field with obscured input
button Button
submit Initiates form submission Button
reset Resets form Button
< input type = ' text ' >
< input type = ' reset ' >
COMP284 Scripting Languages Lecture 2 Slide L2 7
HTML Primer Form Controls
Input
The input element represents a ‘field’ that allows the user to enter
data of a certain type
Common attributes of an input element 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
Depending on the value of the type attribute, an input element will
have additional attributes that define its behaviour
< input type = ' number ' name =' studentid ' id=' sid '
min = ' 190000000 ' max = ' 999999999 ' >
COMP284 Scripting Languages Lecture 2 Slide L2 8
HTML Primer Form Controls
Label
In order for a form to be usable, each form control should be
accompanied by an indication of what it is for or how it should be used
Example: ‘Surname’ or ‘Enter your surname’ next to a field into which
the user is meant to enter their surname
A label element represents such an indication (a caption)
A label element can be associated with a specific form control either
using its for attribute or by putting the form control inside the label
element itself
< label for =' s1 ' > Surname : </ label >
< input type = ' text ' name =' surname ' id=' s1 ' >
<label > First name ( s ):
< input type = ' text ' name =' first ' id ='f1 ' > </label >
COMP284 Scripting Languages Lecture 2 Slide L2 9
HTML Primer Form Controls
Input
< form action = ' p ro ce ss .py ' >
< label for='s1 '>Surname : </ label >
< input type = ' text ' name = ' surname ' id='s1 '>
<label > Firs t name : <i nput type = ' text ' name = ' first ' id = ' f1 ' >
</ label >
<label > Stu de nt ID : < input type = ' number ' name =' studentid ' id=' sid '
min = '190000000 ' max = ' 999999999 ' > </ label >
< input type =" s ub mit ">
</form >
On submission, the web browser will construct pairs name=value where
name is the value of the name attribute of one of the form controls and
value is the input by the user for that form control
A string composed of those pairs will be send to process.py
Example:
Peters, Amy Lee, and 201612345 are entered into the three fields
; surname=Peters, first=Amy+Lee, and studentid=201612345
are sent to process.py
COMP284 Scripting Languages Lecture 2 Slide L2 10
HTML Primer Form Controls
Input
< form action = ' p ro ce ss .py ' >
< label for='s1 '>Surname : </ label >
< input type = ' text ' name =' surname ' id=' s1 '>
<label > Firs t name : <i nput type = ' text ' name = ' first ' id = ' f1 ' >
</ label >
<label > Stu de nt ID : < input type = ' number ' name =' studentid ' id=' sid '
min = '190000000 ' max = ' 999999999 ' > </ label >
< input type = ' submit ' >
</form >
This form can be submitted by either activating the ‘Submit’ button or
by pressing the return key within one of the three input fields
Form submission is possible even with all input fields being empty,
even the one for the StudentID
; we need to add the required attribute to prevent empty inputs
The StudentID field accepts floating point numbers between the
specified min and max values
; 1.9e8 is accepted and studentid=1.9e8 send to process.php
COMP284 Scripting Languages Lecture 2 Slide L2 11
HTML Primer Form Controls
Select
A select element represents a drop-down menu with pre-defined
options between which the user must select
The content of a select element consists of a list of option elements
that represent those options
A select-element can have several attributes, including
id: unique id used to identify the element with the document
name: (unique) name used by the form processor to access input
multiple: allow multiple options to be selected
required: an option must be selected that has a non-empty value
disabled: the current selection can not be changed
size: number of options to show to the user
An option element can have several attributes, including
label: the label used in the drop-down menu
value: the value returned for the option
selected: the option is selected by default
disabled: the option is shown but cannot be selected
COMP284 Scripting Languages Lecture 2 Slide L2 12
HTML Primer Form Controls
Select
A select element represents a drop-down menu with pre-defined
options between which the user must select
(often preferred over a radio button group)
The content of a select element consists of a list of option elements
that represent those options
< label for =' title ' > Select a module : </ label >
< select name = ' module ' >
< option value = ' COMP201 ' > COMP201 : Softw are Engin eerin g I
</ option >
< option value = ' COMP207 ' > COMP207 : Datab ase Devel opmen t
</ option >
< option value = ' COMP519 ' > COMP211 : Compu ter Networks
</ option >
</ select >
COMP284 Scripting Languages Lecture 2 Slide L2 13
HTML Primer Form Controls
Select
< form action = ' process . py ' >
< label for =' module ' > Select a modu le : </ label >
< select name = ' module ">
< option value = ' COMP201 ' > COMP201 : Software Engin eerin g I
</ option >
< option value = ' COMP207 ' > COMP207 : Database Devel opmen t
</ option >
< option value = ' COMP519 ' > COMP211 : Computer Networks
</ 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=COMP201 is sent to process.py
In general, the value associated with the selected option will be send
COMP284 Scripting Languages Lecture 2 Slide L2 14
HTML Primer Form Controls
Select
< form action = ' process . py ' >
< label for =' module ' > Select a modu le : </ label >
< select name = ' module ' >
< option value = ' COMP201 ' > COMP201 : Software Engin eerin g I
</ option >
< option value = ' COMP207 ' selected >
COM P207 : Database D evelopment </ option >
< option value = ' COMP519 ' disabled >
COM P211 : Computer Networks
</ option >
</ select >
< input type = ' submit ' >
</ form >
Adding the attribute selected to an option,
makes it the option that is selected by default
Adding the attribute disabled to an option,
makes it impossible to select that option
If the selection is not changed and the user activates the submit button,
then module=COMP207 is sent to process.py
COMP284 Scripting Languages Lecture 2 Slide L2 15
HTML Primer Form Controls
Select
< form action = ' process . py ' >
< select name =" mod ule " required >
< option value = ' ' > Select a module </ option >
< option value = ' COMP201 ' > COMP201 : Software Engin eerin g I
</ option >
< option value = ' COMP207 ' > COMP207 : Database Devel opmen t
</ option >
< option value = ' COMP211 ' > COMP211 : Computer Networks
</ option >
</ select >
< input type = ' submit ' >
</ form >
That an option with a non-empty value is pre-selected is often not
desirable
; the user does not need to make a conscious choice
Adding a default option with empty value and adding the attribute
required to the select element forces the user to make a conscious
choice
COMP284 Scripting Languages Lecture 2 Slide L2 16
CGI Overview
Common Gateway Interface CGI
The Common Gateway Interface (CGI) is a standard method
for web servers to use an external application, a CGI program,
to dynamically generate web pages
1 A web client generates an HTTP 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 HTTP request to a CGI request, executes the program
3 The CGI program then processes the CGI request and
the server passes the program’s response back to the client
COMP284 Scripting Languages Lecture 2 Slide L2 17
CGI CGI I/O
HTTP Requests and HTML Forms
In the following we focus on HTTP requests that are generated
using HTML forms
< html lang = ' en - GB ' >
<head ><title > Userna me Generator </ title > </ head >
<body >
< form action = ' generate . py ' method = ' post ' >
<label > Enter your full name :
< input type = ' text ' name =' fullname ' >
</ label >
<label > Select your year of r egist ration :
< select name = ' year ' >
<option >-- - - </ option >
<option >2010 </ option > ... < option >2020 </ option >
</ select >
</ label >
< input type = ' submit ' name =' submit ' value =' Generate ' >
</ form >
</ body > </ html >
COMP284 Scripting Languages Lecture 2 Slide L2 18
CGI CGI I/O
HTTP Requests and HTML Forms
In the following we focus on client requests that are generated
using HTML forms
< html lang = ' en - GB ' >
<head > < title > Us er name Genera tor </ title > </ head >
<body >
< form ac ti on =' generate .py ' method = ' post ' >
<label > Enter your full name :
< input type=' text ' name = ' fullnam e '>
</ label >
<label > Select your year of r eg istra tion :
< se le ct name =' year ' >
<option >---- </ option >
<option >2010 </ option > ... < option >2020 </ option >
</ select >
</ label >
< input type=' submit ' name =' submit ' valu e = ' Generat e '>
</form >
</body > </ html >
COMP284 Scripting Languages Lecture 2 Slide L2 19
CGI CGI I/O
HTTP Requests: Encoding of form data
Input data from an HTML form is sent URL-encoded as sequence of
key-value pairs: key1=value1&key2=value2&...
fullname = David %20 Davidson & year =2018& submit = Gen erate
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 %25
+ is represented as %2B ' is represented as %27
COMP284 Scripting Languages Lecture 2 Slide L2 20
CGI CGI I/O
HTTP Requests: GET versus POST: Client
The two main request methods used with HTML forms
are GET and POST:
GET:
The browser appends form data to the URI in the request
<scheme> "://" <server-name> ":" <server-port>
<script-path> <extra-path> "?" <query-string>
Limited to 1KB to 8KB characters depending on both browser and server
Requests remain in the browser history and can be bookmarked
Requests should not be used for sensitive data, e.g. passwords
POST:
The browser appends form data to the body of the request
No limit on the length/size of the form data
Requests do not remain in the browser history and cannot be bookmarked
Requests are suitable for the transfer of sensitive data, e.g. passwords
COMP284 Scripting Languages Lecture 2 Slide L2 21
CGI CGI I/O
HTTP Requests: GET versus POST: Server
The two main request methods used with HTML forms
are GET and POST:
GET:
Form data is provided to CGI programs via the QUERY_STRING
environment variable,
a name/value pair that is part of the environment in which a
process/programs is run by the operating system
Standard input is empty
POST:
The QUERY_STRING environment variable is empty
Form data is provided to CGI programs via standard input
COMP284 Scripting Languages Lecture 2 Slide L2 22
CGI CGI I/O
HTTP Requests: GET versus POST: Server
The two main request methods used with HTML forms
are GET and POST:
Both
Env variable Meaning
REQUEST_METHOD The request method that was used
HTTP_USER_AGENT The browser issuing the request
HTTP_REFERER The URL of the document that the browser
points to before accessing the CGI program
HTTP_ACCEPT A list of the MIME types that the browser can
accept
REMOTE_ADDR The remote IP address of the device from
which the request came
COMP284 Scripting Languages Lecture 2 Slide L2 23
Python CGI Programs Motivation
CGI programs and Python
CGI programs need to process form data from environment variables
and STDIN, depending on the request method
; preferably, the form data would be accessible by the program
in a uniform way
CGI programs need to process form data that is encoded
; preferably, the form 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 environ dictionary of the os module
to access environment variables
the cgi module to process form data
print statements to produce HTML markup
COMP284 Scripting Languages Lecture 2 Slide L2 24
Python CGI Programs Accessing Environment Variables: The os Module
Accessing Environment Variables
The module os provides the environ dictionary
The environ dictionary maps a script’s environmental variables as keys
to the values of those variables
os . environ [ ' REQU EST_METHOD ']
os . environ [ ' HTTP _USE R_AG ENT ']
os . environ [ ' HTTP_REFERER ']
os . environ [ ' HTTP_ACCEPT ']
os . environ [ ' REMOTE_ADDR ']
os . environ [ ' QUERY_STRING ']
GET
... Chrome /78.0 .3904. 85 ...
https :// stu dent . csc . liv. ac.
,uk/cgi - bin / cgiwrap /uh /
,generate . py
text / html , appli cation / xhtml +
,xml , app licati on / xml ;q
,=0.9 , image / webp , image /
,apng ,*/*; q =0.8 ,
,app lication / signed -
,exchange ;v=b3 ;q =0.9
212.1 49.127 .43
empty
COMP284 Scripting Languages Lecture 2 Slide L2 25
Python CGI Programs Accessing Form Data: The cgi Module
Accessing Form Data
The module cgi provides methods to access the input data of
HTML forms in a two step process:
1 Create an instance of the FieldStorage class and assign it to a
variable
variable = cgi . Fi eldStorage ()
This reads the form data from standard input or the environment
variable QUERY_STRING
2 Then
variable['name'].value
variable.getvalue('name')
variable.getfirst('name', default=None)
variable.getlist('name')
return the value/values entered for the form control with name name
COMP284 Scripting Languages Lecture 2 Slide L2 26
Python CGI Programs Example
Example
We want to develop a CGI program for a Username Generator with the
following functionality
Access is restricted to IP addresses starting with 138.253
(University of Liverpool IP addresses)
The program prints out an HTML document with an HTML form that
allows a user to enter the data required for our program
The drop-down menu should cover the previous nine years
On submission of the completed form, the program
generates a username based on the data entered into that form
prints out an HTML document with that username
COMP284 Scripting Languages Lecture 2 Slide L2 27
Python CGI Programs Example
Example: HTML Wrapper
It makes sense to define functions that print out the
initial (up to body start) and final HTML markup (from body end)
# htm lUH . py
def star tHTML ( title ):
print ( '' '\
Content - type : text / html
<! DOCTYP E html >
< html lang = ' en - GB ' >
<head >
< meta charset = ' utf -8' >
< link rel =' stylesheet ' type = ' text / css '
href = ' form . css ' >
<title >''' + title + ' ' ' </ title >
</ head >< body > ' ' ')
def endHTML ():
print ( ' ' ' </ body > </ html > ' ' ')
COMP284 Scripting Languages Lecture 2 Slide L2 28
Python CGI Programs Example
Example: HTML Form
def prin tForm ():
print ( '' '\
< form action = ' generate . py ' method = ' post ' >
<label > Enter your full name :
< input type = ' text ' name =' fullname ' >
</ label >
<label > Select your year of r egist ration :
< select name = ' year ' >
<option >-- - - </ option >' ' ')
now = datetime . dat etime . now ()
for year in range ( now . year -9 , now . year +1):
print ( ' < option > ' , year , ' </ option > ')
print ( '' '\
</ select >
</ label >
< input type = ' submit ' name =' submit ' value =' Generate ' >
</ form > ' ' ')
COMP284 Scripting Languages Lecture 2 Slide L2 29
Python CGI Programs Example
Example: Username
Simple function for generating a username from the full name of a user
and the year the user has registered
def genUs ernam e ( name , year ):
# first let ter of given name
return (" sg" + name . split () [0][0 ]. lower ()
# first three l etters of surname
+ name . split ()[1 ][:2] . lower ()
# last to digits of year
+ str ( year )[2:4] )
COMP284 Scripting Languages Lecture 2 Slide L2 30
Python CGI Programs Example
Example: Putting everything together
#!/ usr / bin / pyt hon3
# gen erate . py
import os , sys , codecs , datetime , local e
from htm lUH import star t_ html , end_html
start_html (" Ge nerat e Use rname ")
if ( os . environ [" R EMO TE_ ADD R "][ 0:7] != "138.253"):
pr int ( ' < div > <b> Sorry , please come back \
when you are on a uni computer </b > </ div > ')
else :
inputs = cgi. F iel dSt ora ge ()
if in puts . getvalu e (' submit '):
# Form has been c omp leted and su bmi tted
name = inpu ts [' fullname ']. value
year = inpu ts [' year ']. value
usern ame = gen Username ( name , year )
print ( ' < div > The user name for ' + name + ' r egistered in '
+ year + ' is ' + us ername + ' </div >)
else :
# Show user the form
printFor m ()
end_h tml ()
COMP284 Scripting Languages Lecture 2 Slide L2 31
Python CGI Programs Example
Example: Making it work
To make the CGI script generate.py
accessible via our departmental web server it must be placed in a
directory
user/public_html/cgi-bin/
The directories
user, public_html and cgi-bin must by
world-executable
The script must be executable by the user
It can then be accessed via
https://student.csc.liv.ac.uk/cgi-bin/cgiwrap/
user/generate.py
If we open that URL in a browser we see
We can then complete the form and activate ‘Generate’
The browser will then show
COMP284 Scripting Languages Lecture 2 Slide L2 32
Revision and Further Reading
Revision and Further Reading
To get familiar with HTML5, read Chapters 4 to 9 of
J. Niederst Robbins:
Learning Web Design: A Beginner’s Guide to HTML, CSS,
JavaScript, and Web Graphics (5th ed).
O’Reilly, 2018.
E-book https://library.liv.ac.uk/record=b5647021
For information on modules for CGI programming in Python see
cgi: Common Gateway Interface support
https://docs.python.org/3/library/cgi.html
os: Miscellaneous operating system interfaces
https://docs.python.org/3/library/os.html
of Python Software Foundation: The Python Standard Library.
Python.org, 23 December 2019.
https://docs.python.org/3/library
[accessed 24 December 2019]
COMP284 Scripting Languages Lecture 2 Slide L2 33
COMP284 Scripting Languages
Lecture 3: PHP (Part 1)
Handouts
Ullrich Hustadt
Department of Computer Science
School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
7 PHP
Motivation
8 Overview
Features
Applications
9 Types and Variables
Types
Integers and Floating-point numbers
Booleans
Strings
Variables
10 Type juggling and Type casting
11 Further Reading
COMP284 Scripting Languages Lecture 3 Slide L3 1
PHP Motivation
Common Gateway Interface CGI
The Common Gateway Interface (CGI) is a standard method for web
servers to use external applications, a CGI program, to dynamically
generate web pages
1 A web client generates a client request, for example, from a HTML
form, and sends it to a web server
2 The web server selects a CGI program to handle the request,
converts the client request to a CGI request, executes the program
3 The CGI program then processes the CGI request and the server passes
the program’s response back to the client
COMP284 Scripting Languages Lecture 3 Slide L3 2
PHP Motivation
Disadvantages of CGI
A distinction is made between static web pages and
dynamic web pages created by external CGI programs
Using CGI programs it is difficult to add ‘a little bit’ of
dynamic content to a web page
; can be alleviated to some extent by ‘packing’ big chunks
of HTML markup into a few 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
COMP284 Scripting Languages Lecture 3 Slide L3 3
Overview Features
PHP
PHP is (now) a recursive acronym for PHP: Hypertext Preprocessor
Development started in 1994 by Rasmus Lerdorf
Originally designed as a tool for tracking visitors at Lerdorf’s website
Developed into full-featured, scripting language for
server-side web programming
Shares a lot of the syntax and features with other languages
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; compatibility
problems between PHP 5.x and PHP 7.x (PHP 6 was never released)
COMP284 Scripting Languages Lecture 3 Slide L3 4
Overview Features
PHP processing
Server plug-ins exist for various web servers
; avoids the need to execute an external program
PHP code is embedded into HTML pages using tags
; static web pages can easily be turned into dynamic ones
PHP satisfies the criteria we had for a good web scripting language
Processing proceeds as follows:
1 The web server receives a client request
2 The web server recognizes that the client request is for
a HTML document containing PHP code
3 The server executes the PHP code, substitutes output
into the HTML document, the resulting page is then send to the client
As in the case of CGI programs, the client never sees the PHP code,
only the HTML document that is produced
COMP284 Scripting Languages Lecture 3 Slide L3 5
Overview Applications
PHP: Applications
Applications written using PHP
activeCollab Project Collaboration Software
http://www.activecollab.com/
Drupal Content Management System (CMS)
http://drupal.org/home
Magento eCommerce platform
http://www.magentocommerce.com/
MediaWiki Wiki software
http://www.mediawiki.org/wiki/MediaWiki
Moodle Virtual Learning Environment (VLE)
http://moodle.org/
Sugar Customer Relationship Management (CRM) platform
http://www.sugarcrm.com/crm/
WordPress Blogging tool and CMS
http://wordpress.org/
COMP284 Scripting Languages Lecture 3 Slide L3 6
Overview Applications
PHP: Websites
Websites using PHP:
Delicious social bookmarking
http://delicious.com/
Digg social news website
http://digg.com
Facebook social networking
http://www.facebook.com
Flickr photo sharing
http://www.flickr.com
Frienster social gaming
http://www.frienster.com
SourceForge web-based source code repository
http://sourceforge.net/
Wikipedia collaboratively built encyclopedia
http://www.wikipedia.org
COMP284 Scripting Languages Lecture 3 Slide L3 7
Overview Applications
Recommended texts
R. Nixon:
Learning PHP, MySQL, and JavaScript.
O’Reilly, 2009.
Harold Cohen Library: 518.561.N73 or e-book
(or later editions of this book)
M. Achour, F. Betz, A. Dovgal, N. Lopes,
H. Magnusson, G. Richter, D. Seguy, J. Vrana, et al.:
PHP Manual.
PHP Documentation Group, 2018.
http://www.php.net/manual/en/index.php
COMP284 Scripting Languages Lecture 3 Slide L3 8
Overview Applications
PHP: Hello World!
<! DOCTYP E html >
< html lang = " en - GB " >
<head ><title > Hello World </ title > </head >
<body >
<p > Our first PHP script </ p >
<? php
print ( " <p><b> Hello World ! </b > </p >\n" );
?>
</ body > </ html >
PHP code is enclosed between <?php and ?>
File must be stored in a directory accessible by the web server, for
example $HOME/public_html, and be readable by the web server
File name must have the extension .php, e.g. hello_world.php
COMP284 Scripting Languages Lecture 3 Slide L3 9
Overview Applications
PHP: Hello World!
Since version 4.3.0, PHP also has a command line interface
# !/ usr / bin / php
<? php
/* Author : Ull rich Hustadt
A " Hello World " PHP script . */
print ( " Hello World !\n" );
// A single - line comment
?>
PHP code still needs to be enclosed between <?php and ?>
Code must be stored in an executable file
File name does not need to have any particular format
; PHP can be used to write CGI programs
; PHP can be used as a scripting language outside a web program-
ming context
Output:
Hello World !
COMP284 Scripting Languages Lecture 3 Slide L3 10
Overview Applications
PHP: Hello World!
<! DOCTYP E html >
< html lang = " en - GB " >
<head ><title > Hello World </ title > </head >
<body ><p > Our first PHP script </ p >
<? php
print ( " <p><b> Hello World ! </b > </p >\n" );
?>
</ body > </ html >
Can also be ‘executed’ using
php filename
File does not need to be exectuable, only readable for the user
Output:
<! DOCTYP E html >
< html lang = " en - GB " >
<head ><title > Hello World </ title > </head >
<body ><p > Our first PHP script </ p >
<p ><b > Hello World !</b > </p >
</ body > </ html >
COMP284 Scripting Languages Lecture 3 Slide L3 11
Overview Applications
PHP scripts
PHP scripts are typically embedded into HTML documents and are
enclosed between <?php and ?> tags
A PHP script consists of one or more statements and comments
; there is no need for a main function (or classes)
Statements end in a semi-colon
Whitespace before and in between statements is irrelevant
(This does not mean its irrelevant to someone reading your code)
One-line comments start with // or # and run to the end of the line or ?>
Multi-line comments are enclosed in /* and */
COMP284 Scripting Languages Lecture 3 Slide L3 12
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
COMP284 Scripting Languages Lecture 3 Slide L3 13
Types and Variables Integers and Floating-point numbers
Integers and Floating-point numbers
PHP distinguishes between
integer numbers 0 2012 -40 1263978
floating-point numbers 1.25 256.0 -12e19 2.4e-10
PHP supports a wide range of pre-defined mathematical functions
abs(number) absolute value
ceil(number) round fractions up
floor(number) round fractions down
round(number [,prec,mode]) round fractions
log(number [,base]) logarithm
rand(min,max) generate an integer random number
sqrt(number) square root
PHP provides pre-defined number constants including
M_PI 3.14159265358979323846
NAN ‘not a number’
INF ‘infinity’
COMP284 Scripting Languages Lecture 3 Slide L3 14
Types and Variables Integers and Floating-point numbers
Integers and Floating-point numbers: NAN and INF
The constants NAN and INF are used as return values for some applications
of mathematical functions that do not return a number
log(0) returns -INF (negative ‘infinity’)
sqrt(-1) returns NAN (‘not a number’)
In PHP 5
1/0 returns FALSE and produces a PHP warning
0/0 returns FALSE and produces a PHP warning
and execution of the script continues!
In PHP 7
1/0 returns INF and produces a PHP warning
0/0 returns NAN and produces a PHP warning
and execution of the script continues!
COMP284 Scripting Languages Lecture 3 Slide L3 15
Types and Variables Booleans
Booleans
PHP has a boolean datatype
with constants TRUE and FALSE (case insensitive)
PHP offers the same short-circuit boolean operators as Java and
JavaScript:
&& (conjunction) || (disjunction) ! (negation)
Alternatively, and and or can be used instead of && and ||, respectively
However, not is not a PHP operator
The truth tables for these operators are the same as for JavaScript
Remember that && and || are not commutative, that is,
(A && B) is not the same as (B && A)
(A || B) is not the same as (B || A)
COMP284 Scripting Languages Lecture 3 Slide L3 16
Types and Variables Booleans
Type conversion to boolean
When converting to boolean, the following values are considered FALSE:
the boolean FALSE
the integer 0 (zero)
the float 0.0 (zero)
the string '0' (but not 0.0 nor '00')
the empty string ''
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)
When converting a boolean to a string,
TRUE becomes "1"
FALSE becomes ""
COMP284 Scripting Languages Lecture 3 Slide L3 17
Types and Variables Strings
Strings
PHP supports both single-quoted and double-quoted strings
PHP also supports heredocs as a means to specify multi-line strings
<<< iden tifie r
here d ocument
iden tifie r
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
<img alt =" Pi ctur e of Crowne Plaza " src ="pic .png ">
</ body >
</ html >
EOF ;
COMP284 Scripting Languages Lecture 3 Slide L3 18
Types and Variables 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
COMP284 Scripting Languages Lecture 3 Slide L3 19
Types and Variables Strings
Strings
Variable interpolation is applied to double-quoted strings
$title = " St ring Ope rators ";
print " <title > $title </ title >";
<title > String Operators </ title >
The string concatenation operator is denoted by .
The string multiplication / repetition operator in PHP is
string str_repeat(string_arg, number)
$st ring = " <p>I shall not repe at myself . <p >\ n " ;
print " <body > " . str_re peat ( $string ,3) . ' </ body > ';
<body ><p >I shall not repeat myself . <p >
<p >I shall not r epeat myself . <p >
<p >I shall not r epeat myself . <p >
</ body >
COMP284 Scripting Languages Lecture 3 Slide L3 20
Types and Variables Variables
Variables
All PHP variable names start with $ followed by a PHP identifier
A PHP identifier consists of letters, digits, and underscores,
but cannot start with a digit
PHP identifiers are case sensitive
In PHP, a variable does not have to be declared before it can be used
A variable also does not have to be initialised before it can be used,
although initialisation is a good idea
Uninitialized variables have a default value of their type depending on
the context in which they are used
Type Default Type Default
bool FALSE string empty string
int/float 0 array empty array
If there is no context, then the default value is NULL
(Not 100% true, e.g., $uninitialized-- is NULL not -1)
COMP284 Scripting Languages Lecture 3 Slide L3 21
Types and Variables Variables
Assignments
Just like Java and Python, PHP uses the equality sign =
for assignments
$stu dent_id = 2008 46369 ;
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
COMP284 Scripting Languages Lecture 3 Slide L3 22
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
// Conv ert Fahr enhei t to Cel sius :
// Subtract 32 , then multiply by 5, then divide by 9
$tem peratu re = 105; // temper ature in Fahrenheit
$tem peratu re -= 32;
$tem peratu re *= 5;
$tem peratu re /= 9; // conve rted to Celsius
COMP284 Scripting Languages Lecture 3 Slide L3 23
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 scalar type
(In PHP 7, expr can also be an array)
case_insensitive is an optional boolean argument, indicating
whether the name of the constant is case-insensitive (default is FALSE)
returns TRUE on success or FALSE on failure
define ( " PI" ,3.14159);
define ( " SPEED _ OF_LIG HT " ,299792458 , true );
// PHP 7
define ( " ANI MALS " ,[" bird" ," cat" ," dog " ]);
COMP284 Scripting Languages Lecture 3 Slide L3 24
Types and Variables Variables
Constants
To use a constant we simply use its name
define ( " PI" ,3.14159);
define ( " SPEED _ OF_LIG HT " ,299792458 , true );
// PHP 7
define ( " ANI MALS " ,[" bird" ," cat" ," dog " ]);
$cir cumfen ce = PI * $ diam eter ;
$distanc e = speed_ of_lig h t * $ time ;
$myPet = ANI MALS [1];
Caveat: PHP does not resolve constants within double-quoted strings
(or here documents)
print " 1 - Value of PI: PI\n";
1 - Value of PI: PI
print " 2 - Value of PI: " . PI . " \n";
2 - Value of PI: 3.14159
COMP284 Scripting Languages Lecture 3 Slide L3 25
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: '. gett ype (23.0). " \ n ";
print ' Type of "23": '. gett ype ( " 23 " ). " \ n " ;
if ( is _int (23)) { echo " 23 is an int eger \ n"; }
else { echo " 23 is not an integer \n"; }
?>
Type of 23: int eger
Type of 23.0: dou ble
Type of " 23": string
23 is an integer
COMP284 Scripting Languages Lecture 3 Slide L3 26
Type juggling and Type casting
Type juggling and Type casting
PHP automatically converts a value to the appropriate type as required
by the operation applied to the value (type juggling)
2 . " worlds" ; "2 worlds"
"2" * 3 ; 6
"1.23e2" + 0 ; 123
"hello" * 3 ; 0 (in PHP 7 also a warning)
"10hello5" + 5 ; 15 (in PHP 7 also a warning)
We can apply an identity function of the target type to force a type
conversion
"12" * 1 ; 12 !!1 ; TRUE !!"1" ; TRUE
"12" * 1.0 ; 12.0 !!0 ; FALSE !!"0" ; FALSE
"12.1" * 1 ; 12.1 !!1.0 ; TRUE !!"" ; FALSE
12 . "" ; "12" !!0.0 ; FALSE FALSE . "" ; ""
12.1 . "" ; "12.1" FALSE * 1 ; 0
Conversion of arrays to strings or numbers does not work
COMP284 Scripting Languages Lecture 3 Slide L3 27
Type juggling and Type casting
Type juggling and Type casting
PHP also supports explicit type casting via (type)
(int) "12" ; 12
(int) "10hello5" ; 10
(int) "1.23e2" ; 1 in PHP 5
(int) "1.23e2" ; 123 in PHP 7
(int) ("1.23e2" * 1) ; 123 in both PHP 5 and 7
(int) (float) "1.23e2" ; 123 in both PHP 5 and 7
(int) "1.23e2h5" ; 1 in PHP 5
(int) "1.23e2h5" ; 123 in PHP 7
(int) 10.5 ; 10
(float) "1.23e2" ; 123.0
(float) "1.23e2h5" ; 123.0
(bool) "0" ; FALSE (was true in JavaScript)
(bool) "foo" ; TRUE
(array) "foo" ; array(0 => "foo")
COMP284 Scripting Languages Lecture 3 Slide L3 28
Further Reading
Revision and Further Reading
Read
Chapter 3: Introduction to PHP
Chapter 4: Expressions and Control Flow in PHP: Expressions
of R. Nixon: Learning PHP, MySQL & JavaScript:
with jQuery, CSS & HTML5. O’Reilly, 2018.
Read
Language Reference: Types: Booleans
http://uk.php.net/manual/en/language.types.boolean.php
Language Reference: Types: Integers
http://uk.php.net/manual/en/language.types.integer.php
Language Reference: Types: Floating Point Numbers
http://uk.php.net/manual/en/language.types.float.php
Language Reference: Types: Strings
http://uk.php.net/manual/en/language.types.string.php
of P. Cowburn (ed.): PHP Manual. The PHP Group, 25 Oct 2019.
http://uk.php.net/manual/en [accessed 26 Oct 2019]
COMP284 Scripting Languages Lecture 3 Slide L3 29
COMP284 Scripting Languages
Lecture 4: PHP (Part 2)
Handouts
Ullrich Hustadt
Department of Computer Science
School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
12 Comparisons
13 Arrays
Basics
Foreach-loops
Array Operators
14 Printing
15 Special types
NULL
Resources
COMP284 Scripting Languages Lecture 4 Slide L4 1
Comparisons
Comparison Operators
Type juggling also plays a role in the way PHP comparison operators work:
expr1 == expr2 Equal TRUE iff expr1 is equal to expr2
after type juggling
expr1 != expr2 Not equal TRUE iff expr1 is not equal to expr2
after type juggling
expr1 <> expr2 Not equal TRUE iff expr1 is not equal to expr2
after type juggling
expr1 === expr2 Identical TRUE iff expr1 is equal to expr2,
and they are of the same type
expr1 !== expr2 Not identical TRUE iff expr1 is not equal to expr2,
or they are not of the same type
Note: For ==, !=, and <>, numerical strings are converted to numbers
and compared numerically
"123" == 123 ; TRUE "123" === 123 ; FALSE
"123" != 123 ; FALSE "123" !== 123 ; TRUE
"1.23e2" == 123 ; TRUE 1.23e2 === 123 ; FALSE
"1.23e2" == "12.3e1" ; TRUE "1.23e2" === "12.3e1" ; FALSE
"10hello5" == 10 ; TRUE "10hello5" === 10" ; FALSE
5 == TRUE ; TRUE 5 === TRUE ; FALSE
COMP284 Scripting Languages Lecture 4 Slide L4 2
Comparisons
Comparison Operators
Type juggling also plays a role in the way PHP comparison operators work:
expr1 < expr2 Less than TRUE iff expr1 is strictly less than expr2
after type juggling
expr1 > expr2 Greater than TRUE iff expr1 is strictly greater than expr2
after type juggling
expr1 <= expr2 Less than
or equal to
TRUE iff expr1 is less than or equal to expr2
after type juggling
expr1 >= expr2 Greater than
or equal to
TRUE iff expr1 is greater than or equal to expr2
after type juggling
Note: For >, >=, <, and <= numerical strings are converted to numbers
and compared numerically
'35.5' > 35 ; TRUE '35.5' >= 35 ; TRUE
'ABD' > 'ABC' ; TRUE 'ABD' >= 'ABC' ; TRUE
'1.23e2' > '12.3e1' ; FALSE '1.23e2' >= '12.3e1' ; TRUE
"F1" < "G0" ; TRUE "F1" <= "G0" ; TRUE
TRUE > FALSE ; TRUE TRUE >= FALSE ; TRUE
5 > TRUE ; FALSE 5 >= TRUE ; TRUE
COMP284 Scripting Languages Lecture 4 Slide L4 3
Comparisons
Comparison operators
To compare strings ‘as strings’ the strcmp function can be used
PHP 7 introduced the so-called ‘spaceship operator’ for three-way
comparisons (that converts numeric strings to numbers)
strcmp(expr1,expr2) String
comparison
Returns < 0 if expr1 is less than expr2,
> 0 if expr1 is greater than expr2,
0 if expr1 is equal to expr2
expr1 <=> expr2
(PHP 7 only)
Three-way
comparison
Returns -1 if expr1 < expr2,
+1 if expr1 > expr2,
0 if expr1 == expr2
strcmp('ABD','ABC') ; 1 strcmp("F1","G0") ; -65536
strcmp('aaa',"aaa") ; 0 strcmp('aaa',"AAA") ; 2105376
strcmp('1.23e2','12.3e1') ; -1
'ABD' <=> 'ABC' ; 1 "F1" <=> "G0" ; -1
'aaa' <=> "aaa" ; 0
'aaa' <=> "AAA" ; 1
'1.23e2' <=> '12.3e1' ; 0
'35.5' <=> 35 ; 1 '10hello5' <=> 10 ; 0
TRUE <=> FALSE ; 1 0.0 <=> FALSE ; 0
5 <=> TRUE ; 0 'FALSE' <=> TRUE ; 0
COMP284 Scripting Languages Lecture 4 Slide L4 4
Comparisons
Integers and Floating-point numbers: NAN and INF
NAN and INF can be compared with each other and other numbers using
equality and comparison operators:
NAN == NAN ; FALSE NAN === NAN ; FALSE NAN == 1 ; FALSE
INF == INF ; TRUE 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
INF === INF returns TRUE
In PHP 5.4 and later versions, INF == INF returns TRUE
INF === INF returns TRUE
COMP284 Scripting Languages Lecture 4 Slide L4 5
Comparisons
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'
COMP284 Scripting Languages Lecture 4 Slide L4 6
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 ( 20084 6369 = > array (" name " = > " Jan Olsen " ,
" CO MP51 8 " => 69 ,
" CO MP51 9 " => 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
COMP284 Scripting Languages Lecture 4 Slide L4 7
Arrays Basics
Arrays
It is possible to omit the keys when using the array construct:
$arr3 = array (" Peter " , " Paul" , " Mary " );
The values given in array will then be associated with the
natural numbers 0, 1, . . .
All the keys of an array can be retrieved using
array_keys($array1)
; returns a natural number-indexed array containing
the keys of $array1
All the values of an array can be retrieved using
array_values($array1)
; returns a natural number-indexed array containing
the values stored in $array1
COMP284 Scripting Languages Lecture 4 Slide L4 8
Arrays Basics
Arrays
An individual array element can be accessed via its key
Accessing an undefined key produces a PHP notice
and returns NULL
$arr1 = array (1 => " Peter " , 3 => 2009 , "a" => 101);
print " 'a ' = > ". $arr1 ["a" ]."\n";
'a' = > 101
print " 'b ' = > ". $arr1 ["b" ]."\n";
PHP Notice : Undef ined index : b in <file > on line < lineno >
'b' = > // $ arr1 [" b"] returns NULL
$arr1 [ 'b '] = 102;
print " 'b ' = > ". $arr1 ["b" ]."\n";
'b' = > 102
The function array_key_exists(key,array1) can be used to check
whether there is a value for key in array1
array _ key_ex i sts ("a", $ arr1 ) # ret urns TRUE
array _ key_ex i sts ("c", $ arr1 ) # ret urns FALSE
COMP284 Scripting Languages Lecture 4 Slide L4 9
Arrays Basics
Arrays
PHP allows the construct
$ array [] = value ;
PHP will determine the maximum value M among the integer indices in
$array and use the key K = M + 1; if there are no integer indices in
$array, then K = 0 will be used
; auto-increment for array keys
$arr4 [] = 51; // 0 => 51
$arr4 [] = 42; // 1 => 42
$arr4 [] = 33; // 2 => 33
A key-value pair can be removed from an array using the
unset function:
$arr1 = array (1 => " Peter " , 3 => 2009 , "a" => 101);
unset ( $arr1 [3]); // Removes the pair 3 => 2009
unset ( $arr1 ); // Removes the whole array
COMP284 Scripting Languages Lecture 4 Slide L4 10
Arrays Foreach-loops
Arrays: foreach-loop
PHP provides a foreach-loop construct to ‘loop’ through the elements
of an array
for each ( array as $ value)
statemen t
for each ( array as $ key = > $ value )
statemen t
array is an array expression
$key and $value are two variables, storing a different key-value pair in
array at each iteration of the foreach-loop
We call $value the foreach-variable
foreach iterates through an array in the order in which elements were
defined
COMP284 Scripting Languages Lecture 4 Slide L4 11
Arrays Foreach-loops
Arrays: foreach-loop
foreach iterates through an array in the order in which elements were
defined
Example 1:
for each ( array (" Peter " , " Paul " , " Mary ") as $key = > $value )
print " The array maps $key to $value \n";
The array maps 0 to Peter
The array maps 1 to Paul
The array maps 2 to Mary
Example 2:
$arr5 [2] = " Mary";
$arr5 [0] = " Peter ";
$arr5 [1] = " Paul";
// 0 => ' Peter ', 1 = > ' Paul ' , 2 => ' Mary '
for each ( $arr5 as $ key => $va lue )
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
COMP284 Scripting Languages Lecture 4 Slide L4 12
Arrays Foreach-loops
Arrays: foreach-loop
Does changing the value of the foreach-variable change the element of the
list that it currently stores?
Example 3:
$arr6 = array ("name " = > " Peter " , " year " => 2009);
for each ( $arr6 as $ key => $va lue ) {
print " The array maps $key to $value \n";
$value .= " - mo dified "; // C hang ing $value
}
print " \ n";
The array maps name to Peter
The array maps year to 2009
for each ( $arr6 as $ key => $va lue )
print " The array now maps $key to $value \n";
The array now maps name to Peter
The array now maps year to 2009
COMP284 Scripting Languages Lecture 4 Slide L4 13
Arrays Foreach-loops
Arrays: foreach-loop
In order to modify array elements within a foreach-loop we need use a
reference
for each ( array as & $ value)
statemen t
unset ( $ value );
for each ( array as $ key = > &$ value )
statemen t
unset ( $ value );
In the code schemata above, $value is a variable whose value is stored at
the same location as an array element
PHP does not allow the key to be a reference
The unset statement is important to return $value to being a ‘normal’
variable
COMP284 Scripting Languages Lecture 4 Slide L4 14
Arrays Foreach-loops
Arrays: foreach-loop
In order to modify array elements within a foreach-loop we need use a
reference
In each iteration, $value contains a reference to an array element
; changing $value changes the array element
$arr6 = array ("name " = > " Peter " , " year " => 2009);
for each ( $arr6 as $ key => & $value ) { // Note : referenc e !
print " The array maps $key to $value \n";
$value .= " - mo dified ";
}
unset ( $value ); // Remove the r efere nce from $ val ue
print " \ n";
The array maps name to Peter
The array maps year to 2009
// See what the cont ent of $ arr6 is now
for each ( $arr6 as $ key => $va lue )
print " The array now maps $key to $value \n";
The array now maps name to Peter - modified
The array now maps year to 2009 - modified
COMP284 Scripting Languages Lecture 4 Slide L4 15
Arrays Foreach-loops
Array Assignments
In Java (and Python) arrays were objects and as a consequence
array assignments were done by reference
In PHP, this is not the case
$m em1 = m emo ry_ge t_u sa ge ();
$array1 = range (1 , 1000);
$m em2 = m emo ry_ge t_u sa ge ();
echo " (1) ", sp ri nt f ( " %6 d ",$mem2 - $ mem1 ) , " more b ytes \ n ";
$array2 = $a rray1 ;
$m em3 = m emo ry_ge t_u sa ge ();
echo " (2) ", sp ri nt f ( " %6 d ",$mem3 - $ mem2 ) , " more b ytes \ n ";
$array2 [1] += 10000;
echo " \ $ ar ra y1 [1] = " , $ array1 [1] ," | ";
echo " \ $ ar ra y2 [1] = " , $ array2 [1] ,"\ n";
$m em4 = m emo ry_ge t_u sa ge ();
echo " (3) ", sp ri nt f ( " %6 d ",$mem4 - $ mem3 ) , " more b ytes \ n ";
(1) 36920 mor e bytes
(2) 0 mor e bytes
$array1 [1] = 2 | $ arra y2 [1] = 1000 2
(3) 36920 mor e bytes
The PHP implementation uses copy-on-write for array assignments
COMP284 Scripting Languages Lecture 4 Slide L4 16
Arrays Foreach-loops
Array Assignments
The PHP implementation uses copy-on-write for array assignments
If we want two array variables to point to the same array literal,
then we need to explicitly use a reference
$ar ray1 = range (1, 1000);
$mem2 = m e mory_ge t_usage ();
$ar ray2 = & $a rray1 ;
$mem3 = m e mory_ge t_usage ();
echo " (2) " ,spr intf (" %6d" , $ mem3 - $mem2 )," more bytes \n";
$ar ray2 [1] += 10000;
echo " \ $array1 [1] = " ,$ar ray1 [1] ," | ";
echo " \ $array2 [1] = " ,$ar ray2 [1] ,"\n";
$mem4 = m e mory_ge t_usage ();
echo " (3) " ,spr intf (" %6d" , $ mem4 - $mem3 )," more bytes \n";
(2) 24 more bytes
$ar ray1 [1] = 10002 | $ array2 [1] = 10002
(3) 0 more bytes
COMP284 Scripting Languages Lecture 4 Slide L4 17
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
COMP284 Scripting Languages Lecture 4 Slide L4 18
Printing
Printing
In PHP, the default command for generating output is echo
void echo(arg1)
void echo arg1, arg2, ...
Outputs all arguments
No parentheses are allowed if there is more than one argument
More efficient than print (and therefore preferred)
Additionally, PHP also provides the functions print, and printf:
int print(arg)
Outputs its argument
Only one argument is allowed!
Returns value 1
Parentheses can be omitted
COMP284 Scripting Languages Lecture 4 Slide L4 19
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 Perl, a PHP array cannot take the place
of a list of arguments
printf ( " %2d apples %2d or anges \n" , array (5 ,7));
produces an error message
COMP284 Scripting Languages Lecture 4 Slide L4 20
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
vpr intf (" %2d ap ples %2d oranges \n", array (5 ,7));
5 app les 7 oranges
COMP284 Scripting Languages Lecture 4 Slide L4 21
Special types NULL
NULL
NULL is both a special type and a value
NULL is the only value of type NULL
and the name of this constant is case-insensitive
A variable has both type NULL and value NULL in the following three
situations:
1 The variable has not yet been assigned a value (not equal to NULL)
2 The variable has been assigned the value NULL
3 The variable has been unset using the unset operation
There are a variety of functions that can be used to test whether a
variable is NULL including:
bool isset($variable)
TRUE iff $variable exists and does not have value NULL
bool is_null(expr)
TRUE iff expr is identical to NULL
COMP284 Scripting Languages Lecture 4 Slide L4 22
Special types NULL
NULL
Warning: Using NULL with == may lead to counter-intuitive results
$d = array();
echo var_dump($d), "\n";
array(0) {
}
echo 'is_null($d): ', (is_null($d)) ? "TRUE\n": "FALSE\n";
is_null($d): FALSE
echo '$d === null: ', ($d === null) ? "TRUE\n": "FALSE\n";
$d === null: FALSE
echo '$d == null: ', ($d == null) ? "TRUE\n": "FALSE\n";
$d == null: TRUE
Type juggling means that an empty array is (loosely) equal to NULL
but not identical (strictly equal) to NULL
COMP284 Scripting Languages Lecture 4 Slide L4 23
Special types Resources
Resources
A resource is a reference to an external resource and corresponds to
a Perl filehandle
resource fopen(filename, mode)
Returns a file pointer resource for filename access using mode on
success, or FALSE on error
Mode Operation Create Truncate
'r' read file
'r+' read/write file
'w' write file yes yes
'w+' read/write file yes yes
'a' append file yes
'a+' read/append file yes
'x' write file yes
'x+' read/write file yes
See http://www.php.net/manual/en/resource.php for further details
COMP284 Scripting Languages Lecture 4 Slide L4 24
Special types Resources
Resources
bool fclose(resource)
Closes the resource
Returns TRUE on success
string fgets(resource [, length])
Returns a line read from resource and
returns FALSE if there is no more data to be read
With optional argument length, reading ends when length 1 bytes
have been read, or a newline or on EOF (whichever comes first)
string fread(resource,length)
Returns length characters read from resource
$ha ndle = fopen ( ' somefile . txt ' , ' r ' );
while ( $line = fgets ( $ handle )) {
// processing the line of the file
}
fclose ( $ha ndle );
COMP284 Scripting Languages Lecture 4 Slide L4 25
Special types Resources
Resources
int fwrite(resource, string [, length])
Writes a string to a resource
If length is given, writing stops after length bytes have been written or
the end of string is reached, whichever comes first
int fprintf(resource, format, arg1, arg2, ...)
Writes a list of arguments to a resource in the given format
Identical to fprintf with output to resource
int vfprintf (resource, format, array)
Writes the elements of an array to a resource in the given format
Identical to vprintf with output to resource
$ha ndle = fopen ( ' somefile . txt ' , ' w ' );
fwrite ( $handle , " Hello World !". PHP_ EOL ); // ` logical newline '
fclose ( $ha ndle );
In PHP \n always represents the character with ASCII code 10 not the
platform dependent newline ; use PHP_EOL instead
COMP284 Scripting Languages Lecture 4 Slide L4 26
Special types Resources
Revision
Read
Chapter 4: Expressions and Control Flow in PHP: Operators
Chapter 6: PHP Arrays
Chapter 7: Practical PHP: File Handling
of R. Nixon: Learning PHP, MySQL & JavaScript:
with jQuery, CSS & HTML5. O’Reilly, 2018.
Read
Language Reference: Types: Arrays
http://uk.php.net/manual/en/language.types.array.php
Language Reference: Control Structures: foreach
http://uk.php.net/manual/en/control-structures.foreach.php
of P. Cowburn (ed.): PHP Manual. The PHP Group, 24 Dec 2019.
http://uk.php.net/manual/en [accessed 25 Dec 2019]
COMP284 Scripting Languages Lecture 4 Slide L4 27
COMP284 Scripting Languages
Lecture 5: PHP (Part 3)
Handouts
Ullrich Hustadt
Department of Computer Science
School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
16 Control Structures
Statement Groups
Conditional Statements
Switch Statements
While- and Do While-loops
For-loops
Try, throw, catch, finally statements
17 Functions
Defining a function
Calling a function
Scope of Variables
Functions and HTML
Variable-length argument lists
18 PHP libraries
Include/Require
COMP284 Scripting Languages Lecture 5 Slide L5 1
Control Structures
Control Structures
PHP control structures
statement groups
conditional statements
switch statements
while- and do while-loops
for-loops
try, throw, catch, finally statements
are mostly identical to those of Java
COMP284 Scripting Languages Lecture 5 Slide L5 2
Control Structures Statement Groups
Control Structures: Statement Groups
A statement group is a sequence of zero or more statements delimited
by a pair of curly brackets
{
stat ement s
}
It allows to use multiple statements where PHP expects only one
statement
The last statement in a statement group does not need to be
terminated by a semi-colon
{
$x = 1;
$y = $x ++
}
COMP284 Scripting Languages Lecture 5 Slide L5 3
Control Structures Conditional Statements
Conditional Statements
The general format of conditional statements is very similar but not
identical to that in Java and JavaScript:
if ( con dition )
statemen t
elseif ( con dition )
statemen t
else
statemen t
the elseif-clause is optional and there can be more than one
Note: elseif instead of elif or else if
the else-clause is optional but there can be at most one
COMP284 Scripting Languages Lecture 5 Slide L5 4
Control Structures Conditional Statements
Conditional Statements/Expressions
PHP allows to replace curly brackets with a colon : combined with an
endif at the end of the statement:
if ( con dition ):
stat ement s
elseif ( con dition ):
stat ement s
else :
stat ement s
endif
This also works for the switch statement in PHP
However, this syntax becomes difficult to parse
when nested conditional statements are used and is best avoided
PHP also supports conditional expressions
conditio n ? if_tr ue_exp r : if_fa l se_exp r
COMP284 Scripting Languages Lecture 5 Slide L5 5
Control Structures Switch Statements
Switch Statement
A switch statement in PHP takes the following form
switch ( expr ) {
case expr1 :
stat ement s
break ;
case expr2 :
stat ement s
break ;
def ault :
stat ement s
break ;
}
there can be arbitrarily many case-clauses
the default-clause is optional but there can be
at most one, it does not need to be last
expr is evaluated only once and then compared
to expr1, expr2, etc using (loose) equality ==
once two expressions are found to be equal the
corresponing 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
COMP284 Scripting Languages Lecture 5 Slide L5 6
Control Structures Switch Statements
Switch Statement: Example
Not every case-clause needs to have associated statements
switch ( $m onth ) {
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 ;
def ault :
$days = 0;
break ;
}
COMP284 Scripting Languages Lecture 5 Slide L5 7
Control Structures While- and Do While-loops
While- and Do While-loops
PHP offers while-loops and do while-loops
while ( cond ition )
statemen t
do
statemen t
while ( cond ition );
Example:
// Comp ute the f actorial of $ number
$fac toria l = 1;
do
$fac toria l *= $ number - -;
while ( $nu mber > 0);
COMP284 Scripting Languages Lecture 5 Slide L5 8
Control Structures For-loops
For-loops
for-loops in PHP take the form
for ( i nitial isatio n ; test ; incr ement )
statemen t
In PHP initialisation and increment can consist of more than one
statement, separated by commas instead of semicolons
Example:
for ( $i = 3 , $j = 3; $j >= 0; $i ++ , $j - -)
echo " $i - $j - " , $i*$j , "\n";
3 - 3 - 9
4 - 2 - 8
5 - 1 - 5
6 - 0 - 0
COMP284 Scripting Languages Lecture 5 Slide L5 9
Control Structures For-loops
Break and Continue
The break command can also be used in while-, do while-, and for-loops
and discontinues the execution of the loop
while ( $value = array _shift ( $data ) {
$written = fwrite ( $resource , $value );
if (! $writte n ) break ;
}
The continue command stops the execution of the current iteration of a
loop and moves the execution to the next iteration
for ( $x = -2; $x <= 2; $x ++) {
if ( $x == 0) continue ;
printf ( " 10 / %2d = %3d\n",$x ,(10/ $x ));
}
10 / -2 = -5
10 / -1 = -10
10 / 1 = 10
10 / 2 = 5
COMP284 Scripting Languages Lecture 5 Slide L5 10
Control Structures Try, throw, catch, finally statements
Exceptions and error handling
PHP distinguishes between Exceptions and Errors
In PHP 7 both are subclasses of Throwable but not in PHP 5
Exceptions can be thrown via a throw statement
throw new Excep tion ( mes sage )
where message is a string
User-level errors/warnings/notices can be generated using
trigg er_err or ( message [ , type ])
where message is a string and type is an integer indicating what type
of error is generated
A try ... catch ... statement allows for exception (throwable)
handling
Since PHP 5.5, a finally clause can be added
try { stat ements }
catch ( Exce ption $e) { stat ement s }
fin ally { state ments }
COMP284 Scripting Languages Lecture 5 Slide L5 11
Control Structures Try, throw, catch, finally statements
Exceptions and error handling
$x = "A";
try {
if (( is _int ( $x) || is_float ( $x )) && is_finite ( $x ))
$y = round ( $x ,2);
else
throw new Excep tion ( " '$x ' is not a number " );
} catch ( Exce ption $e) {
echo " Caught : $e\n";
$y = 0;
} finally {
echo " y = $ y\n";
}
Caught : E xception : 'A' is not a num ber in try . php :7
Stack trace :
#0 { main }
y = 0
COMP284 Scripting Languages Lecture 5 Slide L5 12
Control Structures Try, throw, catch, finally statements
Exceptions and error handling
PHP distinguishes between exceptions and errors
In PHP 5, errors must be dealt with by an error handling function
(‘Division by zero’ produces an error not an exception)
To take advantage of try ... catch ... statements to handle errors,
one can turn errors into exceptions
function exceptio n _error_h a n dler ( $errno , $ errstr ,
$errfile , $ errline ) {
throw new E rrorEx ceptio n ( $errstr , $errno ,
0, $errfile , $errline ); }
set_e r ror_han dler (" exc e p tion_err o r_handle r " );
$x = 0;
try {
$y = 1/ $x;
} catch ( Exce ption $e) {
echo " Caught : $e\n";
}
Caught : E r rorExc eption : Division by zero in try . php :10
COMP284 Scripting Languages Lecture 5 Slide L5 13
Functions Defining a function
Functions
Functions are defined as follows in PHP:
function iden tifier ($ param1 , & $ param2 , ...) {
stat ement s
}
Functions can be placed anywhere in a PHP script but preferably they
should all be placed at start of the script (or at the end of the script)
Function names are case-insensitive
The function name must be followed by parentheses
A function has zero, one, or more parameters that are variables
Parameters can be given a default value using
$param = const_expr
When using default values, any defaults must be on the right side of
any parameters without defaults
COMP284 Scripting Languages Lecture 5 Slide L5 14
Functions Defining a function
Functions
Functions are defined as follows in PHP:
function iden tifier ($ param1 , & $ param2 , ...) {
stat ement s
}
The return statement
return value
can be used to terminate the execution of a function and to make
value the return value of the function
The return value does not have to be scalar value
A function can contain more than one return statement
Different return statements can return values of different types
COMP284 Scripting Languages Lecture 5 Slide L5 15
Functions Calling a function
Calling a function
A function is called by using the function name followed by a list of
arguments in parentheses
function iden tifier ($ param1 , & $ param2 , ...) {
...
}
... identifier ( arg1 , arg2 ,...) ...
The list of arguments can be shorter as well as longer as
the list of parameters
If it is shorter, then default values must have been specified for the
parameters without corresponding arguments
If no default values are available for ‘missing’ arguments,
then we get a PHP fatal error
Example:
function sum ( $num1 , $num2 ) { ret urn $ num1 + $ num2 ; }
echo " sum : " ,sum (5 ,4) ,"\n";
$sum = sum (3 ,2);
COMP284 Scripting Languages Lecture 5 Slide L5 16
Functions Scope of Variables
Variables and Scope
PHP distinguishes the following categories of variables with respect to
scope:
Local variables are only valid in the part of the code
in which they are introduced
(PHP) Global variables are valid outside of functions
Superglobal variables are built-in variables that are always available in
all scopes
Static variables are local variables within a function that retain their
value between separate calls of the function
By default,
variables inside a function definition are local but not static
variables outside any function definition are global
COMP284 Scripting Languages Lecture 5 Slide L5 17
Functions Scope of Variables
Functions and Scope
$x = " Hello ";
function f1 () {
echo " 1: $x \ n " ;
}
function f2 () {
echo " 2: $x \ n " ;
$x = " Bye ";
echo " 3: " ,$x , " \ n " ;
}
f1 ();
f2 ();
echo " 4: $x \ n " ;
A variable defined outside any
function is (PHP) global
A (PHP) global variable can be
accessed from any part of the
script that is not inside a function
A variable within a PHP function is
by default local and can only be
accessed within that function
There is no hoisting of variable
‘declarations’
1: PHP Notice : Und efined var iabl e : x
2: PHP Notice : Und efined var iabl e : x
3: Bye
4: Hello
COMP284 Scripting Languages Lecture 5 Slide L5 18
Functions Scope of Variables
Functions and Global Variables
$x = " Hello ";
function f1 () {
global $x;
echo " 1: $x \ n " ;
}
function f2 () {
$x = " Bye ";
echo " 2: $x \ n " ;
global $x;
echo " 3: $x \ n " ;
}
f1 ();
f2 ();
echo " 4: $x \ n " ;
1: Hello
2: Bye
3: Hello
4: Hello
A ‘local’ variable can be declared
to be (PHP) global using the
keyword global
All (PHP) global variables with
the same name refer to the same
storage location/data structure
An unset operation removes a
specific variable, but leaves other
(global) variables with the same
name unchanged
COMP284 Scripting Languages Lecture 5 Slide L5 19
Functions Scope of Variables
PHP functions and Static variables
A variable is declared to be static using the keyword static and should
be combined with the assignment of an initial value (initialisation)
function cou nter () {
static $count = 0;
return $count ++;
}
; static variables are initialised only once
1 fun ctio n cou nter () { static $ count = 0; ret urn $ cou nt ++; }
2 $count = 5;
3 echo " 1: global \ $count = $ count \ n " ;
4 echo " 2: static \ $count = " , counter () ,"\n";
5 echo " 3: static \ $count = " , counter () ,"\n";
6 echo " 4: global \ $count = $ count \ n " ;
1: global $ count = 5
2: static $ count = 0
3: static $ count = 1
4: global $ count = 5
COMP284 Scripting Languages Lecture 5 Slide L5 20
Functions Scope of Variables
PHP functions: Example
function bubbl e_sor t ( $array ) {
// $array , $size , $i , $j are all local
if (! is_arra y ( $arra y ))
trig g er_err or (" Ar gume nt 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 ( $a rray [ $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 ;
}
COMP284 Scripting Languages Lecture 5 Slide L5 21
Functions Scope of Variables
PHP functions: Example
function bubbl e_sor t ( $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 ( " , " , $a rray ), "\n";
$so rted = bubbl e_sort ( $array );
echo " After sorting " , join ( " , " , $a rray ), "\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
COMP284 Scripting Languages Lecture 5 Slide L5 22
Functions Functions and HTML
Functions and HTML
It is possible to include HTML markup in the body of a
function definition
The HTML markup can in turn contain PHP scripts
A call of the function will execute the PHP scripts, insert the output
into the HTML markup, then output the resulting HTML markup
<?php
fu nction p rin t_f orm($fn , $ln ) {
?>
< form ac tion=" pr ocess _fo rm . php " metho d =POST " >
<label > Firs t Name : < input type = " text " na me =" f" value = " <?php echo $fn ? >" > </label >
<br > <label >Last Name <b >* </ b >:< i nput ty pe =" text " name = "l " valu e =" <? php echo $ln ?>" >
</label >< br >< input type= " sub mit " name =" submi t " valu e =" Su bmit"> <input type=reset >
</form >
<?php
}
pr int _fo rm ( " Ull rich","Hust adt " );
?>
< form ac tion=" pr ocess _fo rm . php " metho d =POST " >
<label > Firs t Name : < input type = " text " na me =" f" value = " Ull rich" ></ label >
<br > <label >Last Name <b >* </ b >:< i nput ty pe =" text " name = "l " valu e =" Hu sta dt " >
</label >< br >< input type= " sub mit " name =" submi t " valu e =" Su bmit"> <input type=reset >
</form >
COMP284 Scripting Languages Lecture 5 Slide L5 23
Functions Variable-length argument lists
Functions with variable number of arguments
The number of arguments in a function call is allowed to exceed the
number of its parameters
; 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 num ber of argum ents
if ( func _num_a rgs () < 1) return null ;
$sum = 0;
for each ( func _get_a rgs () as $ value ) { $ sum += $ value ; }
return $sum ;
}
COMP284 Scripting Languages Lecture 5 Slide L5 24
PHP libraries Include/Require
Including and requiring files
It is often convenient to build up libraries of function definitions,
stored in one or more files, that are then reused in PHP scripts
PHP provides the commands include, include_once, require, and
require_once to incorporate the content of a file into a PHP script
inc lude ' myl ibrary . php ' ;
PHP code in a library file must be enclosed within a PHP start tag
<?php and an end PHP tag ?>
The incorporated content inherits the scope of the line in which an
include command occurs
If no absolute or relative path is specified, PHP will search for the file
first, in the directories in the include path include_path
second, in the script’s directory
third, in the current working directory
COMP284 Scripting Languages Lecture 5 Slide L5 25
PHP libraries Include/Require
Including and requiring files
Several include or require commands for the same library file
results in the file being incorporated several times
; defining a function more than once results in an error
Several include_once or require_once commands for the same
library file results in the file being incorporated only once
If a library file requested by include and include_once cannot be
found, PHP generates a warning but continues the execution of the
requesting script
If a library file requested by require and require_once cannot be
found, PHP generates a error and stops execution of the requesting
script
COMP284 Scripting Languages Lecture 5 Slide L5 26
PHP libraries Include/Require
PHP Libraries: Example
mylibrary.php
<? php
function bubbl e_sor t ( $array ) {
... swap ( $array , $j , $j +1); ...
return $array ;
}
function swap (& $array , $i , $j ) {
...
}
?>
example.php
<? php
requ ire_on ce ' my library .php ';
$array = array (2 ,4 ,3 ,9 ,6 ,8 ,5 ,1);
$so rted = bubbl e_sort ( $array );
?>
COMP284 Scripting Languages Lecture 5 Slide L5 27
PHP libraries Include/Require
Revision
Read
Chapter 4: Expressions and Control Flow in PHP
Chapter 5: PHP Functions and Objects
of
R. Nixon:
Learning PHP, MySQL, and JavaScript.
O’Reilly, 2018.
http://uk.php.net/manual/en/language.control-structures.php
http://uk.php.net/manual/en/language.functions.php
http://uk.php.net/manual/en/function.include.php
http://uk.php.net/manual/en/function.include-once.php
http://uk.php.net/manual/en/function.require.php
http://uk.php.net/manual/en/function.require-once.php
COMP284 Scripting Languages Lecture 5 Slide L5 28
COMP284 Scripting Languages
Lecture 6: PHP (Part 4)
Handouts
Ullrich Hustadt
Department of Computer Science
School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
19 Regular Expressions
Overview
PCRE
Characters
Escape sequence and meta-characters
Character classes
Anchors
Quantifiers
Capturing subpatterns
Alternations
Modifiers
20 PCRE functions
COMP284 Scripting Languages Lecture 6 Slide L6 1
Regular Expressions Overview
PHP and regular expressions
Input validation is an important step in preventing incorrect or
dangerous data entering an application
Regular expression matching is a useful technique for input validation
Regular expressions are also useful for
data extraction
data clearning and data transformation
Over time, PHP has supported different variants of regular expressions
POSIX-extended regular expressions
; deprecated in PHP 5.3.0, removed in PHP 7.0.0
Shell-style wildcard patterns
; still supported, but not particularly powerful
Perl-compatible regular expressions (PCRE)
; closely resemble Perl regular expressions
COMP284 Scripting Languages Lecture 6 Slide L6 2
Regular Expressions PCRE
Perl-compatible regular expressions
In PHP, a regular expression is a string the content of which resembles a
Perl regular expression
' /(\ d +\.\ d+) seconds / ' "/[ bc ][b -e ][^ bcd ]/"
The character / acts as a delimiter indicating the start and end of the
regular expression
; carried over from Perl
; ‘closing’ delimiter can be followed by modifiers
In PHP any non-alphanumeric, non-backslash, non-whitespace character
can be used as delimiter
If the delimiter also occurs inside the pattern it must be escaped using
a backslash \
Backslash behaviour and differences between single- and double-quoted
strings carry over
COMP284 Scripting Languages Lecture 6 Slide L6 3
Regular Expressions Characters
Regular expressions: Characters
The simplest regular expression just consists of a sequence of
alphanumberic characters and
non-alphanumeric characters escaped by a backslash
that matches exactly this sequence of characters occurring as a substring
in the target string
"/cbc/"
matches "ababcbcdcde"
'/1\+2/'
matches "21+23=44"
Strictly speaking, not all non-alphanumeric characters need to be
escaped by a backslash, only those that are ‘reserved’
COMP284 Scripting Languages Lecture 6 Slide L6 4
Regular Expressions Escape sequence and meta-characters
Regular expressions: Escape sequences and
meta-characters
There are various meta-characters and escape sequences that match
characters other than themselves:
. Matches any character except \n
\w Matches a ‘word’ character (alphanumeric plus _’)
\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
"/\w.\d/"
matches "-N$1.00"
'/\W.\D/'
matches "-N$1.00"
COMP284 Scripting Languages Lecture 6 Slide L6 5
Regular Expressions Character classes
Regular expressions: Character class
A character class, a list of characters and escape sequences 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]
"/[bc][b-e][^bcd]/"
matches "abacdecdc"
'/[][1-9]\.[0-9]/'
matches "$2.1"
COMP284 Scripting Languages Lecture 6 Slide L6 6
Regular Expressions Anchors
Regular expressions: Anchors / assertions
Anchors (assertions) 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 (in multi-line matching)
\Z Match only at string end modulo a preceding \n
\z Match only at string end
$ Match only at string end modulo a preceding \n
Match only at a line end (in multi-line matching)
\b Match word boundary (between \w and \W)
\B Match except at word boundary
Target string " one two \ n three four \ nfive \ n "
Do match Do not match
'/\Aone/' (at string start) '/^three/' (not a string start)
'/^three/m' (at line start) '/four\Z/' (not at string end mod \n)
'/four$/m' (at line end) '/five\z/' (not a string end)
'/five\Z/' (at string end mod \n)
'/\bone\b/' (a word in string) '/\bour\b/' (not a word in string)
COMP284 Scripting Languages Lecture 6 Slide L6 7
Regular Expressions Quantifiers
Quantifiers
The constructs for regular expressions that we have seen so far are not
sufficient to match, for example, natural numbers of arbitrary size
Also, writing a regular expressions for, say, a nine digit number
would be tedious
This is made possible with the use of quantifiers
regexpr* (Greedily) Match regexpr 0 or more times
regexpr+ (Greedily) Match regexpr 1 or more times
regexpr? (Greedily) Match regexpr 1 or 0 times
regexpr{n} Match regexpr exactly n times
regexpr{n,} (Greedily) Match regexpr at least n times
regexpr{n,m} (Greedily) Match regexpr between n and m times
Quantifiers are greedy by default and match the longest leftmost sequence
of characters possible
COMP284 Scripting Languages Lecture 6 Slide L6 8
Regular Expressions Quantifiers
Quantifiers
regexpr* (Greedily) Match regexpr 0 or more times
regexpr+ (Greedily) Match regexpr 1 or more times
regexpr? (Greedily) Match regexpr 1 or 0 times
regexpr{n} Match regexpr exactly n times
regexpr{n,} (Greedily) Match regexpr at least n times
regexpr{n,m} (Greedily) Match regexpr between n and m times
"/\d+\.\d+/"
matches "Delay 10.486 sec"
'/\d+/'
matches "No 12 345 6789"
'/[A-Z]0{2}\d{6}/'
matches "ID E004813709"
'/\d+/'
matches "ID E004813709"
The examples on the right illustrate that a regular expressions \d+
matches as early as possible
matches as many digits as possible
COMP284 Scripting Languages Lecture 6 Slide L6 9
Regular Expressions Quantifiers
Quantifiers
There are situations where greedy matching is not appropriate,
for example, matching a single comment in a program
'=/\*.*\*/='
matches "x = /* one */ y*z; /* three */"
By adding ? to a quantifier, we can make it match lazily, that is,
it will match the shortest leftmost sequence of characters possible
'=/\*.*?\*/='
matches "x = /* one */ y*z; /* three */"
COMP284 Scripting Languages Lecture 6 Slide L6 10
Regular Expressions Quantifiers
(Lazy) Quantifiers
regexpr*? Lazily match regexpr 0 or more times
regexpr+? Lazily match regexpr 1 or more times
regexpr?? Lazily match regexpr 1 or 0 times
regexpr{n,}? Lazily match regexpr at least n times
regexpr{n,m}? Lazily match regexpr between n and m times
"/\d+?\.\d+?/"
matches "Delay 10.486 sec"
'/\d+?/'
matches "No 12 345 6789"
'/[A-Z]0{2}\d{6}/'
matches "ID E004813709"
'/\d+?/'
matches "ID E004813709"
COMP284 Scripting Languages Lecture 6 Slide L6 11
Regular Expressions Capturing subpatterns
Regular expressions: Capturing subpatterns and
backreferences
We often encounter situations where we want to identify the repetition
of the same or similar text, for example, in HTML markup:
<strong > ... </ strong >
<h1 > ... </h1 >
We might also not just be interested in the repeating text itself,
but the text between or outside the repetition
We can characterise each individual example above
using regular expressions:
'=< strong >.*? </ strong >= '
'=< h1 >.*? </h1 >= '
but we cannot characterise both without losing fidelity, for example:
' = <\w + >.*? </\ w + >= '
does not capture the ‘pairing’ of HTML tags
COMP284 Scripting Languages Lecture 6 Slide L6 12
Regular Expressions Capturing subpatterns
Regular expressions: Capturing subpatterns and
backreferences
The solution are capturing subpatterns and backreferences
(regexpr) creates a capturing subpattern
(opening parentheses are counted starting from 1
to give an index number)
(?<name>regexpr) creates a named capturing subpattern
(?:regexpr) creates a non-capturing subpattern
\N, \gN, \g{N} backreference to a capturing subpattern N
(where N is a natural number)
\g{name} backreference to a named capture group
"=<(\w+)>.*?</\1>=" "=<(?<c1>\w+)>.*?</\g{c1}>="
matches "<li><b>item</b></li>" matches "<li><b>item</b></li>"
"=<(\w+)>.*?</\1>="
does not match "<li>item</em>"
COMP284 Scripting Languages Lecture 6 Slide L6 13
Regular Expressions Alternations
Regular expressions: Alternations
The regular expression regexpr1|regexpr2 matches
if either regexpr1 or regexpr2 matches
This type of regular expression is called an alternation
Within a larger regular expression we need to enclose alternations
in a subpattern or capturing subpattern
(regexpr1|regexpr2) or (?:regexpr1|regexpr2)
to indicate where regexpr1 and regexpr2 start/end
'/(Mr|Ms|Mrs|Dr).*?([\w\-]+)/'
matches "Dr Michele Zito"
matches "Mr Dave Shield"
matches "Mrs Judith Birtall"
COMP284 Scripting Languages Lecture 6 Slide L6 14
Regular Expressions Alternations
Regular expressions: Alternations
The order of expressions in an alternation only matters
if one expression matches a sub-expression of another
'/cat|dog|bird/'
matches "cats and dogs"
'/dog|cat|bird/'
matches "cats and dogs"
s
0
s
1
s
2
s
3
s
d
s
c
s
b
s
o
s
a
s
i
s
g
s
t
s
r
s
2
d
d o
g
c a t
b i r t
'/dog|dogs/'
matches "cats and dogs"
s
0
s
1
s
2
s
1
d
s
2
d
s
1
o
s
2
o
s
1
g
s
2
g
s
2
s
d
d
o
g
o
g
s
'/dogs|dog/'
matches "cats and dogs"
s
0
s
1
s
2
s
1
d
s
2
d
s
1
o
s
2
o
s
1
g
s
2
g
s
1
s
d
d
o
g
o
g
s
COMP284 Scripting Languages Lecture 6 Slide L6 15
Regular Expressions Modifiers
Regular expressions: Modifiers
Modifiers change the interpretation of certain characters in a regular
expression or the way in which PHP finds a match for a regular expression
/ / Default
. matches any character except \n
^ matches only at string start
$ matches only at string end modulo preceding \n
/ /i perform a case-insensitive match
Target string "Hillary\nClinton"
/clinton/ does not match
/clinton/i does match
COMP284 Scripting Languages Lecture 6 Slide L6 16
Regular Expressions Modifiers
Regular expressions: Modifiers
Modifiers change the interpretation of certain characters in a regular
expression or the way in which PHP finds a match for a regular expression
/ /s Treat string as a single long line
. matches any character including \n
^ matches only at string start
$ matches only at string end modulo preceding \n
/ /m Treat string as a set of multiple lines
. matches any character except \n
^ matches at a line start
$ matches at a line end
Target string "Hillary\nClinton"
/(bill|hillary).clinton/mi does not match
/(bill|hillary).clinton/si does match
/(bill|hillary).^clinton/mi does not match
/(bill|hillary).^clinton/si does not match
COMP284 Scripting Languages Lecture 6 Slide L6 17
Regular Expressions Modifiers
Regular expressions: Modifiers
Modifiers change the interpretation of certain characters in a regular
expression or the way in which Perl finds a match for a regular expression
/ /sm Treat string as a single long line, but detect multiple lines
. matches any character including \n
^ matches at a line start
$ matches at a line end
Target string "Hillary\nClinton"
/(bill|hillary).^clinton/smi does match
COMP284 Scripting Languages Lecture 6 Slide L6 18
PCRE functions
PCRE functions: preg_match (1)
int preg_match(rx, str [,&$matches [,flags [,offset]]])
Attempts to match the regular expression rx against the string str
starting at offset
Returns 1 if there is match; 0 if there is not; FALSE in case of error
$matches is an array containing at index 0 the full match and at the
remaining indices the matches for any capture groups
flags modify the behaviour of the function
$txt = " Yabba dabba doo";
if ( pre g_mat ch ( ' /^[ a -z\s]* $/i' , $txt )) {
echo " ' $txt ' only consists of letters and spaces "
}
' Yabba dabba doo ' only consists of letters and s paces
COMP284 Scripting Languages Lecture 6 Slide L6 19
PCRE functions
PCRE functions: preg_match (2)
int preg_match(rx, str [,&$matches [,flags [,offset]]])
Attempts to match the regular expression rx against the string str
starting at offset
Returns 1 if there is match; 0 if there is not; FALSE in case of error
$matches is an array containing at index 0 the full match and at the
remaining indices the matches for any capture groups
flags modify the behaviour of the function
$t = " Yabba dadda doo ";
if ( pre g_mat ch ( ' /((? < c1 >\w)(? < c2 >\ w)\ g{c2 }\ g{c1 })/ ' ,$t ,$m )){
for each ( $m as $ key = > $ value ) {
printf ( " % -2 s => %s\n" , $key , $v alue );
} }
0 = > abba
1 = > abba
c1 => a c2 => b
2 = > a 3 => b
COMP284 Scripting Languages Lecture 6 Slide L6 20
PCRE functions
PCRE functions: preg_match_all
int preg_match_all(rx, str [,&$matches [,flags [,offs]]])
Retrieves all matches of the regular expression rx against the string
str starting at offs
Returns the number of matches; FALSE in case of error
$matches is a multi-dimensional array containing the matches found
flags modify the behaviour of the function
$txt = " Yabba dadda doo";
if ( preg _ match_ all (' /((? < c1 >\ w)(? < c2 >\ w)\ g{c2 }\ g{c1 })/ ' ,
$txt ,$m , PRE G_SET_ ORDER )){
pri nt_r ( $m ); }
Array ( [0] =>
Array (
[0] = > abba
[1] = > abba
[ c1] => a [ c2 ] = > b
[2] = > a [3] = > b )
[1] = >
Array (
[0] = > adda
[1] = > adda
[ c1] => a [ c2 ] = > d
[2] = > a [3] = > d ))
COMP284 Scripting Languages Lecture 6 Slide L6 21
PCRE functions
PCRE functions: preg_replace
mixed preg_replace(rx, rpl, str [, lmt [, &$num]])
Returns the result of replacing matches of rx in str by rpl
lmt specifies the maximum number of replacements
On completion, $num contains the number of replacements
performed
rpl can refer back to capturing subpatterns in rx via $N where N is
a natural number
$old = " Dr Ullrich Hus tadt ";
$new = preg _repla ce ( ' /( Mr|Ms | Mrs |Dr )?\ s *(\ w +)\ s +(\ w+)/ ' ,
'$3 , $2 ' , $old );
echo $ new ;
Hustadt , Ullrich
COMP284 Scripting Languages Lecture 6 Slide L6 22
PCRE functions
PCRE functions: preg_replace
mixed preg_replace_callback(rx,fun,str [,lmt [,&$num]])
Returns the result of replacing matches of rx in str by the return
values of the application of fun to each match
lmt specifies the maximum number of replacements
On completion, $num contains the number of replacements
performed
$old = " 105 deg rees Fahr enhei t is quite warm ";
$new = preg_r e p lace_ca l lback (' /(\ d+) degrees Fahre nheit / ',
function ( $ match ) {
return round (( $ match [1] - 32) * 5 / 9) .
" de grees Celcius ";
}, $old );
echo $ new ;
41 degr ees Cel cius is quite warm
COMP284 Scripting Languages Lecture 6 Slide L6 23
PCRE functions
PCRE functions: preg_split
array preg_split(rx, str [,lmt [,flags]])
Splits str by the regular expression rx and returns the result as array
lmt specifies the maximum number of split components
flags modify the behaviour of the function
# Establish the freq uency of words in a string
$st ring = " peter paul mary paul jim mary paul ";
$count = [];
for each ( pre g_spl it ( ' /\ s+/ ' , $string ) as $ word )
if ( array _key_ex ists ( $word , $count ))
$count [ $word ]++;
else
$count [ $word ] = 1;
for each ( $count as $ key => $va lue )
print ( " $key => $value ; " );
peter = > 1; paul = > 3; mary => 2; jim = > 1;
COMP284 Scripting Languages Lecture 6 Slide L6 24
PCRE functions
Revision
Read
R. Cox: Regular Expression Matching Can Be Simple And Fast (but is slow
in Java, Perl, PHP, Python, Ruby, . . . ). swtchboard, Jan 2007.
https://swtch.com/
~
rsc/regexp/regexp1.html [accessed 28 Dec 2019]
Read
PHP Manual: Regular Expressions (Perl-Compatible)
http://uk.php.net/manual/en/book.pcre.php
of P. Cowburn (ed.): PHP Manual. The PHP Group, 24 Dec 2019.
http://uk.php.net/manual/en [accessed 29 Dec 2019]
COMP284 Scripting Languages Lecture 6 Slide L6 25
COMP284 Scripting Languages
Lecture 7: PHP (Part 5)
Handouts
Ullrich Hustadt
Department of Computer Science
School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
21 Web applications
Overview
HTML forms
22 Available information and Input
Overview
PHP environment
Server variables
Form data
23 PHP sessions
Start a PHP session
Maintain session data
End a PHP session
Session management
Example
24 Authentication
Overview
Example
COMP284 Scripting Languages Lecture 7 Slide L7 1
Web applications Overview
Web applications using PHP
IBM: Build Ajax-based Web sites with PHP, 2 Sep 2008.
https://www.ibm.com/developerworks/library/wa-aj-php/ [accessed 6 Mar 2013]
COMP284 Scripting Languages Lecture 7 Slide L7 2
Web applications HTML forms
HTML forms
When considering Pythan CGI programming we have used HTML forms
that generated a client request that was handled by a Python CGI
program:
< form action = ' process . py ' method = ' post ' >
...
</ form >
Now we will use a PHP script instead:
< form action = ' process . php ' method = ' post ' >
...
</ form >
The PHP script file must be stored in a directory accessible by the web
server, for example $HOME/public_html, and be readable by the web
server
The PHP script file name must have the extension .php, e.g. demo.php
COMP284 Scripting Languages Lecture 7 Slide L7 3
Available information and Input Overview
Information available to PHP scripts
Information about the PHP environment
Information about the web server and client request
Information stored in files and datbases
Form data
Cookie/Session data
Miscellaneous
string date(format)
returns the current date/time presented according to format
for example, date('H:i l, j F Y')
results in 12:20 Thursday, 8 March 2012
(See http://www.php.net/manual/en/function.date.php)
int time()
returns the current time measured in the number of seconds
since January 1 1970 00:00:00 GMT
COMP284 Scripting Languages Lecture 7 Slide L7 4
Available information and Input PHP environment
PHP environment
phpinfo([part])
displays information about the PHP installation and EGPCS data
(Environment, GET, POST, Cookie, and Server data)
for the current client request
if the optional part is specified, only displays selected information
INFO_GENERAL The configuration, php.ini location, build
date, web server
INFO_CONFIGURATION Local and master values for PHP directives
INFO_MODULES Loaded modules
INFO_VARIABLES All EGPCS data
< html lang = " en - GB " ><head > </ head > < body >
<? php
php info (); // Show all infor matio n
php info ( INFO_ VARIABL ES ); // Show only info on EGPCS data
?>
</ body > </ html >
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/phpinfo.php
COMP284 Scripting Languages Lecture 7 Slide L7 5
Available information and Input PHP environment
Manipulating the PHP configuration
The following functions can be used to access and change the
configuation of PHP from within a PHP script:
array ini_get_all()
returns all the registered configuration options
string ini_get(option)
returns the value of the configuration option option
string ini_set(option, value)
sets the value of the given configuration option to a new value
the configuration option will keep this new value during the script’s
execution and will be restored afterwards
void ini_restore(option)
restores a given configuration option to its original value
COMP284 Scripting Languages Lecture 7 Slide L7 6
Available information and Input PHP environment
Manipulating the PHP configuration: Debugging
By default, our web server does not make errors, notices, and warnings
visible to the user
This can be changed using ini_set with the display_errors option
Via the error_reporting function we can then extend what is
reported by PHP
< html lang = " en - GB " ><head > </ head > < body >
<? php
ini _set ( ' displ ay_err o rs ' ,1);
error _report ing ( E_ALL | E_STRICT );
echo " <p > The value of 1 divided by 0 is " ,1/0 ," </p>";
?>
</ body > </ html >
COMP284 Scripting Languages Lecture 7 Slide L7 7
Available information and Input Server variables
Server variables
The $_SERVER array stores information about the web server
and the client request
; Corresponds to os.environ array in Python CGI programs
< html lang = " en - GB " ><head > </ head > < body >
<? php
echo ' Server software : ' , $ _SER VER [ ' SERVER_ SOFTWAR E ' ], ' <br > ' ;
echo ' Remote address : ' , $ _SER VER [ ' REMOTE_ADDR '] , ' <br >';
echo ' Client browser : ' , $ _SER VER [ ' H TTP_US ER_AGEN T ' ], ' <br > ' ;
echo ' R equest method : ' , $ _SER VER [ ' REQUEST _METHO D '];
? > </body > </html >
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/server.php
Server soft ware : Apache /2.2 .22 ( Fedora )
Remote address : 1 0.128. 0.215
Client browser : Mozilla /5.0 ... Chrome / 41.0.2 272.53 ...
Req uest met hod :
See http://php.net/manual/en/reserved.variables.server.php
for a list of keys
COMP284 Scripting Languages Lecture 7 Slide L7 8
Available information and Input Form data
Form data
Form data is passed to a PHP script via the three arrays:
$_POST Data from POST client requests
$_GET Data from GET client requests
$_REQUEST Combined data from POST and GET client requests
(derived from $_POST and $_GET)
; Accessing $_REQUEST is the equivalent in PHP to
using cgi.FieldStorage() in a Python CGI program
< 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 resp onse " > </ form >
$_REQUEST['username'] Value entered into field with name ‘username’
$_REQUEST['fullname'] Value entered into field with name ‘fullname’
COMP284 Scripting Languages Lecture 7 Slide L7 9
Available information and Input Form data
Example
We want to develop a PHP script with the following functionality
Access is restricted to IP addresses starting with 138.253
(University of Liverpool IP addresses)
The program prints out an HTML document with an HTML form that
allows a user to enter the data required for our program
The drop-down menu should cover the previous nine years
On submission of the completed form, the program checks inputs for
validity
If inputs are invalid issues errors messages and prints out the form again
If inputs are valid, (i) generates a username based on the data entered into
that form and (ii) prints out an HTML document with that username
A name is valid if it consists of a single given name and single surname,
each starting with a capital letter followed by one or more lowercase
letters
A year is valid if it consists of four digits
COMP284 Scripting Languages Lecture 7 Slide L7 10
Available information and Input Form data
Useful PHP functions
string strtolower(str)
Returns string with all alphabetic characters in str converted to lower-
case
string substr(str, start [, length])
Returns the portion of the string str starting at position start and
consisting of at most length characters
If start is negative, the returned string will start at the start’th
character from the end of string
If length is omitted, the returned string continues til the end of str
string date(format [, timestamp])
Returns a string formatted according to the given format string
format using the given timestamp or the current time if no
timestamp is given
For format ’Y’ returns the current year
COMP284 Scripting Languages Lecture 7 Slide L7 11
Available information and Input Form data
Example: HTML Form
function prin tForm () {
echo "
< form action = ' generate . php ' method = ' post '>
<label > Enter your full name :
< input type = ' text ' name = ' ful lname '>
</ label >
<label > Select your year of r egist ration :
< select name = ' year '>
<option >-- - - </ option >";
$now = date ("Y");
for ( $year = $ now - 9; $year <= $now ; $ ye ar ++)
echo " <option > $year </ option >\ n";
echo "
</ select >
</ label >
< input type = ' submit ' name=' submit ' value = ' Gene rate '>
</ form >";
}
COMP284 Scripting Languages Lecture 7 Slide L7 12
Available information and Input Form data
Example: Input validation
function valida teInpu t s ( $ name , $year ) {
$err = " " ;
/* A name is valid if it consists of a single given name
and single surname , each starting with a capital
letter foll owed by one or more l owercase let ters */
if (! pre g_mat ch ( ' /^[ A -Z][ a -z ]+\ s+[ A -Z][ a -z]+ $/' ,$name ) ) {
$err .= " Please enter your first name followed by your
,secon d name .";
}
/* A year is valid if it consists of four digi ts */
if (! pre g_mat ch ( ' /^\ d {4} $/' , $ year )) {
$err .= " Please enter the year you r egist ered using four
, digi ts .";
}
return $err ;
}
COMP284 Scripting Languages Lecture 7 Slide L7 13
Available information and Input Form data
Example: Username
Simple function for generating a username from the full name of a user
and the year the user has registered
function genUs ernam e ( $ name , $year) {
$names = preg_ split ( '/\ s +/ ',$name );
// first letter of given name
return (" sg" . strtolower ( substr ( $names [0] , 0 1))
// first three letters of sur name
. strto lower ( substr ( $names [1] , 0, 3))
// last to digits of year
. sub str ( $year , -2) );
}
COMP284 Scripting Languages Lecture 7 Slide L7 14
Available information and Input Form data
Example: Processing inputs
Processing inputs once the user has submitted name and year
function proce s sInput s ( $ name , $year ) {
if ( $err = valida teInpu t s ( $ name , $year )) {
/* If the vali datio n of i nputs produced a non - empy
error message , show it to the user and produce
the form again . */
echo " <div class =' error '>$err </ div >\ n";
printFor m ();
} else {
/* If the vali datio n of i nputs produced an empty
error message , comp ute the usern ame and show
it to the user . */
$usernam e = genUs ernam e ( $ name , $year );
echo " <div > The user name for $ name regis tered in $year
is $username </div >\n";
}
}
COMP284 Scripting Languages Lecture 7 Slide L7 15
Available information and Input Form data
Example: Putting everything together
<! D OCTYPE html >
< html lang= ' en - GB ' >
<head >
< link rel = ' st ylesheet ' type= ' text/ css ' href = ' form. css '>
<title > Gen erate Username </ title >
</ head >
<body >
<? php
if ( s ubstr ( $ _S ERV ER [" R EMO TE_ ADD R "] ,0 ,7) != " 138.253 ") {
echo ("<div class =' eror ' ><b > Sorry , please come back
when you are on a uni computer </b > </ div >\ n" );
} else {
if ( isset ( $ _RE QUE ST [ ' submit ' ])) {
pro ces sIn put s ( $ _REQUEST [ ' full name '] , $_ REQ UEST [ ' year ' ]);
} else {
// Show user the form
printFor m ();
}
}
?>
</ body >
</ html >
COMP284 Scripting Languages Lecture 7 Slide L7 16
Available information and Input Form data
Web Applications Revisited
Select
Item
Enter
Address
Enter
Payment
Confirm
Order
App
App
App
App
App
Request
Response
Request
Response
Request
Response
Request
Response
Request
An interaction between a user
and a server-side web application
often requires a sequence of
requests and responses
For each request, the application
starts from scratch
it does not remember any data
between consecutive requests
it does not know whether the
requests come from the same user
or different users
; data needs to be transferred
from one execution of the
application to the next
COMP284 Scripting Languages Lecture 7 Slide L7 17
Available information and Input Form data
Transfer of Data: Example
Assume the user completes a sequence of forms
By default, a PHP script only has access to the information entered into
the last form
form1.php
< form action = " form2 . php" method = " post " >
<label > Item : < input type = " text " name ="item " > </ label >
</ form >
form2.php
< form action = " process . php " method = " post " >
<label > A ddress : < input type =" text " name =" address " > </ label >
</ form >
process.php
<? php echo $ _REQUEST [ ' item ']; echo $ _REQ UEST [ ' address ']; ? >
; PHP Notice: Undefined index ’item’
COMP284 Scripting Languages Lecture 7 Slide L7 18
Available information and Input Form data
Transfer of Data: Hidden Inputs
Assume for a sequence of requests we do not care whether they come
from the same user and whether remembered data has been manipulated
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 > Item : < input type = " text " name ="item " > </ label >
</ form >
form2.php
< form action = " process . php " method = " post " >
<label > A ddress : < input type =" text " name =" address " > </ label >
< input type = " hidden " name = " item "
value = " <? php echo $_REQUES T [' item '] ?>" >
</ form >
process.php
<? php echo $ _REQUEST [ ' item ']; echo $ _REQ UEST [ ' address ']; ? >
; 'item' is remembered but can be manipulated
COMP284 Scripting Languages Lecture 7 Slide L7 19
PHP sessions
Sessions
Assume for a sequence of requests we do care that they come from the
same user and that remembered data has not been manipulated
Sessions help to solve this problem by associating client requests with a
specific user and maintaining data over a sequence of requests from
that user
Sessions are often linked to user authentication but session can be used
without user authentication, for example, eCommerce websites maintain
a ‘shopping basket’ without requiring user authentication first
However, sessions are the mechanism that is typically used to allow or
deny access to web pages based on a user having been authenticated
COMP284 Scripting Languages Lecture 7 Slide L7 20
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
is remembered by the browser
is then send by the browser with every further HTTP request to that server
is forgotten by the browser when the session ends or the browser is closed
In addition, the server can use session variables for storing information
that relate to a session (session data), for example,
the items of an order
Sessions variables 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 persistent cookie or a
database to store such information
COMP284 Scripting Languages Lecture 7 Slide L7 21
PHP sessions
Sessions and cookies
Sessions
ID and session data are stored on the web server (server-side)
Access and changes to session data are done in PHP
via $_SESSION array
Expiration can not be set, session data will be expired when users close
the browser or session is ended by script
Web client / user cannot manipulate the data
Cookies
ID and cookie data are stored by the web client (client-side) on the
user’s device
Access to cookie data is done in PHP via $_COOKIE array
Changes to cookie data are done in PHP via setcookie
Expiration can be set, e.g., via setcookie
Web client / user / hackers can manipulate the data
COMP284 Scripting Languages Lecture 7 Slide L7 22
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()
$_SESSION = array();
void session_unset()
bool setcookie(name, value, expires, path)
COMP284 Scripting Languages Lecture 7 Slide L7 23
PHP sessions Start a PHP session
Start a session
bool session_start()
creates a session
creates a session identifier (session id) when a session is created
sets up $_SESSION array that stores session variables and session data
the function must be executed before any other header calls
or output is produced
string session_id([id])
get or set the session id for the current session
the constant SID can also be used to retrieve the current name and
session id as a string suitable for adding to URLs
string session_name([name])
returns the name of the current session
if a name is given, the current session name will be replaced with the
given one and the old name returned
COMP284 Scripting Languages Lecture 7 Slide L7 24
PHP sessions Start a PHP session
Start a PHP session
bool session_regenerate_id([delete_old])
replaces the current session id with a new one
by default keeps the current session information stored in $_SESSION
if the optional boolean agument is TRUE, then the current session
information is deleted
; regular use of this function alleviates the risk of a session
being ‘hijacked’
<? php
sess i on_sta rt ();
echo " Session id : " , sess ion_i d () ," <br >";
echo " Session name : " , sess ion_na me () ," <br >";
sessio n _regener a te_id ();
echo " Session id : " , sess ion_i d () ," <br >"; // chan ged
echo " Session name : " , sess ion_na me () ," <br >"; // u nchanged
?>
COMP284 Scripting Languages Lecture 7 Slide L7 25
PHP sessions Maintain session data
Maintain session data
bool session_start()
resumes the current session based on a session identifier
passed via a GET or POST request, or passed via a cookie
restores session variables and session data into $_SESSION
the function must be executed before any other header calls
or output is produced
$_SESSION array
an associative array containing session variables and session data
you are responsible for choosing keys (session variables)
and maintaining the associated values (session data)
bool isset($_SESSION[key])
returns TRUE iff $_SESSION[key] has already been assigned a value
COMP284 Scripting Languages Lecture 7 Slide L7 26
PHP sessions Maintain session data
Maintain session data
bool session_start()
$_SESSION array
bool isset($_SESSION[key])
<? php
// Counting the number of page reque sts in a session
// Each web page contains the follo wing PHP code
sess i on_sta rt ();
if (! isset ( $_S ESSION [ ' re quests ' ]))
$_SESSIO N [ ' request s ' ] = 1;
else
$_SESSIO N [ ' request s ' ]++;
echo " # Requests in this session so far : ",
$_SESSIO N [ ' request s ' ]," <br >\n";
?>
COMP284 Scripting Languages Lecture 7 Slide L7 27
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
$_SESSION = array() or 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
name: the name of the cookie
value: the value of the cookie
expires: the time the cookie expires (as a Unix timestamp)
path: the path on the server in which the cookie will be available
COMP284 Scripting Languages Lecture 7 Slide L7 28
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
must occur before <html>-tag
<? php
sess i on_sta rt ();
sess i on_uns et ();
if ( ses sion_ id () != "" || isset ( $ _COOKIE [ sessi on_nam e ()]))
// force the cook ie to expire
setcooki e ( sess ion_na me () , session_id () , time () -2592000 , '/' );
sessi on_dest roy ();
?>
Note: Closing your web browser will also end a session
COMP284 Scripting Languages Lecture 7 Slide L7 29
PHP sessions End a PHP session
Transfer of Data: Sessions (Part 1)
Assume for a sequence of requests we do care whether they come from
the same user or different users
form1Session.php (no changes)
< form action = " form2 Sessio n . php" method = " post " >
<label > Item : < input type = " text " name ="item " > </ label >
</ form >
Starting/maintaining a session for the first form is optional
COMP284 Scripting Languages Lecture 7 Slide L7 30
PHP sessions End a PHP session
Transfer of Data: Sessions (Part 2)
Assume for a sequence of requests we do care whether they come from
the same user or different users
form2Session.php
<? php
sess i on_sta rt ();
if ( isset ( $_R EQUEST [ ' item ' ]))
$_SESSIO N [ ' item ' ] = $ _REQUEST [ ' item '];
?>
<! DOCTYP E html >
< html lang = 'en - GB '>
<head ><title > Form 2 </ title > </ head >
<body >
< form action = " proces sSessi on . php " method = " post " >
<label > A ddress : < input type =" text " name =" address " >
</ label >
<!-- no hidden input r equired -->
</ form >
</ body >
</ html >
COMP284 Scripting Languages Lecture 7 Slide L7 31
PHP sessions End a PHP session
Transfer of Data: Sessions (Part 3)
Assume for a sequence of requests we do care whether they come from
the same user or different users
processSession.php
<? php
sess i on_sta rt ();
// not nece ssary but conv enien t
if ( isset ( $_R EQUEST [ ' ad dress ' ]))
$_SESSIO N [ ' addres s ' ] = $ _RE QUEST [ ' address ' ];
?>
<! DOCTYP E html >
< html lang = 'en - GB '>
<head ><title > Processing </ title > </head >
<body >
<? php
echo $_SESSIO N [ ' item ' ]; echo $ _SE SSION [ ' add ress ' ];
// Once we do not need the data anymore , get rid of it
sess i on_uns et (); sess i on_des t roy ();
?>
</ body > </ html >
COMP284 Scripting Languages Lecture 7 Slide L7 32
PHP sessions Session management
More on session management
The following code tracks whether a session is active and ends the session
if there has been no activity for more then 30 minutes
if ( isset( $_ SE SSION [' LA ST_ACTIVITY ' ]) &&
( time () - $ _S ES SION [ ' L AS T_ ACTIVITY '] > 1 800)) {
// last r eques t was more than 30 min ates ago
se ss io n_ destroy (); // destr oy sess ion data in stora ge
$_ SE SSION = array (); // un set s essio n va riables
if ( s ession_id () != " " || is set ( $_ COOKIE [ s es si on _name ( )]) )
se tc ookie ( se ss io n_ na me (), se ss io n_id (), time () -25 92000 , '/ ' );
} else {
// upd ate last activi ty time stamp
$_ SE SSION [ ' LA ST _A CTIVITY ' ] = time ();
}
The following code generates a new session identifier every 30 minutes
if (! isset ( $_SESSI ON [' CRE ATED ' ])) {
$_ SE SSION [ ' CREAT ED '] = ti me ();
} else if ( time () - $ _S ESSION [ ' CREA TED ' ] > 1800) {
// sessi on star ted m ore than 30 minates ago
session_reg en er at e_ id ( tru e );
$_ SE SSION [ ' CREAT ED '] = ti me ();
}
http://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session- after- 30-minutes
COMP284 Scripting Languages Lecture 7 Slide L7 33
PHP sessions Example
PHP sessions: Example
mylibrary.php:
<? php
sess i on_sta rt ();
function destroy_ s e ssion_an d _data () {
$_SESSIO N = array ();
if ( ses sion_ id () != "" || isset ( $ _COOKIE [ sessi on_nam e ()]))
setcooki e ( sess ion_na me () , session_id () , time () -2592000 , '/' );
sessi on_dest roy ();
}
function count_ reques t s () {
if (! isset ( $_S ESSION [ ' re quests ' ]))
$_SESSIO N [ ' request s ' ] = 1;
else $_SESSIO N [ ' request s ' ]++;
return $ _SESSION [ ' requests ' ];
}
?>
COMP284 Scripting Languages Lecture 7 Slide L7 34
PHP sessions Example
PHP sessions: Example
page1.php:
<? php
requ ire_on ce ' my library .php ';
echo " <html lang ='en -GB ' ><head > </ head ><body >
Hello visitor ! < br > This is your page req uest no ";
echo count _reques ts (). " from this site . < br >\ n " ;
echo " <a href =' page1 .php '>Continue </a> |
<a href =' finish . php '>Finish </a > </body >";
?>
finish.php:
<? php
requ ire_on ce ' my library .php ';
destro y _ session_ a nd_data ();
echo " <html lang ='en -GB ' ><head > </ head ><body >
Goo dbye visitor ! < br >
<a href =' page1 . php '>Start again </ a > </body >";
?>
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/page1.php
COMP284 Scripting Languages Lecture 7 Slide L7 35
PHP sessions Example
PHP and Cookies
Cookies can survive a session and transfer information from one session to
the next
cmylibrary.php:
<? php
sess i on_sta rt ();
function destroy_ s e ssion_an d _data () { // uncha nged }
function count_ reques t s () {
if (! isset ( $_COOKI E [ ' re quests ' ])) {
setcooki e ( ' request s ' , 1, time ()+31 536000 , '/' );
return 1;
} else {
// $ _COOKIE [ ' requests ']++ would not survive , i nstead use
setcooki e ( ' request s ' , $ _COOKIE [ ' requests ' ]+1 ,
time ()+ 31536000 , ' / ' ); // valid for 1 year
return $ _CO OKIE [ ' requests ' ]+1;
} }
?>
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/cpage1.php
COMP284 Scripting Languages Lecture 7 Slide L7 36
Authentication Overview
PHP Sessions and Authentication
Sessions are the mechanism that is typically used to allow or deny
access to web pages based on a user having been authenticated
Outline solution:
We want to protect a page content.php from unauthorised use
Before being allowed to access content.php, users must first authenticate
themselves by providing a username and password on the page login.php
The system maintains a list of valid usernames and passwords in a database
and checks usernames and passwords entered by the user against that
database
If the check succeeds, a session variable is set
The page content.php checks whether this session variable is set
If the session variable is set, the user will see the content of the page
If the session variable is not set, the user is redirected to login.php
The system also provides a logout.php page to allow the user to log out
again
COMP284 Scripting Languages Lecture 7 Slide L7 37
Authentication Example
PHP Sessions and Authentication: Example
content.php:
<? php
sess i on_sta rt ();
if (! isset ( $_S ESSION [ ' user ' ])) {
// User is not logged in , redir ectin g to login page
header ( ' Location : login . php ' );
}
?>
<! DOCTYP E html >
< html lang = " en - GB " >
<head ><title > Content that requ ires login </ title > </ head >
<body >
<h1 > P rotected Content </h1 >
<b > Welcome <i> <? php echo $ _SESSION [ ' user '] ? ></i > </b><br >
<b ><a href =" logout . php " >Log Out </a ></b >
</ body >
</ html >
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/content.php
COMP284 Scripting Languages Lecture 7 Slide L7 38
Authentication Example
PHP Sessions and Authentication: Example
Second part of login.php:
<! DOCTYP E html >
< html lang = " en - GB " >
<head ><title > Login </ title > </ head >
<body >
<h1 >Login </ h1 >
< form action = " " method = " post " >
<label > U sername :
< input name = " user " p laceholder = " user name " type =" text " >
</ label >
<label > P assword :
< input name = " passwd " p laceh older = " ** " type =" passw ord " >
</ label >
< input name = " submit " type = " submit " value =" login ">
<span > <? php echo $error ; ? ></ span >
</ form >
</ body >
</ html >
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/login.php
COMP284 Scripting Languages Lecture 7 Slide L7 39
Authentication Example
PHP Sessions and Authentication: Example
First part of login.php:
<? php
session_ sta rt ();
functio n checkCre den tia ls ( $ user , $ passwd ) {
// Check whet her $ us er and $p asswd are non - empty
// and match an entry in the databas e
}
$error = ' ';
if ( isset ( $_SE SSION [ ' user ' ])) {
header (" locat ion : content . php");
} else {
if ( isset ( $_RE QUEST [ ' submit '])) {
if ( che ckC red ent ial s ( $_REQ UEST [ ' user ' ], $ _REQ UEST [ ' passwd ' ])) {
$_SES SION [ ' user ' ]= $ _R EQUES T [ ' user '];
header (" locat ion : content . php"); // Red irect ing to Content
} else {
$error = " Us ername or Pas sword is i nvalid . Try Again ";
} } }
?>
COMP284 Scripting Languages Lecture 7 Slide L7 40
Authentication Example
PHP Sessions and Authentication: Example
logout.php:
<? php
sess i on_sta rt ();
$user = $ _SESSION [ ' user '];
$_SESSIO N = array ();
sessi on_dest roy ();
?>
<! DOCTYP E 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 >
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/logout.php
COMP284 Scripting Languages Lecture 7 Slide L7 41
Authentication Example
Revision
Read
Chapter 10: Accessing MySQL Using PHP
Chapter 11: Form Handling
Chapter 12: Cookies, Sessions, and Authentication
of
R. Nixon:
Learning PHP, MySQL, and JavaScript.
O’Reilly, 2018.
COMP284 Scripting Languages Lecture 7 Slide L7 42
COMP284 Scripting Languages
Lecture 8: PHP (Part 6)
Handouts
Ullrich Hustadt
Department of Computer Science
School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
25 Classes
Defining and Instantiating a Class
Visibility
Class Constants
Static Properties and Methods
Destructors
Inheritance
Interfaces
Introspection Functions
26 The PDO Class
Introduction
Connections
Queries and Processing of Results
Prepared Statements
Transactions
COMP284 Scripting Languages Lecture 8 Slide L8 1
Classes Defining and Instantiating a Class
Defining and Instantiating a Class
PHP is an object-oriented language with classes
A class can be defined as follows:
class i denti fier {
proper t y_defin i tions
functi o n_defin i tions
}
The class name identifier is case-sensitive
The body of a class consists of property definitions and function definitions
The function definitions may include the definition of a constructor
An object of a class is created using
new identifier ( arg1 , arg2 ,...)
where arg1,arg2,... is a possibly empty list of arguments passed to
the constructor of the class identifier
COMP284 Scripting Languages Lecture 8 Slide L8 2
Classes Defining and Instantiating a Class
A Closer Look at Class Definitions
In more detail, the definition of a class
typically looks as follows
class i denti fier {
# Prope rties
vis $ attrib1
...
vis $ attribN = value
# Const ructor
function __con struc t (p1 ,...) {
stat ement s
}
# Methods
vis function method1 ( p1 ,...) {
stat ement s
}
vis function methodN ( p1 ,...) {
stat ement s
}
}
Every instance obj of this
class will have attributes
attrib1,. . . and methods
method1(), . . . accessible
as obj->attrib1 and
obj->method1(a1...)
__construct is the
constructor of the class and
will be called whenever
new identifier(a1,...)
is executed
vis is a declaration of the
visibility of each attribute
and method
COMP284 Scripting Languages Lecture 8 Slide L8 3
Classes Defining and Instantiating a Class
A Closer Look at Class Definitions
The pseudo-variable $this is available when a method is called from
within an object context and is a reference to the calling object
Inside method definitions, $this can be used to refer to the properties
and methods of the calling object
The object operator -> is used to access methods and properties of the
calling object
class R ectangle {
protecte d $he ight ;
protecte d $width ;
function __con struc t ( $height , $width ) {
$this -> width = $ wid th ;
$this -> height = $height ;
}
}
COMP284 Scripting Languages Lecture 8 Slide L8 4
Classes Visibility
Visibility
Properties and methods can be declared as
public accessible everywhere
private accessible only within the same class
protected accessible only within the class itself and
by inheriting and parent classes
For properties, a visibility
declaration is required
For methods, a visibility
declaration is optional
; by default, methods
are public
Accessing a private or
protected property /
method outside its visibility
is a fatal error
class Vis {
public $ public = 1;
pri vate $private = 2;
protecte d $ pro tecte d = 3;
protecte d function proFc () {}
pri vate function priFc () {}
}
$v = new Vis ();
echo $v - > public ; # prints 1
echo $v - > private ; # Fatal Error
echo $v - > prot ected ; # Fatal Error
echo $v - > priFc (); # Fatal Error
echo $v - > proFc (); # Fatal Error
COMP284 Scripting Languages Lecture 8 Slide L8 5
Classes Class Constants
Constants
Classes can have their own constants and
constants can be declared to be public, private or protected
; by default, class constants are public
vis const i denti fier = value ;
Accessing a private or protected constant outside its visibility
is a fatal error ; execution of the script stops
Class constants are allocated once per class,
and not for each class instance
Class constants are accessed using the scope resolution operator ::
class MyClass {
const SIZE = 10;
}
echo M yClass :: SIZE ; # prints 10
$o = new MyC lass ();
echo $o :: SIZE ; # prints 10
COMP284 Scripting Languages Lecture 8 Slide L8 6
Classes Static Properties and Methods
Static Properties and Methods
Class properties or methods can be declared static
Static class properties and methods are accessed (via the class) using
the scope resolution operator ::
Static class properties cannot be accessed via an instantiated
class object, but static class methods can
Static class method have no access to $this
class E mplo yee {
static $ total Number = 0;
public $name ;
function __con struc t ( $name ) {
$this -> name = $name ;
Employee :: $tot alNumb er ++;
} }
$e1 = new E mplo yee ( " Ada " );
$e2 = new E mplo yee ( " Ben " );
echo E mployee :: $ totalN umber # prints 2
COMP284 Scripting Languages Lecture 8 Slide L8 7
Classes Destructors
Destructors
A class can have a destructor method __destruct that will be called as
soon as there are no references to a particular object
class E mplo yee {
static $ total Number = 0;
public $name ;
function __con struc t ( $name ) {
$this -> name = $name ;
Employee :: $tot alNumb er ++;
}
function __de struct () {
Employee :: $totalNumber - -;
}
}
$e1 = new E mplo yee ( " Ada " );
$e2 = new E mplo yee ( " Ben " );
echo E mployee :: $ totalN umber # prints 2
$e1 = null ;
echo E mployee :: $ totalN umber # prints 1
COMP284 Scripting Languages Lecture 8 Slide L8 8
Classes Inheritance
Inheritance
In a class definition it is possible to specify one parent class from which
a class inherits constants, properties and methods:
class i dentif ier1 ext ends ident ifier 2 { ... }
The constructor of the parent class is not automatically called it must
be called explicitly from the child class
Inherited constants, properties and methods can be overridden by
redeclaring them with the same name defined in the parent class
The declaration final can be used to prevent a method from being
overriden
Using parent:: it is possible to access overridden methods or static
properties of the parent class
Using self:: it is possible to access static properties and methods of
the current class
COMP284 Scripting Languages Lecture 8 Slide L8 9
Classes Inheritance
Inheritance: Example
class R ec ta ngle {
protected $ height ;
protected $ width;
fu nction _ _c onstruc t ( $ height , $ width ) {
$this - > height = $height ;
$this - > widt h = $ width ;
}
fu nction area () {
re turn $this - > width * $this -> he ight ;
} }
class Square extends Rectang le {
fu nction _ _c onstruc t ( $size ) {
pa rent :: __ co nstruct ($size , $ size );
} }
$rt1 = new Recta ng le (3 ,4);
echo "\ $rt1 area = " , $rt1 -> area () , "\n ";
$sq1 = new Square (5);
echo "\ $sq1 area = " , $sq1 -> area () , "\n ";
$rt1 area = 12
$sq1 area = 25
COMP284 Scripting Languages Lecture 8 Slide L8 10
Classes Interfaces
Interfaces
Interfaces specify which methods a class must implement without
providing an implementation
Interfaces are defined in the same way as a class with the keyword
class replaced by interface
All methods in an interface must be declared public
A class can declare that it implements one ore more interfaces
using the implements keyword
interfac e Shape {
public func tion area ();
}
class R ectangle implements Shape {
...
}
COMP284 Scripting Languages Lecture 8 Slide L8 11
Classes Introspection Functions
Introspection Functions
There are functions for inspecting objects and classes:
bool class_exists(string class)
returns TRUE iff a class class exists
class_exists('Rectangle') # returns TRUE
string get_class(object obj)
returns the name of the class to which an object belongs
get_class($sq1) # returns 'Square'
bool is_a(object obj, string class)
returns TRUE iff obj is an instance of class named class
is_a($sq1,'Rectangle') # returns TRUE
bool method_exists(object obj,string method)
returns TRUE iff obj has a method named method
method_exists($sq1,'area') # returns TRUE
COMP284 Scripting Languages Lecture 8 Slide L8 12
Classes Introspection Functions
Introspection Functions
There are functions for inspecting objects and classes:
bool property_exists(object obj,string property)
returns TRUE iff object has a property named property
property_exists($sq1,'size') # returns FALSE
get_object_vars(object)
returns an array with the accessible non-static properties of object
mapped to their values
get_object_vars($e2)
# returns ["name" => "Ben"]
get_class_methods(class)
returns an array of method names defined for class
get_class_methods('Square')
# returns ["__construct", "area"]
COMP284 Scripting Languages Lecture 8 Slide L8 13
The PDO Class Introduction
The PDO Class
The PHP Data Objects (PDO) extension defines an interface for
accessing databases in PHP
Various PDO drivers implement that interface for specific
database management systems
PDO_MYSQL implements the PDO interface for MySQL 3.x to 5.x
PDO_SQLSRV implements the PDO interface for MS SQL Server and
SQL Azure
COMP284 Scripting Languages Lecture 8 Slide L8 14
The PDO Class Connections
Connections
Before we can interact with a DBMS we need to establish a connection
to it
A connection is established by creating an instance of the PDO class
The constructor for the PDO class accepts arguments that specify the
database source (DSN), username, password and additional options
$pdo = new PDO ( dsn , username , password , options );
Upon successful connection to the database, the constructor returns an
instance of the PDO class
The connection remains active for the lifetime of that PDO object
Assigning NULL to the variable storing the PDO object destroys it and
closes the connection
$pdo = NULL
COMP284 Scripting Languages Lecture 8 Slide L8 15
The PDO Class Connections
Connections: Example
# Conne ction infor mation for the D epartm ental MySQL Server
$host = " studdb . csc . liv. ac. uk";
$user = " sgf surn "; # your U niver sity username
$pa sswd = " ---- ---"; # your MySQL server account passw ord
$db = " sgfsurn " ; # your U niver sity username
$charset = " utf8 mb4 " ;
$dsn = " mysql : host = $host ; dbname = $db; charset = $ch arse t ";
# Use ful options
$opt = array (
PDO :: A TTR_E RRMODE => PDO :: ER RMODE_EXC EPTION ,
PDO :: A T TR_DEFAU L T_FETCH_M O DE = > PDO :: FETC H_ASSOC ,
PDO :: A T TR_EMUL A T E_PREPA R ES => false
);
try {
$pdo = new PDO ( $dsn ,$user , $passwd , $ opt );
} catch ( PDOEx ceptio n $e) {
echo ' Co nnect ion failed : ',$e - > getMe ssage ();
}
COMP284 Scripting Languages Lecture 8 Slide L8 16
The PDO Class Queries and Processing of Results
Queries
The query() method of PDO objects can be used to execute
an SQL query
$result = $pdo->query(statement)
$result = $pdo->query("SELECT * FROM meetings")
query() returns the result set (if any) of the SQL query as a
PDOStatement object
The exec() method of PDO objects executes an SQL statement,
returning the number of rows affected by the statement
$rowNum = $pdo->exec(statement)
$rowNum = $pdo->exec("DELETE * FROM meetings")
COMP284 Scripting Languages Lecture 8 Slide L8 17
The PDO Class Queries and Processing of Results
Processing Result Sets
To get a single row as an array from a result set stored in a
PDOStatement object, we can use the fetch() method
By default, PDO returns each row as an array indexed by
the column name and 0-indexed column position in the row
$row = $result -> fetch ()
array ( ' slot ' => 1,
' name ' = > ' Michael North ',
' email ' = > 'M. N orth@s tudent . live rpool . ac . uk ',
0 => 1,
1 => ' Michael North ' ,
2 => ' M. Nor th@stu dent . l iverpool . ac . uk ')
After the last call of fetch() the result set should be released using
$rows = $result -> clos eCurs or ()
To get all rows as an array of arrays from a result set stored in a
PDOStatement object, we can use the fetchAll() method
$rows = $result -> fetchAl l ()
COMP284 Scripting Languages Lecture 8 Slide L8 18
The PDO Class Queries and Processing of Results
Processing Result Sets
We can use a while-loop together with the fetch() method to iterate
over all rows in a result set
while ( $row = $result -> fetch ()) {
echo " Slot : " , $row[" slot "], " <br >\n";
echo " Name : " , $row[" name "], " <br >\n";
echo " Email : " , $row[" email "]," <br ><br >\n";
}
Alternatively, we can use a foreach-loop
for each ( $result as $ row ) {
echo " Slot : " , $row[" slot "], " <br >\n";
echo " Name : " , $row[" name "], " <br >\n";
echo " Email : " , $row[" email "]," <br ><br >\n";
}
fetch() uses a cursor that moves through the rows in a result set and
does not reset at the end
; store the result set in an array first (e.g., using fetchAll() ),
then iterate over the array as often as you want
COMP284 Scripting Languages Lecture 8 Slide L8 19
The PDO Class Queries and Processing of Results
Processing Result Sets
Using bindColumn() we can bind a variable a particular column in the
result set from a query
columns can be specified by number (starting with 1!)
columns can be specified by name (matching case)
Each call to fetch() and fetchAll() will then update all the
variables that are bound to columns
The binding needs to be renewed after each query execution
$result -> bindColumn (1 , $ slot ); # bind by column no
$result -> bindColumn (2 , $ name );
$result -> bindColumn (' email ' , $ email ); # bind by column name
while ( $row = $result -> fetch ( PDO :: FET CH_BOUND )) {
echo " Slot : " , $slot , " <br >\n";
echo " Name : " , $name , " <br >\n";
echo " Email : " , $email , " <br > < br >\ n " ;
}
COMP284 Scripting Languages Lecture 8 Slide L8 20
The PDO Class Prepared Statements
Prepared Statements
The use of parameterised prepared statements is preferable over queries
Prepared statements are are parsed, analysed, compiled and optimised
only once
Prepared statements can be executed repeatedly with different
arguments
Arguments to prepared statements do not need to be quoted and
binding of parameters to arguments will automatically prevent SQL
injection
PDO can emulate prepared statements for a DBMS that does not
support them
MySQL supports prepared statements natively, so PDO emulation
should be turned off
$pdo -> se tAttri bute (PDO :: A TTR_E MULAT E_PRE PARES , FALSE );
COMP284 Scripting Languages Lecture 8 Slide L8 21
The PDO Class Prepared Statements
Prepared Statements: SQL Templates
Using a prepared statement requires three steps
1 Preparing a statement using a SQL template containing parameters
2 Binding the parameters to values
3 Executing the prepared statements
COMP284 Scripting Languages Lecture 8 Slide L8 22
The PDO Class Prepared Statements
Prepared Statements: SQL Templates
An SQL template is an SQL query (as a string) possibily containing
either
named parameters of the form :name, where name is a PHP identifier, or
question marks ?
for which values will be substituted when the query is executed
$tpl1 = " select slot from meetings where
name =: name and email =: ema il " ;
$tpl2 = " select slot from meetings where name =? " ;
The PDO method prepare() turns an SQL template into prepared
statement (by asking the DBMS to do so)
on success, a PDOStatement object is returned
on failure, FALSE or an error will be returned
$stmt1 = $pdo -> prepare ( $tpl1 );
$stmt2 = $pdo -> prepare (" se lect * from fruit where col =? ");
COMP284 Scripting Languages Lecture 8 Slide L8 23
The PDO Class Prepared Statements
Prepared Statements: Binding
We can bind the parameters of a PDOStatement object to a value
using the bindValue() method
Named parameters are bound by name
Question mark parameters are bound by position (starting from 1!)
the datatype of the value can optionally be declared
(to match that of the corresponding database field)
the value is bound to the parameter at the time bindValue() is executed
$stmt1 -> bindVal ue ( ': name ' ,' Ben ' ,PDO :: P ARAM_STR );
$email = ' bj1@li v . ac. uk';
$stmt1 -> bindVal ue ( ': email ' , $ ema il );
$stmt2 -> bindVal ue (1,20 , PDO :: PARAM_I NT );
COMP284 Scripting Languages Lecture 8 Slide L8 24
The PDO Class Prepared Statements
Prepared Statements: Binding
We can bind the parameters of a PDOStatement object to a variable
using the bindParam() method
Named parameters are bound by name
Question mark parameters are bound by position (starting from 1!)
the datatype of the value can optionally be declared
(to match that of the corresponding database field)
the variable is bound to the parameter as a reference
a value is only substituted when the statement is executed
$name = ' Ben ' ;
$stmt1 -> bindPar am ( ': name ' ,$name , PDO :: PARAM_S TR );
$stmt1 -> bindPar am ( ': email ' , $ ema il );
$email = ' bj1@li v . ac. uk';
$slot = 20;
$stmt2 -> bindPar am (1 , $slot , PDO :: PARAM_I NT );
It is possible to mix bindParam() and bindValue()
COMP284 Scripting Languages Lecture 8 Slide L8 25
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)
This result set can be processed in the same way as the result set
returned by query()
$stmt1 -> ex ecut e ();
$stmt1 -> ex ecut e ( array ( ' : name ' = > ' Eve ' , ': email ' = > $ email ));
$stmt2 -> ex ecut e ( array (10));
COMP284 Scripting Languages Lecture 8 Slide L8 26
The PDO Class Transactions
Transactions
There are often situations where a single ‘unit of work’ requires a
sequence of database operations
; e.g., bookings, transfers
By default, PDO runs in ”auto-commit” mode
; successfully executed SQL statements cannot be ‘undone’
To execute a sequence of SQL statements whose changes are
only committed at the end once all have been successful or
rolled back otherwise,
PDO provides the methods
beginTransaction()
commit()
rollBack()
COMP284 Scripting Languages Lecture 8 Slide L8 27
The PDO Class Transactions
Transactions
To support transactions, PDO provides the methods
beginTransaction()
turns off auto-commit mode; changes to the database are not
committed until commit() is called
returns TRUE on success or FALSE on failure
throws an exception if another transaction is already active
commit()
changes to the database are made permanent;
auto-commit mode is turned on
returns TRUE on success or FALSE on failure
throws an exception if no transaction is active
rollBack()
discard changes to the database; auto-commit mode is restored
returns TRUE on success or FALSE on failure
throws an exception if no transaction is active
COMP284 Scripting Languages Lecture 8 Slide L8 28
The PDO Class Transactions
Transactions: Example (Part 1)
We want to transfer £10.50 from one account at a bank to another,
but only if the payer has enough money
Either both subtracting the money from one account and adding it to
another should be successful or neither
$b al an ce = array ();
// sto re Ba la nc e ( $id , $b )
// $id: account id
// $b : balanc e for the accoun t with id $id
// maps $id to $b in the array $balance
fu nc ti on st or eBalance ( $id ,$b ) {
gl obal $ ba la nc e ;
$b al an ce [$id ] = $b ;
}
$pdo = new PDO ( ' mysql : host =.. .; db name =... ' ,' ... ' , ' ... ',
array(PDO :: A TT R_ ER RM ODE => PDO :: ERRMO DE _E XC EPTION ,
PDO :: AT TR _EMUL AT E_PRE PA RES => fals e ));
try {
// Deta il s of the tran sa ct io n : payer , payee , am ount
$p ay er Id = 1; $p ay ee Id = 2; $p ay mentAmo un t = 10. 50;
COMP284 Scripting Languages Lecture 8 Slide L8 29
The PDO Class Transactions
Transactions: Example (Part 2)
$pdo - > b eginTra ns action ();
// Obta in p ayee 's and payer ' s a ccount b al an ces
// and lock access to both records
$s ql1 = " select id , bala nce from accounts where id =? or id =? for upda te ";
$s tmt = $pdo - > prep ar e ( $ sql 1 );
$stmt -> ex ecute ( array( $payerId , $ payeeId ));
// St ore the data retrieved from the database in $ balance ar ray
$stmt -> fe tc hAll ( PDO :: FETCH _FUNC , ' store Ba la nc e ');
// Ch eck wh ether there is e nough money in the payer 's accoun t
if ( $b alance [ $p ayerId ] < $ payment Am ount ) {
echo " In sufficient fu nds in pay er 's ac count ";
} else {
$sql = " UPDAT E accounts SET balance = ba lance + ? WHERE id = ? ";
$s tmt = $pdo - > prep ar e ( $ sql );
// Increase ba la nce of payee 's acco un t by pa ym ent ammo unt
$stmt -> ex ecute ( array( $p aymentAmo un t , $p ay ee Id ));
// Decrease ba la nce of payer 's acco un t by pa ym ent ammo unt
$stmt -> ex ecute ( array(- $paym en tAmount , $payerId ));
}
COMP284 Scripting Languages Lecture 8 Slide L8 30
The PDO Class Transactions
Transactions: Example (Part 3)
// Comm it the transaction ( whether mone y was tr an sf er re d or not)
$pdo - > commit ();
} cat ch ( PDO Ex ce pt io n $e ) {
// Something went wro ng at some p oint
echo " Error : ",$e - > g et Me ss ag e () , " <br >\ n";
// Roll ba ck the tr an sa ction
$pdo - > r ol lBack ();
}
COMP284 Scripting Languages Lecture 8 Slide L8 31
The PDO Class Transactions
Revision
Read
Language Reference: Classes and Objects
http://php.net/manual/en/language.oop5.php
The PDO Class
http://php.net/manual/en/class.pdo.php
of M. Achour, F. Betz, A. Dovgal, et al: PHP Manual. The PHP Group,
2017. http://uk.php.net/manual/en [accessed 07 Dec 2017]
COMP284 Scripting Languages Lecture 8 Slide L8 32
COMP284 Scripting Languages
Lecture 9: JavaScript (Part 1)
Handouts
Ullrich Hustadt
Department of Computer Science
School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
27 JavaScript
Motivation
Overview
Example
28 Types and Variables
Numbers
Booleans
Strings
Variables
Typecasting
Comparisons
COMP284 Scripting Languages Lecture 9 Slide L9 1
JavaScript Motivation
JavaScript: Motivation
PHP allows us to create dynamic web pages
In web applications, PHP code is executed on the web server
(server-side scripting)
allows to use a website template that is instantiated using data stored in a
database
‘business logic’ is hidden from the user:
the code of an application is not visible to the user/client;
the user/client only has access to the HTML produced by the code
not ideal for interactive web applications:
too slow to react and too much data needs to be transferred
operations that refer to the location of the user/client are difficult,
for example, displaying the local time
echo date ('H:i l , j F Y ');
displays the local time on the server not the local time for the user
COMP284 Scripting Languages Lecture 9 Slide L9 2
JavaScript Overview
JavaScript
JavaScript is a language for client-side scripting
script code is embedded in a web page (as for PHP),
but delivered to the client as part of the web page and
executed by the user’s web browser
; code is visible to the user/client
allows for better interactivity as reaction time is improved and
data exchange with the server can be minimised
a web browser may not support JavaScript or
the user may have disallowed the execution of JavaScript code
different JavaScript engines may lead to different results, in particular,
results not anticipated by the developer of JavaScript code
performance relies on the efficiency of the JavaScript engine and
the client’s computing power (not the server’s)
operations that refer to the location of the client are easy:
document . write (" Local time : " + ( new Date ). to String ());
COMP284 Scripting Languages Lecture 9 Slide L9 3
JavaScript Overview
JavaScript: History
originally developed by Brendan Eich at Netscape
under the name Mocha
first shipped together with Netscape browser in September 1995
under the name LiveScript
obtained its current name in December 1995 under a deal between
Netscape and Sun Microsystems, the company behind Java,
in December 1995
does not have a particularly close relationship to Java,
it mixes aspects of Java with aspects of PHP and Perl
and its own peculiarities
is a dialect of ECMAScript, a scripting language standardised in the
ECMA-262 specification and ISO/IEC 16262 standard since June 1997
other dialects include Microsoft’s JScript and TypeScript and
Adobe’s ActionScript
COMP284 Scripting Languages Lecture 9 Slide L9 4
JavaScript Overview
Websites and Programming Languages
Website Client-Side Server-Side Database
Google JavaScript,
TypeScript
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 MariaDB
Twitter JavaScript C
++
, Java, Scala,
Ruby
MySQL
Bing JavaScript C
++
, C# MS SQL Server
Wikipedia Contributors: Programming languages used in most popular websites. Wikipedia, The Free Encyclopedia,
11 December 2019, at 16:24. https://en.wikipedia.org/wiki/Programming_languages_used_in_most_popular_websites
[accessed 21 December 2019]
COMP284 Scripting Languages Lecture 9 Slide L9 5
JavaScript Example
JavaScript: Hello World!
<! DOCTYP E html >
< html lang = 'en - GB ' ><head > < title > Hello World </ title > </ head >
<body >
<p > Our first Java Scrip t script </p>
<script >
document . writeln (" <p><b> Hello World ! </ b > </ p >")
</ script >
< noscript > JavaScript not s uppo rted or disabled </ noscript >
</ body > </ html >
JavaScript code is enclosed between <script> and </script>
Alternative HTML markup that is to be used in case JavaScript is not
enabled or supported by the web browser, can be specified between
<noscript> and </noscript>
File must be stored in a directory accessible by the web server, for
example $HOME/public_html, and be readable by the web server
No particular file name extension is required
COMP284 Scripting Languages Lecture 9 Slide L9 6
JavaScript Example
JavaScript scripts
JavaScript scripts are embedded into HTML documents and are
enclosed between <script> and </script> tags
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 semi-colon 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
COMP284 Scripting Languages Lecture 9 Slide L9 7
Types and Variables
Types
JavaScript is a dynamically and loosely typed language
like PHP
JavaScript distinguished five main types:
boolean booleans
number integers and floating-point numbers
string strings
function functions
object objects (including arrays)
JavaScript distinguishes between these five types including between the
three primitive types boolean, number and string
Every value is of a particular type
Integers, floating-point numbers, and strings do not differ significantly
from the corresponding PHP types
COMP284 Scripting Languages Lecture 9 Slide L9 8
Types and Variables 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
The Math object provides a wide range of mathematical functions
Math.abs(number) absolute value
Math.ceil(number) round fractions up
Math.floor(number) round fractions down
Math.round(number) round fractions
Math.log(number) natural logarithm
Math.random() random number between 0 and 1
Math.sqrt(number) square root
There are also some pre-defined number constants including
Math.PI (case sensitive) 3.14159265358979323846
NaN (case sensitive) ‘not a number’
Infinity (case sensitive) ‘infinity’
COMP284 Scripting Languages Lecture 9 Slide L9 9
Types and Variables Numbers
Numbers: NaN and Infinity
The constants NaN and Infinity are used as return values for
applications of mathematical functions that do not return a number
Math.log(0) returns -Infinity (negative ‘infinity’)
Math.sqrt(-1)returns NaN (‘not a number’)
1/0 returns Infinity (positive ‘infinity’)
0/0 returns NaN (‘not a number’)
In contrast to PHP, none of these operations causes a warning or error
JavaScript provides two functions to test whether a value is or is not
NaN, Infinity or -Infinity:
bool isNaN(value)
returns TRUE iff value is NaN
bool isFinite(value)
returns TRUE iff value is neither NaN nor Infinity/-Infinity
There is no isInfinite function
COMP284 Scripting Languages Lecture 9 Slide L9 10
Types and Variables Booleans
Booleans
JavaScript has a boolean datatype
with constants true and false (case sensitive)
JavaScript offers the same short-circuit boolean operators
as Java, Perl and PHP:
&& (conjunction) || (disjunction) ! (negation)
But and and or cannot be used instead of && and ||, respectively
The truth tables for these operators are the same as for Perl and PHP,
taking into account that the conversion of non-boolean values to
boolean values differs
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)
COMP284 Scripting Languages Lecture 9 Slide L9 11
Types and Variables Strings
Strings
JavaScript supports both single-quoted and double-quoted strings
JavaScript uses + for string concatenation
Within double-quoted strings JavaScript supports the following
escape characters
\b (backspace) \f (form feed) \n (newline)
\r (carriage return) \t (tab) \ (backslash)
\' (single quote) \" (double quote)
JavaScript does not support variable interpolation
JavaScript also does not support heredocs,
but multi-line strings are possible
document . writeln (" Your name is " + name + " and \
you are s tudy ing " + degree + "\
at " + unive rsity );
In contrast to PHP we cannot omit the escape characters at the end of
each line
COMP284 Scripting Languages Lecture 9 Slide L9 12
Types and Variables Variables
Variables
JavaScript variable names do not start with a particular character
A JavaScript variable name may consist of letters, digits, the $ symbol,
and underscore, but cannot start with a digit
; you can still stick to the PHP ‘convention’ that
variable names start with a $ symbol
JavaScript variable names are case sensitive
COMP284 Scripting Languages Lecture 9 Slide L9 13
Types and Variables Variables
Variables
Variables can be declared using one of the following statements:
var variable1 , variable2 , ...
var vari able1 = value1 , varia ble2 = value2 , ...
The second statement also initialises the variables
Used inside a function definition, a declaration creates a local variable
(only accessible within the function)
Used outside a function definition, a declaration creates a global variable
A variable can be initialised without a declaration
by assigning a value to it:
variable = value
Both inside and outside a function definition,
initialising an undeclared variable creates a global variable
Note: A declaration does not specify the type of a variable
only assigning a value of a certain type gives a variable a type
COMP284 Scripting Languages Lecture 9 Slide L9 14
Types and Variables Variables
Variables
In JavaScript, the use of the value of a variable that is neither declared
nor initialised will result in a reference error and script execution stops
A declared but uninitialised variable has the default value undefined
and has no specific type
JavaScript automatically converts a value to the appropriate type as
required by the operation applied to the value (type coercion)
The value undefined is converted as follows:
Type Default Type Default Type Default
bool false string 'undefined' number NaN
undefine d || true // result is true
undefine d + " -!" // result is " undefined -!"
undefine d + 1 // result is NaN
COMP284 Scripting Languages Lecture 9 Slide L9 15
Types and Variables Variables
Assignments
JavaScript uses the equality sign = for assignments
stud ent_i d = 2008 46369 ;
As in PHP and Perl, 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)
COMP284 Scripting Languages Lecture 9 Slide L9 16
Types and Variables Variables
Constants
JavaScript allows the definition of constants using
const v ariable1 = value1 , vari able2 = 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;
col umns ++; // type error
However, this construct is not supported by MS Internet Explorer 6–10
and does not have the desired effect in Safari before version 5.1.7
nor Opera before version 12
COMP284 Scripting Languages Lecture 9 Slide L9 17
Types and Variables Variables
Values, Variables and Types
string typeof value
returns a string representation of the type of value
Boolean "boolean" Number "number"
String "string" Object "object"
undefined "undefined" null "object"
NaN "number" Infinity "number"
Future versions of JavaScript may have an option to change
typeof null to "null" (as in PHP)
document . writeln (" Type of 23.0: " + typeof (23.0)
Type of 23.0: num ber
document . writeln (" Type of \"2 3\": " + typ eof ( " 23 " )
Type of " 23": string <br >
var a
document . writeln (" Type of a: " + typ eof ( a ) + " <br >"
Type of a: undefined <br >
COMP284 Scripting Languages Lecture 9 Slide L9 18
Types and Variables Typecasting
Typecasting
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
COMP284 Scripting Languages Lecture 9 Slide L9 19
Types and Variables Typecasting
Typecasting
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
COMP284 Scripting Languages Lecture 9 Slide L9 20
Types and Variables Typecasting
Type conversion to boolean
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
COMP284 Scripting Languages Lecture 9 Slide L9 21
Types and Variables Typecasting
Typer conversion to string
When converting to a string:
NaN converts to 'NaN'
Infinity converts to 'Infinity'
true converts to 'true'
false converts to 'false'
null converts to 'null'
undefined converts to 'undefined'
; in JavaScript it is easier to print out boolean values than in PHP
COMP284 Scripting Languages Lecture 9 Slide L9 22
Types and Variables Comparisons
Comparison operators
JavaScript distinguishes between (loose) equality ==
and strict equality ===:
in the same way as PHP:
expr1 == expr2 Equal TRUE iff expr1 is equal to expr2
after type coercion
expr1 != expr2 Not equal TRUE iff expr1 is not equal to expr2
after type coercion
When comparing a number and a string,
the string is converted to a number
When comparing with a boolean,
the boolean is converted to 1 if true and to 0 if false
If an object is compared with a number or string, JavaScript uses the
valueOf and toString methods of the objects to produce a primitive
value for the object
If two objects are compared,
then the equality test is true only if both refer to the same object
COMP284 Scripting Languages Lecture 9 Slide L9 23
Types and Variables Comparisons
Comparison operators
JavaScript distinguishes between (loose) equality ==
and strict equality ===:
in the same way as PHP:
expr1 === expr2 Strictly equal TRUE iff expr1 is equal to expr2,
and they are of the same type
expr1 !== expr2 Strictly not
equal
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
COMP284 Scripting Languages Lecture 9 Slide L9 24
Types and Variables Comparisons
Comparison operators
JavaScript’s comparison operators also applies type coercion to their
operands and do so following the same rules as equality ==:
expr1 < expr2 Less than true iff expr1 is strictly less than expr2
after type coercion
expr1 > expr2 Greater than true iff expr1 is strictly greater than expr2
after type coercion
expr1 <= expr2 Less than
or equal to
true iff expr1 is less than or equal to expr2
after type coercion
expr1 >= expr2 Greater than
or equal to
true 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
COMP284 Scripting Languages Lecture 9 Slide L9 25
Types and Variables Comparisons
Equality and comparison operators on Infinity and NaN
Equality and comparison operators produce the following results
for Infinity and NaN:
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
COMP284 Scripting Languages Lecture 9 Slide L9 26
Types and Variables Comparisons
Equality and program behaviour
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 " );
5 is true and 5 is equal to true
JavaScript:
if (5) docu ment . wri teln ("5 is true " );
else d ocument . writeln ( " 5 is not true " )
document . writeln (" and " )
if (5 == true ) d ocum ent . writ eln ( " 5 is equal to true ")
else d ocument . writeln ( " 5 is not equal to true ")
5 is true and 5 is not equal to true
COMP284 Scripting Languages Lecture 9 Slide L9 27
Types and Variables Comparisons
Equality and program behaviour
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:
$ar ray3 = array ( " 1.23 e2 " ,5);
$ar ray4 = array ( " 12.3 e1 " ,true );
if (( $array 3 [0] == $ array4 [0]) && ( $array3 [1] == $ arr ay4 [1]))
print ( " The two arrays are equal " );
else print ("The two arrays are not equal " );
The two arra ys are equal
JavaScript:
$ar ray3 = [" 1.23 e2" ,5]
$ar ray4 = [" 12.3 e1", true ]
if (( $array 3 [0] == $ array4 [0]) && ( $array3 [1] == $ arr ay4 [1]))
document . writeln (" The two arra ys are equal ")
else d ocument . writeln ( " The two arrays are not equal " )
The two arra ys are not equal
COMP284 Scripting Languages Lecture 9 Slide L9 28
Types and Variables Comparisons
Equality
Note: The way in which more complex data structures are compared
also differs between PHP and JavaScript
PHP:
$ar ray3 = array ( " 1.23 e2 " ,5);
$ar ray4 = array ( " 12.3 e1 " ,true );
if ( $array3 == $ array4 )
print ( " The two arrays are equal " );
else print ("The two arrays are not equal " );
The two arra ys are equal
JavaScript:
$ar ray3 = [" 1.23 e2" ,5]
$ar ray5 = [" 1.23 e2" ,5]
if ( $array3 == $ array5 )
document . writeln (" The two arrays are equal ")
else d ocument . writeln ( " The two arr ays are not equal ")
The two arra ys are not equal
COMP284 Scripting Languages Lecture 9 Slide L9 29
Revision
Revision
Read
Chapter 13: Exploring JavaScript
of
R. Nixon:
Learning PHP, MySQL, and JavaScript.
O’Reilly, 2019.
COMP284 Scripting Languages Lecture 9 Slide L9 30
COMP284 Scripting Languages
Lecture 10: JavaScript (Part 2)
Handouts
Ullrich Hustadt
Department of Computer Science
School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
29 Control structures
Blocks
Conditional statements
Switch statements
While- and Do While-loops
For-loops
Try, throw, catch, finally statements
Variable Declarations Revisited
30 Arrays
Definition
forEach-method
Array functions
COMP284 Scripting Languages Lecture 10 Slide L10 1
Control structures
Control structures
JavaScript control structures
block statements
conditional statements
switch statements
while- and do while-loops
for-loops
try, throw, catch finally statements
are syntactically identical to those of Java
COMP284 Scripting Languages Lecture 10 Slide L10 2
Control structures Blocks
Control structures: block statements
A block statement is a sequence of zero or more statements delimited
by a pair of curly brackets
{
stat ement s
}
It allows to use multiple statements where JavaScript expects only one
statement
{
var x = 1
var y = x ++
}
COMP284 Scripting Languages Lecture 10 Slide L10 3
Control structures Conditional statements
Control structures: conditional statements
Conditional statements take the following form in JavaScript:
if ( con dition )
statemen t
else if ( conditio n )
statemen t
else
statemen t
There are no elsif- or elseif-clauses in JavaScript
The else-clause is optional but there can be at most one
Each statement can be a block statement
JavaScript also supports conditional expressions
conditio n ? if_tr ue_exp r : if_fa l se_exp r
COMP284 Scripting Languages Lecture 10 Slide L10 4
Control structures Switch statements
Control structures: switch statement
Switch statements in JavaScript take the same form as in PHP:
switch ( expr ) {
case expr1 :
stat ement s
break ;
case expr2 :
stat ement s
break ;
def ault :
stat ement s
break ;
}
there can be arbitrarily many case-clauses
the default-clause is optional but there can be
at most one
expr is evaluated only once and then compared
to expr1, expr2, etc using (loose) equality ==
once two expressions are found to be equal the
corresponing 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
COMP284 Scripting Languages Lecture 10 Slide L10 5
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 ;
def ault :
days = 0;
break ;
}
COMP284 Scripting Languages Lecture 10 Slide L10 6
Control structures While- and Do While-loops
Control structures: while- and do while-loops
JavaScript offers while-loops and do while-loops
while ( cond ition )
statemen t
do
statemen t
while ( cond ition )
Example:
// Comp ute the f actorial of a given num ber
var fact orial = 1;
do {
factoria l *= number --
} while ( number > 0)
COMP284 Scripting Languages Lecture 10 Slide L10 7
Control structures For-loops
Control structures: for-loops
for-loops in JavaScript take the form
for ( i nitial isatio n ; test ; incr ement )
statemen t
var fact orial = 1
for ( var i = 1; i <= number ; i ++)
factoria l *= i
A for-loop is equivalent to the following while-loop:
initi alisat ion
while ( test ) {
statemen t
incremen t
}
for ( var fact orial = 1; number ; number - -)
factoria l *= number
COMP284 Scripting Languages Lecture 10 Slide L10 8
Control structures For-loops
Control structures: for-loops
In JavaScript, initialisation and increment can consist of more
than one statement, separated by commas instead of semicolons
for ( i = 1 , j = 1; j >= 0; i ++, j - -)
document . writeln (i + " * " + j + " = " + i * j )
// Indent ation has no ` meaning ' in JavaScript ,
// the next line is not part of the loop !! BAD STYLE !!
document . writeln (" Outsid e loop : i = " + i + " j = " + j )
1 * 1 = 1
2 * 0 = 0
Out side loop : i = 3 | j = -1
Note: Variables declared with var inside a for-loop are still visible
outside
for ( var i = 0; i < 1; i ++)
document . writeln (" In side loop : i = " + i )
document . writeln (" Outsid e loop : i = " + i )
Inside loop : i = 0
Out side loop : i = 1
COMP284 Scripting Languages Lecture 10 Slide L10 9
Control structures For-loops
Control structures: break and continue
The break command can also be used in while-, do while-, and for-loops
and discontinues the execution of the loop
while ( value < 100) {
if ( value == 0) break ;
value ++
}
The continue command stops the execution of the current iteration of a
loop and moves the execution to the next iteration
for ( x = -2; x <= 2; x ++) {
if (x == 0) continue ;
document . writeln (" 10 / " + x + " = " + (10/ x ));
}
10 / -2 = -5
10 / -1 = -10
10 / 1 = 10
10 / 2 = 5
COMP284 Scripting Languages Lecture 10 Slide L10 10
Control structures Try, throw, catch, finally statements
Error handling
When a JavaScript statement generates an error, an exception is thrown
Exceptions can also explicitly be thrown via a throw statement
A try ... catch ... statement allows for error / exception handling
try { stat ements }
catch ( error) { statements }
fin ally { state ments }
Statements in the try block are executed first
If any statement within the try block throws an exception, control
immediately shifts to the catch block
error is a variable used to store the error / exception
Statements in the finally block are executed after try and catch
statements, regardless of whether an exception was thrown or caught
Curly brackets are necessary even where a block consists of only one
statement
COMP284 Scripting Languages Lecture 10 Slide L10 11
Control structures Try, throw, catch, finally statements
Error handling
When a JavaScript statement generates an error, an exception is thrown
Exceptions can also explicitly be thrown via a throw statement
A try ... catch ... statement allows for error / exception handling
throw e xpres sion
A throw statement throws (generates) an exception and interrupts the
normal flow of control
The exception expression can be a string, a number, a boolean or an
object
try ... catch ... statements can be nested
COMP284 Scripting Languages Lecture 10 Slide L10 12
Control structures Try, throw, catch, finally statements
Error handling: Example
x = "A"
try {
if ( isNaN (x)) throw " x is NaN "
y = x. toFixed (2)
} catch ( e ) {
document . writeln ( ' Ca ught : ' + e)
y = 0
} finally {
document . writeln ( ' y = ' ,y)
}
Caught TypeError : x . toF ixed is not a f unction
y = 0
COMP284 Scripting Languages Lecture 10 Slide L10 13
Control structures Variable Declarations Revisited
Variable Declarations Revisited
Variables can be declared (within a scope) using one of the following
statements:
var variable1 , variable2 , ...
var vari able1 = value1 , varia ble2 = value2 , ...
The second statement also initialises the variables
Used inside a function definition, creates a local variable, only accessible
within the function
Used outside a function definition, creates a global variable
A variable can be defined without an explicit declaration
by assigning a value to it:
variable = value
Always creates a global variable
COMP284 Scripting Languages Lecture 10 Slide L10 14
Control structures Variable Declarations Revisited
Variable Declarations Revisited
Variables can be declared (within a block context) using one of the
following statements:
let variable1 , variable2 , ...
let vari able1 = value1 , varia ble2 = value2 , ...
The second statement also initialises the variables
Used inside a block, creates a local variable, only accessible within the block
Used outside any block, creates a global variable
for ( var i =0; i <1; i ++) {
var j = i + 1
console .log ('I : i =',i,'j = ' ,j)
}
console .log ('O : i =',i,'j = ' ,j )
I: i = 0 j = 1
O: i = 1 j = 1
for ( let i =0; i <1; i ++) {
let j = i + 1
console .log ('I : i =',i,'j = ' ,j )
}
console .log ('O : i =',i,'j = ' ,j)
I: i = 0 j = 1
Refer enc eErro r : i is not defined
Refer enc eErro r : j is not defined
COMP284 Scripting Languages Lecture 10 Slide L10 15
Control structures Variable Declarations Revisited
Variable Declarations Revisited
Variables can be declared (within a block context) using one of the
following statements:
let variable1 , variable2 , ...
let vari able1 = value1 , varia ble2 = value2 , ...
Variable declarations using let are not hoisted
var m yV ar 1
console .log (" myVar1 = " , myVar1 )
console .log (" myVar2 = " , myVar2 )
var m yV ar 2
my Va r1 = un de fined
my Va r2 = un de fined
let m yV ar 1
console .log (" myVar1 = " , myVar1 )
console .log (" myVar2 = " , myVar2 )
let m yV ar 2
my Va r1 = un de fined
Refer enc eErro r : myVar2 is not de fi ned
COMP284 Scripting Languages Lecture 10 Slide L10 16
Arrays Definition
Arrays
An array is created by assigning an array value to a variable
var arrayVar = []
var arrayVar = [ elem0 , elem1 , ... ]
JavaScript uses
arrayVar [ index ]
to denote the element stored at position index in arrayVar
The first array element has index 0
Arrays have no fixed length and it is always possible to add more
elements to an array
Accessing an element of an array that has not been assigned a value yet
returns undefined
For an array arrayVar, arrayVar.length returns the maximal index
index such that arrayVar[index] has been assigned a value
(including the value undefined) plus one
COMP284 Scripting Languages Lecture 10 Slide L10 17
Arrays Definition
Arrays
It is possible to assign a value to arrayVar.length
if the assigned value is greater than the previous value of arrayVar.length,
then the array is ‘extended’ by additional undefined elements
if the assigned value is smaller than the previous value of arrayVar.length,
then array elements with greater or equal index will be deleted
Assigning an array to a new variable creates a reference to the
original array
; changes to the new variable affect the original array
Arrays are also passed to functions by reference
The slice function can be used to create a proper copy of an array:
object arrayVar.slice(start, end)
returns a copy of those elements of array variable that have indices
between start and end
COMP284 Scripting Languages Lecture 10 Slide L10 18
Arrays Definition
Arrays: Example
var array1 = ['hello', [1, 2], function() {return 5}, 43]
document.writeln("1: array1.length = "+array1.length)
1: array1.length = 4
document.writeln("2: array1[3] ="+array1[3])
2: array1[3] = 43
array1[5] = 'world'
document.writeln("3: array1.length = "+array1.length)
3: array1.length = 6
document.writeln("4: array1[4] ="+array1[4])
4: array1[4] = undefined
document.writeln("5: array1[5] ="+array1[5])
5: array1[5] = world
array1.length = 4
document.writeln("6: array1[5] ="+array1[5])
6: array1[5] = undefined
var array2 = array1
array2[3] = 7
document.writeln("7: array1[3] ="+array1[3])
7: array1[3] = 7
COMP284 Scripting Languages Lecture 10 Slide L10 19
Arrays forEach-method
forEach-method
The recommended way to iterate over all elements of an array is a
for-loop
for ( index = 0; index < arrayVar . length ; index ++) {
... arrayVar [ index] ...
}
An alternative is the use of the forEach method:
var callback = func tion ( elem , index , a rrayArg ) {
stat ement s
}
array . for Each ( cal lback );
The forEach method takes a function as an argument
It iterates over all indices/elements of an array
It passes the current array element (elem), the current index (index) and
a pointer to the array (arrayArg) to the function
Return values of that function are ignored,
but the function may have side effecs
COMP284 Scripting Languages Lecture 10 Slide L10 20
Arrays forEach-method
forEach-method: Example
var myArray = [ ' Michel e Zito ' ,' Ullrich Hustadt '];
var rewri teName s = function ( elem , index , arr ) {
arr [ index ] = elem . replace (/(\ w +)\ s (\ w +)/ , " $2 , $1");
}
myA rray . forEach ( rewr iteNam es );
for ( i =0; i < myArray . length ; i ++) {
document . write ( ' [ ' +i+ ' ] = ' + myArray [i]+ " " );
}
[0] = Zito , Michele [1] = Hustadt , Ullrich
COMP284 Scripting Languages Lecture 10 Slide L10 21
Arrays Array functions
Array operators
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
Note: In contrast to PHP, array does not need to be a variable
COMP284 Scripting Languages Lecture 10 Slide L10 22
Arrays Array functions
Array operators: push, pop, shift, unshift
planets = ["earth"]
planets.unshift("mercury","venus")
planets.push("mars","jupiter","saturn");
document.writeln("planets\@1: "+planets.join(""))
planets@1: mercury venus earth mars jupiter saturn
last = planets.pop()
document.writeln("planets\@2: "+planets.join(""))
planets@2: mercury venus earth mars jupiter
first = planets.shift()
document.writeln("planets\@3: "+planets.join(""))
planets@3: venus earth mars jupiter
document.writeln(" \@4: "+first+""+last)
@4: mercury saturn
home = ["mercury","venus","earth"].pop()
document.writeln(" \@5: " + home)
@5: earth
number = ["earth"].push("mars");
document.writeln(" \@6: " + number)
@6: 2
COMP284 Scripting Languages Lecture 10 Slide L10 23
Revision
Revision
Read
Chapter 14: Expressions and Control Flow in JavaScript
Chapter 15: JavaScript Functions, Objects, and Arrays
of
R. Nixon:
Learning PHP, MySQL, and JavaScript.
O’Reilly, 2018.
COMP284 Scripting Languages Lecture 10 Slide L10 24
COMP284 Scripting Languages
Lecture 11: JavaScript (Part 3)
Handouts
Ullrich Hustadt
Department of Computer Science
School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
31 Functions
Defining a function
Calling a function
Variable-length argument lists
Static variables
Example
Nested function definitions
32 JavaScript libraries
33 (User-defined) Objects
Object Literals
Object Constructors
Definition and use
Prototype property
Public and private static variables
Pre-defined objects
COMP284 Scripting Languages Lecture 11 Slide L11 1
Functions Defining a function
Functions
Function definitions can take several different forms in JavaScript
including:
function iden tifier ( param1 , param2 , ...) {
stat ement s }
var identifier = func tion ( param1 , param2 , ...) {
stat ement s }
Such function definitions are best placed in the head section
of a HTML page or in a library that is then imported
Function names are case-sensitive
The function name must be followed by parentheses
A function has zero, one, or more parameters that are variables
Parameters are not typed
identifier.length can be used inside the body of the function to
determine the number of parameters
COMP284 Scripting Languages Lecture 11 Slide L11 2
Functions Defining a function
Functions
Function definitions can take several different forms in JavaScript
including:
function iden tifier ( param1 , param2 , ...) {
stat ement s }
var identifier = func tion ( param1 , param2 , ...) {
stat ement s }
The return statement
return value
can be used to terminate the execution of a function and to make
value the return value of the function
The return value does not have to be of a primitive type
A function can contain more than one return statement
Different return statements can return values of different types
; there is no return type for a function
COMP284 Scripting Languages Lecture 11 Slide L11 3
Functions Calling a function
Calling a function
A function is called by using the function name followed by a list of
arguments in parentheses
function iden tifier ( param1 , param2 , ...) {
...
}
... identifier ( arg1 , arg2 ,...) ... // Function call
The list of arguments can be shorter as well as longer as
the list of parameters
If it is shorter, then any parameter without corresponding argument
will have value undefined
function sum ( num1 , num2 ) { return num1 + num2 }
sum1 = sum (5 ,4) // sum1 = 9
sum2 = sum (5 ,4 ,3) // sum2 = 9
sum3 = sum (5) // sum3 = NaN
COMP284 Scripting Languages Lecture 11 Slide L11 4
Functions Calling a function
‘Default Values’ for Parameters
ECMAScript 2015 introduced default parameter values
function sum ( num1 = 0 , num2 = 0) { return num1 + num2 }
sum1 = sum (5 ,4) // sum1 = 9
sum2 = sum (5 ,4 ,3) // sum2 = 9
sum3 = sum (5) // sum3 = 5
In Internet Explorer or other older browsers, a function instead has to
check whether an argument has the value undefined and take
appropriate action
function sum ( num1 , num2 ) {
if ( num1 == unde fined ) num1 = 0
if ( num2 == unde fined ) num2 = 0
return num1 + num2
}
COMP284 Scripting Languages Lecture 11 Slide L11 5
Functions Calling a function
Functions as Arguments
JavaScript functions are objects and can be passed as arguments to other
functions
function apply (f,x,y) {
return f(x,y)
}
function mult (x ,y) {
return x * y
}
con sole . log( ' 2 * 3 = ' , apply ( mult ,2 ,3))
2 * 3 = 6
con sole . log( ' 2 + 3 = ' ,
apply ( function (a,b) { ret urn a + b },
2 ,3))
2 + 3 = 5
COMP284 Scripting Languages Lecture 11 Slide L11 6
Functions Variable-length argument lists
Variable-length argument lists
Every JavaScript function has a property called arguments
The arguments property consists of an array of all the arguments
passed to a function
As for any JavaScript array, arguments.length can be used to
determine the number of arguments
// Function that retu rns the sum of all its a rgum ents
function sumAll () { // no minimum number of argu ments
var sum = 0
for ( var i =0; i < argu ments . length ; i ++)
sum = sum + a rguments [ 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
COMP284 Scripting Languages Lecture 11 Slide L11 7
Functions Static variables
JavaScript functions and Static variables
JavaScript does not have a static keyword to declare a variable to be
static and preserve its value between different calls of a function
The solution is to use a function property instead
function cou nter () {
cou nter . count = counter . count || 0 // f unct ion prop erty
cou nter . count ++
return counter . count
}
document . writeln (" 1: sta tic count = "+ co unter ())
document . writeln (" 2: sta tic count = "+ co unter ())
document . writeln (" 3: glo bal counter . cou nt = " + counter . count)
1: static count = 1
2: static count = 2
3: global cou nter . count = 2
As the example shows the function property is global/public
Private static variables require more coding effort
COMP284 Scripting Languages Lecture 11 Slide L11 8
Functions Example
JavaScript functions: Example
function bubbl e_sor t ( array ) {
if (!( array && array . c onstr uctor == 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 chan ge array b ecause array is
// passed by r eference
swap ( array , j , j +1)
} } }
return array
}
function swap ( array , i , j ) {
var tmp = array [i]
array [ i ] = array [ j ]
array [ j ] = tmp
}
COMP284 Scripting Languages Lecture 11 Slide L11 9
Functions Example
JavaScript functions: Example
function bubbl e_sor t ( array ) { ... }
function swap ( array , i , j ) { ... }
array = [2 ,4 ,3 ,9 ,6 ,8 ,5 ,1]
document . writeln (" array before sorting "+
array . join (" , " ))
array before sor ting 2, 4 , 3 , 9 , 6, 8, 5, 1
sorted = bubble _sort ( array . slice (0)) // slice creates copy
document . writeln (" array after sorting of copy "+
array . join (" , " ))
array after sor ting of copy 2, 4, 3 , 9 , 6 , 8 , 5 , 1
sorted = bubble _sort ( array )
document . writeln (" array after sorting of itself " +
array . join (" , " ))
array after sor ting of its elf 1 , 2 , 3, 4, 5, 6, 8, 9
document . writeln (" so rted array "+
sorted . join ( " , " ))
sorted array 1, 2 , 3, 4, 5, 6, 8, 9
COMP284 Scripting Languages Lecture 11 Slide L11 10
Functions Nested function definitions
Nested function definitions
Function definitions can be nested in JavaScript
Inner functions have access to the variables of outer functions
By default, inner functions can not be invoked from outside
the function they are defined in
function bubbl e_sor t ( array ) {
function swap (i , j) {
// swap can chan ge array b ecause array is
// a local variable of the outer function bubb le_sort
var tmp = array [i]; array [ i ] = array [ j ]; array [ j ] = tmp ;
}
if (!( array && array . c onstr uctor == 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 }
COMP284 Scripting Languages Lecture 11 Slide L11 11
JavaScript libraries
JavaScript libraries
Collections of JavaScript functions (and other code), libraries, can be
stored in one or more files and then be reused
By convention, files containing a JavaScript library are given the file
name extension .js
<script>-tags are not allowed to occur in the file
A JavaScript library is imported using
< script src =" url " ></ script >
where url is the (relative or absolute) URL for library
< script src =" http :// st udent . csc . liv .ac .uk /
sguh / jsLib . js " >
</ script >
One such import statement is required for each library
Import statements are typically placed in the head section of a page or
at the end of the body section
Web browers typically cache libraries
COMP284 Scripting Languages Lecture 11 Slide L11 12
JavaScript libraries
JavaScript libraries: Example
~ullrich/public_html/sort.js
function bubbl e_sor t ( array ) {
... swap ( array , j , j +1) ...
return array
}
function swap ( array , i , j ) { ... }
example.html
<! DOCTYP E html >
< html lang = 'en - GB ' ><head > < title > Sorting example </ title >
< script src =" http :// st udent . csc . liv .ac .uk /
ull rich / sort. js" >
</ script > </ head >
<body >
< script type = " text / java scrip t " >
array = [2 ,4 ,3 ,9 ,6 ,8 ,5 ,1];
sorted = bubble _sort ( array . slice (0))
</ script >
</ body >
</ html >
COMP284 Scripting Languages Lecture 11 Slide L11 13
(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
{ membe rName1 : value1 , m emberN ame2 : value2 , ... }
where memberName1, memberName2, . . . are member names
and value1, value2, . . . are member values (expressions)
Terminology:
member value is function ; method
member value is some other value ; property
var person1 = {
age : (30 + 2) ,
gender : ' male ' ,
nme : { first : ' Ben ' , last : ' Budd ' } ,
interest s : [ ' music ' , ' skiing ' ],
he llo : funct ion () { retur n 'Hi ! I \ ' m ' + this . name . first + ' .' }
};
COMP284 Scripting Languages Lecture 11 Slide L11 14
(User-defined) Objects Object Literals
Object Literals
Member values can be accessed using dot notation or bracket notation
var person1 = {
age : (30 + 2) ,
gender : ' male ' ,
nme : { first : ' Ben ' , last : ' Budd ' } ,
interest s : [ ' music ' , ' skiing ' ],
he llo : funct ion () { retur n 'Hi ! I \ ' m ' + this .nme. first }
};
person1 . age --> 32 // dot notation
person1 [ ' gen der '] - -> ' male ' // bracket no tatio n
person1 . nme . first --> ' Ben '
person1 [ ' nme '][ ' last ' ] --> ' Budd '
COMP284 Scripting Languages Lecture 11 Slide L11 15
(User-defined) Objects Object Literals
Object Literals
var person1 = {
...
nme : { f irst : ' Ben ', last : ' Budd ' },
he llo : funct ion () { retur n 'Hi ! I \ ' m ' + this .nme. first }
};
person1 . hello () --> " Hi ! I ' m Ben "
person1 [ ' hello ' ]() --> " Hi ! I ' m Ben "
Every part of a JavaScript program is executed in a particular
execution context
Every execution context offers a keyword this as a way of referring to
itself
In person1.hello() the execution context of hello() is person1
; this.nme.first is person1.nme.first
COMP284 Scripting Languages Lecture 11 Slide L11 16
(User-defined) Objects Object Literals
Object Literals
var nme = { first : ' Adam ' , last : ' Alby ' }
var person1 = {
nme : { first : ' Ben ' , last : ' Budd ' },
hello : funct ion () { return ' I\' m ' + this . nme . first } ,
full1 : this .nme . first + " " + this . nme .last ,
full2 : nme . first + " " + nme . last ,
greet : funct ion () { return ' I\' m ' + nme . first }
}
con sole . log( ' hello = ' , person1 . hello ())
hello = I ' m Ben
document . writeln ( ' greet = ',person1 . greet ())
document . writeln ( ' full1 = ',person1 . full1)
document . writeln ( ' full1 = ',person1 . full2)
greet = I ' m Adam
full1 = Adam Alby
full2 = Adam Alby
COMP284 Scripting Languages Lecture 11 Slide L11 17
(User-defined) Objects Object Literals
Object Literals
var nme = { first : ' Adam ' , last : ' Alby ' }
var person1 = {
nme : { first : ' Ben ' , last : ' Budd ' },
hello : funct ion () { return ' I\' m ' + this . nme . first } ,
full1 : this .nme . first + " " + this . nme .last ,
full2 : nme . first + " " + nme . last ,
greet : funct ion () { return ' I\' m ' + nme . first }
}
In the construction of the object literal itself, this does not refer to
person1 but its execution context (the window object)
; none of nme.first, nme.last, this.nme.first, and
this.nme.last refers to properties of this object literal
In person1.greet() the execution context of greet() is person1
; but nme.first does not refer to person1.nme.first
Do not think of an object literal as a block of statements
(and of property-value pairs as assignments within that block)
COMP284 Scripting Languages Lecture 11 Slide L11 18
(User-defined) Objects Object Constructors
Objects 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 instance variables of the object
; each object will have its own copy of these variables
it is possible to make such variables private or public
inner functions will be methods of the object
it is possible to make such functions/methods private or public
private variables/methods can only be accessed inside the function
public variables/methods can be accessed outside the function
Whenever an object constructor is called,
prefixed with the keyword new, then
a new object is created
the function is executed with the keyword this bound to that object
COMP284 Scripting Languages Lecture 11 Slide L11 19
(User-defined) Objects Definition and use
Objects: Definition and Use
fu nct ion Som eOb j () {
this.prop1 = 'A ' // public pro per ty
var prop2 = ' B' // p riv ate pro per ty
// public method
this.method1 = function () {
// ( use of a) pu blic v ari abl e must be p rec ede d by ` this '
// ( use of a) pr iva te v ari abl e m ust NOT be pr ece ded by ` this '
return ' m1 [ prop1 =' + this . prop1 + ' pr op2 = ' + prop2 + ' ]' }
// private me thod
var m ethod2 = func tio n () {
return ' m2 [] ' }
// public method
this.method3 = function () {
// ( call of a) pub lic metho d m ust be preceded by ` this '
// ( call of a) privat e method mu st NOT be pr ece ded by ` this '
return ' m3 [' + this . met hod 1 () + ' ' + me tho d2 () + ' ]' }
}
obj1 = new SomeObj () // creates a new objec t
obj1.prop1 = ' A'
obj1.prop2 = undef ine d
obj1.method1 () = ' m1[ prop1 = A prop2 =B] '
obj1.method2 () --> Ty peE rro r : obj . method2 is not a fu nct ion
obj1.method3 () = ' m3[ m1 [ prop1 =A pro p2 =B ] m2 []] '
COMP284 Scripting Languages Lecture 11 Slide L11 20
(User-defined) Objects Definition and use
Objects: Definition and Use
fu nct ion Som eOb j () {
this.prop1 = 'A ' // public pro per ty
var prop2 = ' B' // p riv ate pro per ty
var that = t his
// private me thod
var m ethod4 = func tio n () {
// ( use of a) pu blic v ari abl e must be p rec ede d by ' that '
// ( use of a) pr iva te v ari abl e m ust NOT be pr ece ded by ' that '
return ' m4 [ prop1 =' + that . prop1 + ' pr op2 = ' + prop2 + ' ]' }
// private me thod
var m ethod6 = func tio n () {
// ( call of a) pub lic metho d m ust be preceded by ' that '
// ( call of a) privat e method mu st NOT be pr ece ded by ' that '
return ' m6 [' + that . met hod 1 () + ' ' + me tho d4 () + ' ]' }
this.method5 { re turn m eth od4 () }
this.method7 { re turn m eth od6 () }
}
obj1 = new SomeObj () // creates a new objec t
obj1.method5 () = m4 [prop 1 =A p rop2 = B]
obj1.method7 () = m6 [m1 [ pr op1 = A pro p2 =B ] m4 [ prop1 =A pro p2 =B ]]
COMP284 Scripting Languages Lecture 11 Slide L11 21
(User-defined) Objects Definition and use
Objects: Definition and Use
fu nct ion Som eOb j () {
this.prop1 = 'A ' // public pro per ty
var prop2 = ' B' // p riv ate pro per ty
this.method1 = function () { // pu bli c m eth od
return ' m1 [ prop1 =' + this . prop1 + ' pr op2 = ' + prop2 + ' ]' }
var me tho d2 = fu nct ion () { ... } // private m ethod
}
obj1 = new SomeObj ()
obj2 = new SomeObj ()
co nsole . log ( ' obj1 . me tho d3 () = ' ,o bj1 . me tho d3 ())
obj1.method3 () = m3 [m1 [ pr op1 = A pro p2 =B ] m2 []]
obj1.method1 = function () { retur n ' mo dified ' }
obj2.prop1 = ' C'
co nsole . log ( ' obj1 . metho d3 () = ' ,o bj1 . me tho d3 ())
co nsole . log ( ' obj2 . metho d3 () = ' ,o bj2 . me tho d3 ())
obj1.method3 () = m3 [ mod ifi ed m2 []]
obj2.method3 () = m3 [m1 [ pr op1 = C pro p2 =B ] m2 []]
prop1, prop2, method1 to method2 are all members
(instance variables) of SomeObj
The only difference is that prop1 and prop2 store strings while
method1 and method2 store functions
; every object stores its own copy of the methods
COMP284 Scripting Languages Lecture 11 Slide L11 22
(User-defined) Objects Prototype property
Objects: Prototype property
All functions have a prototype property that can hold
shared object properties and methods
; objects do not store their own copies of these properties and
methods but only store references to a single copy
function Som eObj () {
this . prop1 = 'A' // public property
var prop2 = 'B' // priv ate p roperty
Som eObj . prototyp e . method1 = function () { ... } // public
Som eObj . prototyp e . method3 = function () { ... } // public
var method2 = func tion () { ... } // private method
var method4 = func tion () { ... } // private method
}
Note: prototype properties and methods are always public!
COMP284 Scripting Languages Lecture 11 Slide L11 23
(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
fu nc tion SomeOb j () { ... }
obj1 = new Some Ob j ()
obj2 = new Some Ob j ()
do cu ment . wri teln ( o bj1 . pro p3 )
do cu ment . wri teln ( o bj2 . pro p3 )
So meObj. pr ot ot ype . pr op3 = ' A'
do cu ment . wri teln ( ' obj1 . prop 3 = ' ,obj1. prop3 )
do cu ment . wri teln ( ' obj2 . prop 3 = ' ,obj2. prop3 )
So meObj. pr ot ot ype . pr op3 = ' B'
do cu ment . wri teln ( ' obj1 . prop 3 = ' ,obj1. prop3 )
do cu ment . wri teln ( ' obj2 . prop 3 = ' ,obj2. prop3 )
obj1 . prop3 = ' C' // create s a new p roperty for obj1
So meObj. pr ot ot ype . pr op3 = ' D'
do cu ment . wri teln ( ' obj1 . prop 3 = ', ob j1 . prop3 )
do cu ment . wri teln ( ' obj2 . prop 3 = ', ob j2 . prop3 )
un defined
un defined
'A '
'A '
'B '
'B '
'C '
'D '
COMP284 Scripting Languages Lecture 11 Slide L11 24
(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
fun ction S omeObj () { ... }
obj1 = new SomeOb j ()
obj2 = new SomeOb j ()
SomeOb j . prototype . prop4 = 'E'
SomeOb j . prototype . setProp4 = fun ction ( arg ) {
this . prop4 = arg
}
obj1 . setPro p4 ( 'E')
obj2 . setPro p4 ( 'F')
doc ument . writ eln ( ' obj1 . prop4 = ',obj1. prop4 )
doc ument . writ eln ( ' obj2 . prop4 = ',obj2. prop4 )
E
F
COMP284 Scripting Languages Lecture 11 Slide L11 25
(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 instances) and class methods
fu nction Ci rcl e ( radius ) { this . r = rad ius }
// ` class varia ble ' - prop er ty of the Cir cle const ru ct or f uncti on
Ci rcle . PI = 3 .1415 9
// ` i nstance m ethod '
Ci rcle . protot yp e . area = fun ct ion () {
re turn Circle .PI * this.r * this . r; }
// ` class met hod ' - p roperty of the Circl e co nstructor fun ct ion
Ci rcle . max = func tion ( cx , cy ) {
if ( cx .r > cy .r) { retu rn cx } else { return cy }
}
c1 = new Circ le (1.0) // cr eate an inst an ce of the Cir cle c las s
c1 .r = 2.2; // set the r insta nce varia ble
c1 _area = c1 . are a (); // inv oke the area () i nstan ce meth od
x = Math . exp( Circle .PI) // use the PI class va riabl e in a co mputation
c2 = new Circ le (1.2) // cr eate anoth er Circ le inst ance
bi gger = Circl e . max ( c1 , c2 ) // use the max () c las s met hod
COMP284 Scripting Languages Lecture 11 Slide L11 26
(User-defined) Objects Public and private static variables
Private static variables
In order to create private static variables shared between objects
we can use a self-executing anonymous function
var Perso n = ( f uncti on () {
var popu lation = 0 // pri vate sta tic ` class ' v ariab le
retur n fun ction ( val ue ) { // co ns tructor
po pu latio n ++
var nam e = va lue // priva te pr opert y
this . se tName = funct ion ( value ) { name = value }
this . ge tName = funct ion () { return name }
this . getPo p = func tion () { r etu rn po pu lation }
}
}())
pe rson1 = new Pe rson ( ' Pet er ' )
pe rson2 = new Pe rson ( ' Jam es ' )
do cumen t . writeln ( p erson 1 . ge tName () )
do cumen t . writeln ( p erson 2 . ge tName () )
do cumen t . writeln ( p erson 1 . name )
do cumen t . writeln ( P erson . pop ul ation || per son1 . p opula ti on )
do cumen t . writeln ( p erson 1 . ge tPo p () )
pe rson1 . set Name ( ' David ')
do cumen t . writeln ( p erson 1 . ge tName () )
Peter
James
un defined
un defined
2
David
COMP284 Scripting Languages Lecture 11 Slide L11 27
(User-defined) Objects Pre-defined objects
Pre-defined objects: String
JavaScript has a collection of pre-defined objects,
including Array, String, Date
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
COMP284 Scripting Languages Lecture 11 Slide L11 28
(User-defined) Objects Pre-defined objects
Pre-defined objects: String and RegExp
JavaScript supports (Perl-like) regular expressions and String objects
have methods that use regular expressions:
search(regexp)
matches regexp with a string and returns the start position of
the first match if found, -1 if not
match(regexp)
without g modifier returns the matching groups for the first
match or if no match is found returns null
with g modifier returns an array containing all the matches
for the whole expression
replace(regexp,replacement)
replaces matches for regexp with replacement,
and returns the resulting string
name1 = ' Dave Shield ' . re place (/(\ w +)\ s(\ w+)/ , "$2 , $1")
regexp = new RegExp ( " (\\ w +)\\ s (\\ w +) " )
name2 = ' Ken Chan ' . replace ( regexp , "$2 , $1 ")
COMP284 Scripting Languages Lecture 11 Slide L11 29
(User-defined) Objects Pre-defined objects
Pre-defined objects: Date
The Date object can be used to access the (local) date and time
The Date object supports various constructors
new Date() current date and time
new Date(milliseconds) set date to milliseconds since 1 January 1970
new Date(dateString) set date according to dateString
new Date(year, month, day, hours, min, sec, msec)
Methods provided by Date include
toString()
returns a string representation of the Date object
getFullYear()
returns a four digit string representation of the (current) year
parse()
parses a date string and returns the number of milliseconds
since midnight of 1 January 1970
COMP284 Scripting Languages Lecture 11 Slide L11 30
(User-defined) Objects Pre-defined objects
Revision
Read
Chapter 15: JavaScript Functions, Objects, and Arrays
Chapter 16: JavaScript and PHP Validation and Error Handling
(Regular Expressions)
of
R. Nixon:
Learning PHP, MySQL, and JavaScript.
O’Reilly, 2018.
http://coffeeonthekeyboard.com/
private-variables-in-javascript-177/
http://coffeeonthekeyboard.com/
javascript-private-static-members-part-1-208/
http://coffeeonthekeyboard.com/
javascript-private-static-members-part-2-218/
COMP284 Scripting Languages Lecture 11 Slide L11 31
COMP284 Scripting Languages
Lecture 12: JavaScript (Part 4)
Handouts
Ullrich Hustadt
Department of Computer Science
School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
34 Dynamic web pages using JavaScript
Window and Document objects
Window object: Properties and methods
Dialog boxes
Input validation
Document object and Document Object Model
COMP284 Scripting Languages Lecture 12 Slide L12 1
Dynamic web pages using JavaScript Window and Document objects
Window and Document objects
JavaScript provides two objects that are essential to the creation of
dynamic web pages and interactive web applications:
window object
a JavaScript object that represents a browser window or tab
automatically created whith every instance of a <body> or
<frameset> tag
allows properties of a window to be accessed and manipulated
; JavaScript provides methods that allow window objects to be
created and manipulated
Example: window.open(’http://www.csc.liv.ac.uk’,’Home’)
whenever an object method or property is referenced in a script without
an object name and dot prefix it is assumed by JavaScript to be a
member of the window object
Example: We can write alert() instead of window.alert()
COMP284 Scripting Languages Lecture 12 Slide L12 2
Dynamic web pages using JavaScript Window object: Properties and methods
Window object
A window object represents an open window in a browser.
If a document contain frames, then there is
one window object, window, for the HTML document
and one additional window object for each frame,
accessible via an array window.frames
A window object has properties including
document document object for the window
history history object for the window
location location object (current URL) for the window
navigator navigator (web browser) object for the window
opener reference to the window that created the window
innerHeight inner height of a window’s content area
innerWidth inner width of a window’s content area
closed boolean value indicating whether the window is
(still) open
COMP284 Scripting Languages Lecture 12 Slide L12 3
Dynamic web pages using JavaScript Window object: Properties and methods
Navigator object
Properties of a navigator object include
navigator.appName the web brower’s name
navigator.appVersion the web brower’s version
Example: Load different style sheets depending on browser
<! DOCTYP E html >
<html ><head >< title > Navigat or example </ title >
< script type = " text / java scrip t " >
if ( nav igator . ap pName == ' Net scap e ' ) {
document . writeln ( ' < link rel = stylesh eet type =" text / css " '+
href = " Netscape . css " > ' )
} else if ( navigato r . appNam e == ' Opera ') {
document . writeln ( ' < link rel = stylesh eet type = " text / css " '+
href =" Opera . css " > ')
} else {
document . writeln ( ' < link rel = stylesh eet type =" text / css " '+
href = " Others . css" > ' )
}
</ script > </ head > < body > ... </ body > </ html >
COMP284 Scripting Languages Lecture 12 Slide L12 4
Dynamic web pages using JavaScript Window object: Properties and methods
Window object
Methods provided by a window object include
open(url, name [, features])
opens a new browser window/tab
returns a reference to a window object
url is the URL to access in the new window; can be the empty string
name is a name given to the window for later reference
features is a string that determines various window features
The standard sequence for the creation of a new windows is not:
// new inst ance of ` Window ' class
var newWin = new Window (...)
newWin . document . write ( ' < html >... </ html > ')
instead it is
// new window created by using ` open ' with an e xist ing one
var newWin = window . open (...)
newWin . document . write ( ' < html >... </ html > ')
COMP284 Scripting Languages Lecture 12 Slide L12 5
Dynamic web pages using JavaScript Window object: Properties and methods
Window object
Methods provided by a window object include
close()
closes a browser window/tab
focus()
give focus to a window (bring the window to the front)
blur()
removes focus from a window (moves the window behind others)
print()
prints (sends to a printer) the contents of the current window
COMP284 Scripting Languages Lecture 12 Slide L12 6
Dynamic web pages using JavaScript Window object: Properties and methods
Window object: Example
< html lang = 'en - GB ' ><head > < title > Win dow handling </ title >
< script type = ' text / java scrip t ' >
function Help () {
var Outpu tWindo w = window . open( ' ' , ' Help ' , ' res izable =1 ' );
Outp utWind ow . document . open ()
Outp utWind ow . document . writeln (" <! DOCTYPE html >\
< html lang = ' en - GB '>< head > < title > Help </ title >\
</ head >< body > This might be a context - se nsitive help \
message , depe nding on the appl icati on and state of the
page .</ body ></ html > " );
Outp utWind ow . document . close ()
}
</ script > </ head > < body >
< form name = " Butto nForm " id=" ButtonForm " action = "" >
<p >
< input type = " button " value = " Click for Help "
onc lick =" Help ();" >
</p>
</ form > </ body >
</ html >
COMP284 Scripting Languages Lecture 12 Slide L12 7
Dynamic web pages using JavaScript Dialog boxes
Window object: Dialog boxes
Often we only want to open a new window in order to
display a message
ask for confirmation of an action
request an input
For these purposes, the window object in JavaScript provides
pre-defined methods for the handling of dialog boxes
(windows for simple dialogs):
null alert(message_string)
bool confirm(message_string)
string prompt(message_string, default)
COMP284 Scripting Languages Lecture 12 Slide L12 8
Dynamic web pages using JavaScript Dialog boxes
Window object: Dialog boxes
null alert(message_string)
creates a message box displaying message_string
the box contains an ‘OK’ button that the user will have to click
(alternatively, the message box can be closed)
for the execution of the remaining code to proceed
Example:
alert ( " Local time: " + ( new Date ). t oString ())
COMP284 Scripting Languages Lecture 12 Slide L12 9
Dynamic web pages using JavaScript Dialog boxes
Window object: Dialog boxes
bool confirm(message_string)
creates a message box displaying message_string
the box contains two buttons ‘Cancel’ and ‘OK’
the function returns true if the user selects ‘OK’, false otherwise
Example:
var answer = confirm ( " Are you sure ? " )
COMP284 Scripting Languages Lecture 12 Slide L12 10
Dynamic web pages using JavaScript Dialog boxes
Window object: Dialog boxes
string prompt(message_string, default)
creates a dialog box displaying
message_string and an input
field
if a second argument default
is given, default will be
shown in the input field
the box contains two buttons
‘Cancel’ and ‘OK’
if the user selects ‘OK’ then
the current value entered in
the input field is returned as a
string, otherwise null
is
returned
Example:
var userName =
prompt ( " What is your name ?" ,
"")
COMP284 Scripting Languages Lecture 12 Slide L12 11
Dynamic web pages using JavaScript Dialog boxes
Window object: Dialog boxes
prompt() always returns a string, even if the user enters a number
To convert a string to number the following functions can be used:
number parseInt(string [,base])
converts string to an integer number wrt numeral system base
only converts up to the first invalid character in string
if the first non-whitespace character in string is not a digit, returns NaN
number parseFloat(string)
converts string to a floating-point number
only converts up to the first invalid character in string
if the first non-whitespace character in string is not a digit, returns NaN
number Number(string)
returns NaN if string contains an invalid character
Apply an identity function of number, for example, string * 1
Note: Conversion may return a number even if string is not
(for example, 2014Mar)
COMP284 Scripting Languages Lecture 12 Slide L12 12
Dynamic web pages using JavaScript Dialog boxes
Dialog boxes: Example
<! DOCTYP E html >
< html lang = 'en - GB '>
<head ><title > In teract ion example </ title > </ head >
<body >
<script >
do {
string = prompt ( " How many items do you want to buy ?")
quantity = parseInt ( string )
} while ( isNaN ( qua ntity ) || quan tity <= 0)
do {
string = prompt ( " How much does an item cost ? " )
price = parse Float ( 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 >
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/jsPrompt.html
COMP284 Scripting Languages Lecture 12 Slide L12 13
Dynamic web pages using JavaScript Input validation
User input validation
A common use of JavaScript is the validation of user input
in a HTML form before it is processed:
check that required fields have not been left empty
check that fields only contain allowed characters or
comply to a certain grammar
check that values are within allowed bounds
< form me thod = " post " actio n =" process . php"
onSubmit =" r eturn validate ( this )" >
<label > User name: < input type=" text " name = " user " > </ label >
<label > Email add ress : < input type =" text " name = " email " ></ label >
< input type=" sub mit " name =" s ubmit " >
</ form >
<script >
function val idate ( form ) {
fail = vali dat eUse r ( form . user . valu e )
fail += val idateEm ail ( form . email . value )
if ( fail == "") return true
else { alert (fail ); return false } }
</ script >
COMP284 Scripting Languages Lecture 12 Slide L12 14
Dynamic web pages using JavaScript Input validation
User input validation
function valid ateUse r ( field ) {
if ( field == "") return " No user name entered \ n "
else if ( field . length < 5)
return " User name too short \ n "
else if ( field . match (/[^a -zA -Z0 -9_ -]/))
return " Invali d characte r in username \n"
else return ""
}
function valid a teEmai l ( field ) {
if ( field == "" ) ret urn " No email entered \ n "
else if (!(( field . indexOf ( " . " ) > 0) &&
( field . in dexO f ("@") > 0)))
return " Invali d format of email \ n "
else if ( field . match (/[^a -zA -Z0 -9. @_ -]/))
return " Invali d characte r in email \n"
else return ""
}
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/jsValidate.html
COMP284 Scripting Languages Lecture 12 Slide L12 15
Dynamic web pages using JavaScript Input validation
Window and Document objects
JavaScript provides two objects that are essential to the creation of
dynamic web pages and interactive web applications:
document object
an object-oriented representation of a web page (HTML document) that
is displayed in a window
allows interaction with the Document Object Model (DOM) of a page
Example: document.writeln() adds content to a web page
Document Object Model
A platform- and language-neutral interface that allows programs and
scripts to dynamically access and update the content, structure and style
of HTML, XHTML and XML documents
COMP284 Scripting Languages Lecture 12 Slide L12 16
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 > O ver the River , Charli e </ 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]
COMP284 Scripting Languages Lecture 12 Slide L12 17
Dynamic web pages using JavaScript Document object and Document Object Model
Accessing HTML elements: Object methods
Example:
// a ccess the tbody eleme nt fro m the ta ble elem ent
var myTbod yE le me nt = my Ta bl eElement . f ir stChild ;
// a ccess its second tr ele ment ; the list of child ren s tar ts at 0 ( not 1).
var mySecondTrElemen t = myTbody El em en t . childN odes [1];
// r emove its first td element
my Se co nd Tr El em en t . r emoveCh il d ( mySecondTrElement . f ir stChild );
// c hange the text cont ent of the r emainin g td eleme nt
my Se co nd Tr El em en t . firstC hi ld . first Child . data = " Peter " ;
COMP284 Scripting Languages Lecture 12 Slide L12 18
Dynamic web pages using JavaScript Document object and Document Object Model
Accessing HTML elements: Names (1)
Instead of using methods such as firstChild and childNodes[n], it is
possible to assign names to denote the children of a HTML element
Example:
< form name =" form1 " action = "">
<label > Tem perature in Fahre nheit : </ label >
< input type =" text " name = " fa hrenh eit " size = " 10 " value ="0 " ><br >
<label > Tem perature in Ce lsius : </ label >
< input type =" text " name = " celsiu s " size = " 10" value ="" >
</ form >
Then document.form1
refers to the whole form
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
COMP284 Scripting Languages Lecture 12 Slide L12 19
Dynamic web pages using JavaScript Document object and Document Object Model
Accessing HTML elements: Names (2)
Accessing HTML elements by giving them names and using paths within
the Document Object Model tree structure is still problematic
; If that tree structure changes, then those paths no longer work
Example:
Changing the previous form to
< form name =" form1 " action = "">
<div cl as s = " f ield " name = " fdiv " >
<label > Tem perature in Fahre nheit : </ label >
< input type =" text " name =" fah renheit " size =10 value ="0 " >
</div >
<div cl as s = " f ield " name = " cdiv " >
<label > Tem perature in Ce lsius : </ label >
< input type =" text " name = " celsiu s " size="10 " value = "">
</div >
</ form >
; there is now a div element between form and text field
; document.form1.celsius no longer works
; we now need to use document.form1.cdiv.celsius
COMP284 Scripting Languages Lecture 12 Slide L12 20
Dynamic web pages using JavaScript Document object and Document Object Model
Accessing HTML elements: IDs
A more reliable way is to give each HTML element an ID
(using the id attribute) and to use getElementById to retrieve
a HTML element by its ID
Example:
< form id="form1 " action = "">
<label > Tem perature in Fahre nheit : </ label >
< input type =" text " id=" fahre nhe it " size =" 10" value ="0" ><br >
<label > Tem perature in Ce lsius : </ label >
< input type =" text " id=" ce lsius " size ="10 " value = " " >
</ 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
COMP284 Scripting Languages Lecture 12 Slide L12 21
Dynamic web pages using JavaScript Document object and Document Object Model
Manipulating HTML elements
It is not only possible to access HTML elements, but also possible to
change them on-the-fly
<! DOCTYPE html >
< html l ang=" en -GB">< head >< title > Man ip ulating HTML eleme nts </ title >
<style >
td . RedBG { bac kg ro und : # f00; }
</ style >
<script >
fu nction c hange Backg round 1 ( id) {
do cument . g et Eleme ntById ( id ). style . backgr ou nd = " #00 f";
do cument . g et Eleme ntById ( id ). i nn erHTML = " blue";
}
fu nction c hange Backg round 2 ( id) {
do cument . g et Eleme ntById ( id ). cell . cl assName = " Re dBG ";
do cument . g et Eleme ntById ( id ). cell . in nerHTML = " red ";
}
</ script > </ head ><body >
< table border="1 " >< tr >
<td id ="0 " onclick = " chan geBac kgrou nd1 ( '0 '); " > white </ td >
<td id ="1 " onclick = " chan geBac kgrou nd2 ( '1 '); " > white </ td >
</tr > </ table > </ body > </ html >
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/jsBG.html
COMP284 Scripting Languages Lecture 12 Slide L12 22
Dynamic web pages using JavaScript Document object and Document Object Model
Revision
Read
Chapter 16: JavaScript and PHP Validation and Error Handling
of
R. Nixon:
Learning PHP, MySQL, and JavaScript.
O’Reilly, 2018.
Mozilla Developer Network and individual contributors:
Document Object Model (DOM), 17 November 2019.
https://developer.mozilla.org/en/docs/DOM
[accessed 4 January 2020].
W3Schools: JavaScript and HTML DOM Reference,
4 January 2019. http://www.w3schools.com/jsref/
[accessed 4 January 2019].
COMP284 Scripting Languages Lecture 12 Slide L12 23
COMP284 Scripting Languages
Lecture 13: JavaScript (Part 5)
Handouts
Ullrich Hustadt
Department of Computer Science
School of Electrical Engineering, Electronics, and Computer Science
University of Liverpool
Contents
35 Event-driven Programs
Introduction
Events
36 Extended Example
37 What next?
COMP284 Scripting Languages Lecture 13 Slide L13 1
Event-driven Programs Introduction
Event-driven JavaScript Programs
The JavaScript programs we have seen so far
were all executed sequentially
programs have a particular starting point
programs are executed step-by-step,
involving control structures and function execution
programs reach a point at which their execution stops
COMP284 Scripting Languages Lecture 13 Slide L13 2
Event-driven Programs Introduction
Event-Driven JavaScript Programs
Client-side 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)
COMP284 Scripting Languages Lecture 13 Slide L13 3
Event-driven Programs Introduction
Event Handlers and HTML Elements
HTML events are things, mostly user actions, that happen to HTML
elements
Event handlers are JavaScript functions that process events
Event handlers must be associated with HTML elements for specific
events
This can be done via attributes
< input type = " button " value = " Help " onc lick = " Help ()" >
Alternatively, a JavaScript function can be used to add a handler to an
HTML element
// All good b rows ers
window . addEve n tListe n er (" load " , Hello )
// MS IE browser
window . attachEven t (" on load " , Hello )
More than one event handler can be added this way to the same
element for the same event
COMP284 Scripting Languages Lecture 13 Slide L13 4
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 ( wi ndow . addEv entList ener ) {
window . addEve n tListe n er (" load " , Hello )
} else {
window . attachEven t (" on load " , Hello )
}
Event handlers can also be removed
if ( wi ndow . remov e EventLi s tener ) {
window . removeE v entList e ner (" load ", Hello )
} else {
window . detachEven t (" on load " , Hello )
}
COMP284 Scripting Languages Lecture 13 Slide L13 5
Event-driven Programs Introduction
Events: Load
An (on)load event occurs when an object has been loaded
Typically, event handlers for onload events are associated with the
window object or the body element of an HTML document
< html lang = " en - GB " >
<head >
<title > Onload Example </ title >
< script type = " text / java scrip t " >
function Hello () { alert (" Welcome to my page ! " ) }
</ script >
</ head >
< body onload = " Hello () " >
<p > Content of the web page </ p >
</ body >
</ html >
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP519/examples/jsOnload.html
COMP284 Scripting Languages Lecture 13 Slide L13 6
Event-driven Programs Events
Events: Focus / Change
A focus event occurs when a form field receives input focus by tabbing
with the keyboard or clicking with the mouse
; onFocus attribute
A change event occurs when a select, text, or textarea field loses focus
and its value has been modified
; onChange attribute
< form name = " form1 " method = " post " action = " pro cess . php" >
< select name = " select" required
onChange =" doc umen t . form1 . su bmit (); " >
< option value = " " >Select a name </ option >
< option value = " 2008 12345 " > Tom Beck </ option >
< option value = " 2008 67890 " > Jim Kent </ option >
</ select >
</ form >
COMP284 Scripting Languages Lecture 13 Slide L13 7
Event-driven Programs Events
Events: Focus / Change
A focus event occurs when a form field receives input focus by tabbing
with the keyboard or clicking with the mouse
; onFocus attribute
A change event occurs when a select, text, or textarea field loses focus
and its value has been modified
; onChange attribute
<form ><label > Temperat ure in Fahre nheit : </ label >
< input type = " text " id =" f ahren heit " size ="10 " value ="0"
onchange =" doc umen t . getE lementB yId (' c elsius '). value =
Fahren heitToCe l sius ( p arseF loat (
document . getEl ementB y Id (' fa hrenh eit '). value )). t oFixed (1); "
>
<label > Te mpera ture in Celsius : </ label >
< input type = " text " id =" celsius "
size = " 10 " value ="" onfo cus = " blur (); " > </ form >
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/jsOnchange.html
COMP284 Scripting Languages Lecture 13 Slide L13 8
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
<! DOCTYP E html >
<html ><head >< title > On click Example </ title > </head >< body >
< form name = " form1 " action = " " >
Enter a number here :
< input type = " text " size ="12 " id =" number " value =" 3.1 ">
< input type = " button " value = " Double "
onc lick =" doc umen t . getE l ementB yId (' n umber '). value =
pars eFloa t ( document . getE lement ById (' number '). value )
* 2;" >
</ form > </ body > </ html >
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/jsOnclick.html
COMP284 Scripting Languages Lecture 13 Slide L13 9
Event-driven Programs Events
Events: MouseOver / Select / Submit
A keydown event occurs when the user presses a key
; onkeydown attribute
A mouseOver event occurs once each time the mouse pointer moves
over an HTML element from outside that element
; onMouseOver attribute
A select event occurs when a user selects some of the text within a text
or textarea field
; onSelect attribute
A submit event occurs when a user submits a form
; onSubmit attribute
COMP284 Scripting Languages Lecture 13 Slide L13 10
Event-driven Programs Events
Events and DOM
When an event occurs, an event object is created
; an event object has attributes and methods
; event objects can be created by your code
independent of an event occurring
In most browsers, the event object is passed to event handler functions
as an argument
In most versions of Microsoft Internet Explorer, the most recent event
can only be accessed via window.event
<html >< body onKey Down = " processKe y ( event )" >
<script >
function proc essKey (e) {
e = e || window . event
document . getEl ementB y Id (" key "). innerHT ML =
String . fromC harCod e (e. keyCod e )+ ' has been p ressed '}
</ script >
<!-- key code will appear in the para graph below -->
<p id ="key " ></p >
</ body > </ html >
COMP284 Scripting Languages Lecture 13 Slide L13 11
Extended Example
Example: Two-Player Board Game
We want to develop a two-player board game
along the lines of Tic-Tac-Toe
The full code is available at
https://cgi.csc.liv.ac.uk/
~
ullrich/COMP284/examples/jsBoard.html
The interface will consist of a 3x3 table representing the board and a
section for messages, both of which will be generated dynamically
<body >
< table id=" t1" ></ table >
<div id=" m1" ></div >
<script >... </ script >
</ body >
COMP284 Scripting Languages Lecture 13 Slide L13 12
Extended Example
Example: Two-Player Board Game
Following the Model-View-Controller paradigm we need a model of the
game, including the board and overall state of the
var board = [[0 ,0 ,0] ,[0 ,0 ,0] ,[0 ,0 ,0]];
var free = 9; // free position s on the board
var turn = 1; // alter nates between 0 and 1
We will use 0 to represent an empty position on the board
1 to represent a position taken by player 1
2 to represent a position taken by player 2
We have a function that turns these values into ‘nice’ representations
function numTo Lette r ( num) {
switch ( num) {
case 0: return " "
case 1: return " O "
case 2: return " X "
}
}
COMP284 Scripting Languages Lecture 13 Slide L13 13
Extended Example
Example: Two-Player Board Game
We need a function to show a message to the user
and another to clear that message
function showM essag e ( message , style) {
m1 = docu ment . getEle mentBy Id (" m1" );
m1 . i nnerHTML = message ;
m1 . style . display = " block " ;
m1 . c lassName = style ;
}
function clear Messag e () {
m1 = docu ment . getEle mentBy Id (" m1" );
m1 . style . display = " none " ;
}
COMP284 Scripting Languages Lecture 13 Slide L13 14
Extended Example
Example: Two-Player Board Game
The play function implements the turn of a user
function play (x ,y, event ) {
clea rMessa ge ();
con sole . log("x = "+x+" y = "+y); // debugging
con sole . log("b = "+ board [y ][x ]); // debug ging
if ( board [y ][x] > 0) {
show Message (" Grid position ["+x+","+y+
"] al ready oc cupi ed "," RedBG ");
} else {
board [ y ][x] = 2- turn ;
free - -;
event . target . innerHTM L = numTo Lette r (2- turn );
turn = 1 - turn ;
}
}
Arguments x and y are the co-ordinates on which the player as placed a piece
event is the event that was triggered and event.target gives us the
HTML element / table cell on which it was triggered
COMP284 Scripting Languages Lecture 13 Slide L13 15
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 = doc ument . crea teElem e nt ("tr ");
table . appendChil d ( tr );
for ( i =0; i < board [ j ]. length ; x ++) {
var td = document . create Elemen t (" td" );
var txt = docum ent . c reateT extNod e (
numT oLetter ( board [j ][i ]);
td . a ppendC hild ( txt );
td . ad d EventL i stener ( " click " ,play. bind( null ,i,j ));
tr . a ppendC hild ( td );
}
}
}
table = docum ent . getElem entByI d ( ' t1 ' );
init ( table );
play.bind makes sure that parameters x and y of play are bound to the
current values of i and j
COMP284 Scripting Languages Lecture 13 Slide L13 16
Extended Example
Example: Two-Player Board Game
Finally, we add some CSS directives to improve the visual appearance
of the game
<style >
td { border : 1 px solid black ;
width : 2 em;
height : 2 em;
text - align : center ;
vertical - align : m iddle ;
}
div . RedBG {
background - color : # f00 ;
}
div . GreenBG {
background - color : # 0 f0;
}
</ style >
COMP284 Scripting Languages Lecture 13 Slide L13 17
Extended Example
Example: Two-Player Board Game
Possible improvements:
We should detect that the board is full (free == 0) and
end the game with an appropriate message
We should detect a winning placement of pieces on the board,
end the game and declare a winner
COMP284 Scripting Languages Lecture 13 Slide L13 18
What next?
What Next?
Web applications almost always combine
client-side scripting and server-side scripting
; How to connect to a server using JavaScript?
Ajax (Asynchronous JavaScript and XML) is a
set of techniques for sending and retrieving data
from a server (asynchronously)
On the server-side often a PHP script acts as
mediator that retrieves data from a database in
response to Ajax requests
Data is typically exchanged in XML or JSON
(JavaScript Object Notation) format
By DanielSHaischt,
via Wikimedia Commons
https://commons.wikimedia.org/wiki/File%3AAjax-vergleich.svg,
CC BY-SA 3.0,
https://commons.wikimedia.org/w/index.php?curid=29724785
COMP284 Scripting Languages Lecture 13 Slide L13 19
What next?
What next?
Development of applications typically does not start from scratch
; modules and libraries / frameworks are used
PHP frameworks
Laravel
CodeIgniter
Symfony
CakePHP
Zend Framework
Phalcon
FuelPHP
PHPPixie
JavaScript frameworks
jQuery
Angular (Google)
React (Facebook)
Vue.js
Ember.js
Node.js
Mithril
Polymer
Using a framework is a skill in itself
Popularity / use of frameworks changes quite frequently
; not clear which ones to teach / learn
COMP284 Scripting Languages Lecture 13 Slide L13 20
What next?
Revision
Read
Chapter 17: Using Asynchronous Communication
of
R. Nixon:
Learning PHP, MySQL, and JavaScript.
O’Reilly, 2018.
Mozilla Developer Network and individual contributors:
Document Object Model (DOM), 17 November 2019.
https://developer.mozilla.org/en/docs/DOM
[accessed 4 January 2020].
W3Schools: JavaScript and HTML DOM Reference,
4 January 2019. http://www.w3schools.com/jsref/
[accessed 4 January 2019].
COMP284 Scripting Languages Lecture 13 Slide L13 21