COMP519 Web Programming Lecture 1: Overview of COMP519 Handouts
COMP519 Web Programming Lecture 1: Overview of COMP519 Handouts
Ullrich Hustadt
Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Contents
1 Overview Information Learning Outcomes
2 Background Internet and WWW: A First Definition Internet and WWW: History Internet and WWW: A Modern Definition Distributed Systems: Fundamental Questions Distributed Systems: Model-View-Controller Examples Web Programming versus App Programming
COMP519 Web Programming Lecture 1 Slide L1 – 1 Overview Information COMP519 Web Programming
• Module co-ordinator: Dr Ullrich Hustadt, Ashton Building, Room 1.03, [email protected] • Delivery: • Two or three lectures per week (≈28 in total) • Two lab sessions per week (≈18 in total) Refer to your personal timetable for dates, times, and places
• On-line resources: http://cgi.csc.liv.ac.uk/~ullrich/COMP519/ • Assessment: Four programming assignments each worth 25% of the module mark (68 hours vs 48 hours on COMP518; one working day per week)
COMP519 Web Programming Lecture 1 Slide L1 – 2 Overview Information Recommended Books
1 C. Bates: Web Programming: Building Internet Applications (3rd ed). John Wiley & Sons, 2006. 2 A. Beautieu: Learning SQL (2nd ed). O’Reilly, 2009. 3 M. E. Davis and J.A. Phillips, Learning PHP & MySQL (2nd ed). O’Reilly, 2007. 4 S. Schafer, Web Standards programmer’s reference: HTML, CSS, JavaScript, Perl, Python, and PHP. Wiley, 2005. 5 R. L. Schwartz, T. Phoenix, and bd foy: Learning Perl (6th ed). O’Reilly, 2011. 6 N. C. Zakas: Professional Javascript for Web Developers (2nd ed). Wiley, 2009. http://readinglists.liverpool.ac.uk/modules/comp519.html
By the end of this module, a student should 1 have an understanding of the range of programming techniques and languages available to organisations and businesses and be able to choose an appropriate architecture for a web application; 2 be able to demonstrate abilities to design and implement maintainable web sites; 3 be able to make informed and critical decisions regarding client development using HTML and JavaScript; 4 be able to design and implement reasonably sophisticated server-side applications using one or more suitable technologies; 5 have the knowledge to critically analyse and evaluate web applications; 6 have a critical and systematic understanding of web protocols.
COMP519 Web Programming Lecture 1 Slide L1 – 4 Overview Learning Outcomes Learning Outcomes in a Nutshell
By the end of this module, a student should • be able to design, develop and evaluate web applications
COMP519 Web Programming Lecture 1 Slide L1 – 5 Background Internet and WWW: A First Definition Web 6= Internet
Internet A physical network of networks connecting billions of computers and other devices using common protocols (TCP/IP) for sharing and transmitting information
World Wide Web [Old] A collection of interlinked multimedia documents (web pages stored on internet connected devices and accessed using a common protocol (HTTP))
Key distinction: • The internet is hardware plus protocols while the world wide web is software plus protocols • The world wide web is an application using the internet to transmit information, just like many others, for example, email, SSH, FTP
COMP519 Web Programming Lecture 1 Slide L1 – 6 Background Internet and WWW: History History (1)
• 1969: ARPANET (precursor of the Internet) • 1971: First e-mail transmission • 1971: File Transfer Protocol (FTP) • 1972: Vadic VA3400 modem (1,200 bit/s over phone network) • 1977: RSA public-key cryptography • 1977-79: EPSS/SERCnet (first UK networks between research institutions) • 1981: IBM PC 5150 • 1981: Hayes Smartmodem (300 bit/s; computer controlled) • 1982: TCP/IP standardised • 1985: FTP on TCP standardised
COMP519 Web Programming Lecture 1 Slide L1 – 7 Background Internet and WWW: History History (2)
• mid 1980s: Janet (UK network between research institutions with 2 Mbit/s backbone and 64 kbit/s access links) • 1986: U.S. Robotics HST modem (9600 bit/s) • late 1980s: TCP/IP networks expand across the world • 1991: Janet adds IP service • 1991: Gopher / World Wide Web • 1991: GSM (second generation cellular network) digital, circuit switched network for full duplex voice telephony • 1995: First public releases of JavaScript and PHP • 1997: World Wide Web slowly arrives on mobile phones
COMP519 Web Programming Lecture 1 Slide L1 – 8 Background Internet and WWW: History History (3)
Current Applications: • Communication via e-mail, Twitter, etc • Joint manipulation of concepts and actions: Collaborative editing, Crowd sourcing, Wikis (Wikipedia) • E-Commerce: Online auctions and markets • Social media, social networks, virtual learning environments
COMP519 Web Programming Lecture 1 Slide L1 – 9 Background Internet and WWW: A Modern Definition Web 6= Internet
World Wide Web [New] An infrastructure that allows to easily develop, deploy, and use distributed systems
Distributed systems A system in which components located on networked computers communicate and coordinate their actions by passing messages in order to achieve a common goal
COMP519 Web Programming Lecture 1 Slide L1 – 10 Background Internet and WWW: A Modern Definition Web 6= Internet
World Wide Web [New] An infrastructure that allows to easily develop, deploy, and use distributed systems
Key points: • The internet already eased the development of distributed systems by providing an appropriate infrastructure for that • The world wide web eases the development and deployment of interfaces to such system via a combination of web pages and ubiquitous web browers • The world wide web then allows every (authorised) person to instantaneously interact with such systems • Search engines allow users to easily find distributed systems that are useful to them
COMP519 Web Programming Lecture 1 Slide L1 – 11 Background Distributed Systems: Fundamental Questions Distributed Systems: Fundamental Questions
Software developers have to consider a wide, but rather stable, range of questions including: • Where can or should computations take place? • Where can or should data be stored? • How fast can data be transferred/communicated? • What is the cost of data storage/computations/communication depending on how/where we do it? • How robustly/securely can data storage/computations/communication be done depending on how/where we do it? • How much energy is available to support data storage/computations/communication depending on how/where we do it? • What is the legality of data storage/computations/communications depending on how/where we do it? The possible answers to each of these questions is also rather stable, but the ‘right’ answers change
We use the Model-View-Controller software design pattern to discuss some of these questions in more detail: • The model manages the behaviour and data • The view renders the model into a form suitable for interaction • The controller receives user input and translates it into instructions for the model
1 Where should the viewbe rendered? • On the user’s computer • On a central server (farm) possibly shared by a multitude of users
We use the Model-View-Controller software design pattern to discuss some of these questions in more detail: • The model manages the behaviour and data • The view renders the model into a form suitable for interaction • The controller receives user input and translates it into instructions for the model 2 Where should the behaviour of the model be computed? • Close to the user, on a single computer exclusively used by the user • Away from the user, on a central server (farm) shared by a multitude of users • Distributed, on several computers owned by a large group of users COMP519 Web Programming Lecture 1 Slide L1 – 14 Background Distributed Systems: Model-View-Controller Distributed Systems: Model-View-Controller
We use the Model-View-Controller software design pattern to discuss some of these questions in more detail: • The model manages the behaviour and data • The view renders the model into a form suitable for interaction • The controller receives user input and translates it into instructions for the model 3 Where should the data for the model be held? • Close to the user, on a single computer exclusively used by the user • Away from the user, on a central server (farm) shared by a multitude of users • Distributed, on several computers owned by a large group of users COMP519 Web Programming Lecture 1 Slide L1 – 15 Background Distributed Systems: Model-View-Controller Distributed Systems: Fundamental Questions
• Software developers have to consider a wide, but rather stable, range of questions • The possible answers to each of these questions is also rather stable • The ‘right’ answer to each these questions will depend on • the domain in which the question is posed • available technology • available resources
• The ‘right’ answer to each of the questions changes over time • We may go back and forth between the various answers • The reasons for that are not purely technological, but includes • legal factors • social factors • economic factors
• 1960ies: Computer terminals start to be used to interact with computers • 1968: NLS “oN-Line System” (Douglas Engelbart, SRI)
A ‘networked’ computer system with GUI, off-line mode, ‘e-mail’, collaborative word processing, hypertext, video conferencing and mouse is demonstrated
(The picture shows one of several terminals connected to a mainframe computer) Videos of the demo are available at http://www.youtube.com/watch?v=JfIgzSoTMOs
COMP519 Web Programming Lecture 1 Slide L1 – 17 Background Examples Thin clients, fat clients and cloud clients
• 1970ies: Computer terminals continue to dominate • 1978: DEC VT100 Intel 8080 processor 3 kb main memory Monochrome graphics Like NLS, this is a terminal connected to a mainframe computer via serial lines Key points: • The data is stored on the mainframe computer which also computes the behaviour of the model • The view is computed on the mainframe computer and only displayed on the terminal • The terminal receives user inputs and relays it to the mainframe computer that translates it into instructions for the model • This architecture dominated the industry for about 20 years COMP519 Web Programming Lecture 1 Slide L1 – 18 Background Examples The PC Era
• 1981: IBM PC 5150 • 1983: Apple Lisa First PC with a graphical user interface • 1985: Microsoft Windows 1.0 • 1987: HyperCard Hypermedia system for Mac OS • 1988: HyperStudio HyperCard clone for MS Windows • 1991: Instant Update Collaborative editor for Mac OS • 1992: CU-SeeMe Video Conferencing Key points: • Model, View and Controller are stored and computed locally on the PC • It took 24 years to catch up with NLS • This architecture dominated the industry for about 20 years
COMP519 Web Programming Lecture 1 Slide L1 – 19 Background Examples The Post-PC Era
• 1992: IBM Simon Personal Communicator (First smartphone) • 1996: Nokia 9000 Communicator • 2007: Apple iPhone Samsung 32-bit RISC ARM 128MB main memory 4-16GB flash memory ‘Apps’ / Web browser
• 2011: Google Chromebook Intel Atom processor 2GB main memory 16GB SSD Web-based applications In effect the Chromebook is a ’terminal’ connected to Google’s servers and others via a wireless network
COMP519 Web Programming Lecture 1 Slide L1 – 20 Background Examples The Post-PC Era
• 2011: Google Chromebook Intel Atom processor 2GB main memory 16GB SSD Web-based applications
Key points: • The data is stored on a server farm (the ‘cloud’) which also computes the behaviour of the model • The view is either computed on a server farm or on the terminal • The terminal receives user inputs and either relays those to the server farm or directly translates it into instructions for the model • This architecture has fought for dominance for 15 years • Will it dominate the future?
COMP519 Web Programming Lecture 1 Slide L1 – 21 Background Examples Thin clients, fat clients and cloud clients
• The Google Chromebook gives very similar answers to the fundamental questions as the DEC VT100 the possible answers to the fundamental questions stay the same • The; PC gave very different answers to the fundamental questions the ‘right’ answers change with time • The; Google Chromebook is more advanced than the DEC VT100 in (almost) every aspect we are not going around in circles, ; we always advance technologically
COMP519 Web Programming Lecture 1 Slide L1 – 22 Background Web Programming versus App Programming Web Programming versus App Programming
• Web Programming relies on web browsers as means to render user interfaces that are coded in HTML/CSS • Web Programming relies on HTTP as the main protocol to exchange information within a distributed system • Web-based apps use a mix of server-side and client-side computing • Web-based apps can be changed almost instantaneously and on a per-user basis • App Programming relies on directly coded ‘native’ interfaces (Swift/Java) • App Programming can rely on arbitrary protocols to exchange information within a distributed system • Programmers have more flexibility and more control when developing ‘traditional’ apps
It is not obvious which approach is better and in which situation COMP519 Web Programming Lecture 1 Slide L1 – 23 COMP519 Web Programming Lecture 2: HTML (HTTP and HTML5 Basics) Handouts
Ullrich Hustadt
Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Contents
3 HTTP Introduction History Requests Character Encodings 4 HTML Introduction History Elements, Attributes and Values 5 Further Reading
• Web clients (web browsers) and web servers use HTTP (Hypertext Transfer Protocol) to communicate with each other • More generally, HTTP is an application-layer protocol for distributed systems
COMP519 Web Programming Lecture 2 Slide L2 – 2 HTTP History HTTP: History
• 1991 – HTTP 0.9 first documented version of the protocol • 1996 – HTTP/1.0 first version of HTTP that was an Internet Engineering Task Force (IETF) informational RFC (RFC 1945) HTTP 0.9 and HTTP/1.0 require a separate TCP/IP connection for every resource request • 1997 – HTTP/1.1 first version of HTTP that was an Internet Engineering Task Force (IETF) formal standard (RFC 2068) HTTP/1.1 can reuse a TCP/IP connection to request several resources from the same server • 1997-2014 • 2015
COMP519 Web Programming Lecture 2 Slide L2 – 3 HTTP History HTTP: History
• 1991 – HTTP 0.9 • 1996 – HTTP/1.0 • 1997 – HTTP/1.1 • 1997-2014 Minor improvements and clarifications of HTTP/1.1 are developed • 2015 – HTTP/2 • Major revision of HTTP with focus on efficiency and privacy improvements • HTTP/2 allows a server to push resources to client even before they are requested • HTTP/2 puts more emphasis on encrypted connections
Browser/Client −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−→ Server GET /index.html HTTP/1.1 Host: www.example.com
Browser/Client ←−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− Server HTTP/1.1 200 OK Header Date: Mon, 24 Sep 2018 22:38:34 GMT Content-Type: text/html; charset=UTF-8 Content-Encoding: UTF-8 Content-Length: 138 Last-Modified: Wed, 10 Jan 2018 23:11:55 GMT Server: Apache/2.4.34 (Unix) (Red-Hat/Linux) ETag: "3f80f-1b6-3e1cb03b" Accept-Ranges: bytes Connection: close
Message body
An Example Page Hello World, this is a very simple HTML document.
Wikipedia Contributors: Wikipedia, The Free Encyclopedia, 16 September 2018 23:26 https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol. [accessed 13 Sep 2017]
COMP519 Web Programming Lecture 2 Slide L2 – 5 HTTP Character Encodings Character Encodings
• Computers operate on bits (0/1) and sequences of bits • To store a text, it needs to be encoded as a sequence of bits To retrieve a text, a sequence of bits needs to be decoded back to a sequence of characters • Early examples of such encodings are • 7-bit ASCII (American Standard Code for Information Interchange) • 8-bit ANSI (American National Standards Institute) • 8-bit Windows-1252 • 8-bit Mac OS Roman • However these allow to encode at most 256 characters the languages of the world contain many more characters ;
COMP519 Web Programming Lecture 2 Slide L2 – 6 HTTP Character Encodings Character Encodings
• UTF-8 is a modern solution to this problem: (Almost?) every known character is mapped to a sequence of 1x8 bits to 4x8 bits • Within UTF-8, ANSI characters retain their encoding
Char ASCII ANSI UTF-8 Mac OS Roman a 1100001 01100001 01100001 01100001 ˆa 11100010 11100010 10001001 ¨a 11100100 11100100 10001010 α 11001001:10100011
• When two systems exchange texts, then they need to agree which encoding they are using A HTTP header uses ASCII ; A HTTP message body can use an arbitrary encoding COMP519; Web Programming Lecture 2 Slide L2 – 7 HTML Introduction Hypertext and HTML
• The Hypertext Markup Language is the language for specifying the static part of a web page / elements of an interface • The terms ‘hypertext’ and ‘hypermedia’ were coined by Ted Nelson in 1963 as part of a model he developed for creating and using linked content • The idea of hypertext is attributed to Vannevar Bush who in in 1945 described a hypothetical hypertext device called Memex in a magazine article • Hypertext documents contain links to other hypertext documents, creating an associative trail that readers can choose to follow • Markup is a general term for special symbols (tags) that are added to plain text to provide additional information about document structure, content type, formatting, etc
COMP519 Web Programming Lecture 2 Slide L2 – 8 HTML History HTML: Chronology
• 1989, Berners-Lee HTML 1 Very basic, limited integration of multimedia added in 1993, web browser Mosaic supported many additional features • 1994, IETF HTML 2.0 Tried to standardize these additional features, but during 1994–96, web browsers Netscape and IE supported many new, divergent features • 1995, IETF HTML 3.0 Proposed, but never received approval • 1996, W3C HTML 3.2 Again attempted to unify all features into a single standard but also dropped some tags that were in HTML 2.0
COMP519 Web Programming Lecture 2 Slide L2 – 9 HTML History HTML: Chronology
• 1997, W3C HTML 4.0 Tried to discourage the use of ‘frames’, dropped Netscape visual tags, and introduced CSS; defined three variants: • Strict: Deprecated elements are forbidden • Transitional: Deprecated elements are allowed • Frameset: Frames are allowed • 1999, W3C HTML 4.01 Minor changes, the three variations are maintained • 2000, ISO ‘ISO HTML’ ISO/IEC 15445:2000, based on HTML 4.01 Strict
COMP519 Web Programming Lecture 2 Slide L2 – 10 HTML History HTML: Chronology
• 2000, W3C XHTML 1.0 Reformulation of all three HTML 4.01 variations in XML Unlike HTML, anyone can define their own tags and attributes Unlike HTML, XHTML requires strict adherence to coding rules • 2001, W3C XHTML 1.1 Based on XHTML 1.0 Strict, introduces modules
COMP519 Web Programming Lecture 2 Slide L2 – 11 HTML History HTML: Chronology
• 2014, W3C HTML5 Shifts the focus from ‘semantically describing scientific documents’ to ‘supporting web applications’ • 2016, W3C HTML 5.1 Adds features for more responsive web apps and improved navigation • 2017, W3C HTML 5.1 2nd Edition
COMP519 Web Programming Lecture 2 Slide L2 – 12 HTML Elements, Attributes and Values Elements, Attributes and Values
• The HTML5 specification defines a set of elements, attributes, and attribute values and their meanings (semantics) (there are more than 100 different elements alone) • Authors of HTML documents should not use elements, attributes, or attribute values for purposes other than their intended semantic purpose otherwise documents might not be processed correctly ; (still, most authors violate this rule) • HTML5 follows the separation of concerns design principle: a system should be divided into parts with functionality that overlaps as little as possible in HTML5 semantics and presentation are (mostly) separated • For; the full specification of the most recent version see S. Faulkner, A. Eicholz, T. Leithead, A. Danilo, editors: HTML 5.1 2nd Edition. W3C Recommendation, 3 October 2017. https://www.w3.org/TR/html51/ (accessed 05 October 2017)
COMP519 Web Programming Lecture 2 Slide L2 – 13 HTML Elements, Attributes and Values Elements, Attributes and Values
• Most elements consist of a start tag and a matching end tag, with some content in between • The general form of a start tag where tagName is a non-empty sequence of alphanumberic ASCII chars, attrib1,. . . ,attribN, N ≥ 0, are attributes and value1,. . . ,valueN, N ≥ 0, are attribute values • A end tag/ closing tag takes the form
COMP519 Web Programming Lecture 2 Slide L2 – 14 HTML Elements, Attributes and Values Elements, Attributes and Values
• So-called void elements only have a start tag area base br col embed hr img input keygen link meta param source track wbr • The start tags of void elements can be made self-closing by ending the tag with /> instead of >, optionally preceded by a space Examples:
• Comments take the form and cannot be nested
COMP519 Web Programming Lecture 2 Slide L2 – 15 HTML Elements, Attributes and Values Elements, Attributes and Values
• HTML5 distinguished between different categories of attributes • Required attributes: needed by elements of a particular type to function correctly • Optional attributes: used to modify the default functionality of an element • Standard attributes: supported by a large number of element types • Event attributes: used to link an element to code that is run if a particular event happens in the element’s context • Standard attributes include: • id: meant to provide a document-wide unique identifier for an element that can be used to refer to that specifc element • class: assigns an element to a named group either for semantic or for presentation purposes • title: assigns a subtextual explanation to an element; in a web browser typically shown if the mouse ‘hovers’ over the element • style: allows to change the presentation of an element
COMP519 Web Programming Lecture 2 Slide L2 – 16 HTML Elements, Attributes and Values Non-ASCII Characters
• The HTML5 specification defines a large number of named characters with the general format &name; allows access to non-ASCII and reserved characters ; Named char Rendered as Named char Rendered as â ˆa < < ä ¨a > >
Examples α α & & • Arbitrary characters can also be accessed using dec; and hex; where dec and hex are decimal and hexadecimal encodings for a character Named char Rendered as Named char Rendered as â ˆa < < ä ¨a > >
Examples α α & &
COMP519 Web Programming Lecture 2 Slide L2 – 17 Further Reading Revision and Further Reading
Read • Chapter 1: The Basics of HTML of S. Schafer: Web Standards Programmer’s Reference. Wiley Publishing, 2005. Harold Cohen Library 518.532.S29 or E-book http://library.liv.ac.uk/record=b2174141
COMP519 Web Programming Lecture 2 Slide L2 – 18 COMP519 Web Programming Lecture 3: HTML (HTLM5 Elements: Part 1) Handouts
Ullrich Hustadt
Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Contents
6 HTML HTML5 Documents The head-element The body-element
7 HTML Elements for the Body Structure Headings Lists Paragraphs Div- and Span-element Address Hyperlinks
8 Further Reading
COMP519 Web Programming Lecture 3 Slide L3 – 1 HTML HTML5 Documents HTML5 Documents
• An HTML5 document has a very simple form: It consists of a DOCTYPE-declaration and an html-element html-element
• An html-element has the form head-element body-element
• It is recommended that the start tag of an html-element specifies the language used in the document
COMP519 Web Programming Lecture 3 Slide L3 – 2 HTML The head-element Head
• The head-element should include a title-element (typically appears in the (tab) title bar of a browser) • The head-element should also include meta data such as the author of the page, a description of its content, keywords • The head-element can also include Cascading Style Sheet (CSS) definitions or links to external style sheets • The head-element can also include JavaScript code or links to files containing such code
The Highway Code
COMP519 Web Programming Lecture 3 Slide L3 – 3 HTML The body-element Body
• The body-element contains the content that is to be displayed by a web browser including • Articles, sections, footers, and navs • Headings • Paragraphs • Lists and tables • Images • The body-element may contain PHP code that is executed by the web server, producing HTML markup, that is then merged with the other content before being send to a web browser • The body-element may contain JavaScript code that reacts to events in the web browser and can dynamically change the content
COMP519 Web Programming Lecture 3 Slide L3 – 4 HTML Elements for the Body Structure Structuring the Body
• An article-element contains text that makes header- sense on its own element • A section-element contains text on the same nav- theme element • A header-element contains introductory text section- for a document, article, or section elements aside- article- element • A footer-element typically contains the elements author of the document, copyright information, footer- links to terms of use, contact information, etc element • A nav-element contains a set of navigation hyperlinks Several of these could be in one body-element • An -element contains related but aside The elements are seman- independent content to the articles/sections tic, not layout related
COMP519 Web Programming Lecture 3 Slide L3 – 5 HTML Elements for the Body Structure Structuring the Body
article-elements and section-elements header- are typically nested inside each other: element • In an HTML document corresponding to a nav- scientific paper one expects several element section-elements (for introduction, section- conclusion, etc) inside one article-element elements aside- • In an HTML document corresponding to a article- element newspaper one expects several elements article-elements (one for each report/story) footer- inside one section-element element The whole newspaper would consist of several section-elements (sport, business, etc)
COMP519 Web Programming Lecture 3 Slide L3 – 6 HTML Elements for the Body Headings Headings
• Sections are meant to be organised into a hierarchy (not necessarily using nested section-elements) • The hierarchy can be up to six levels deep • The heading elements h1 to h6 allow to specify a heading for a section at the corresponding level, with h1 being the highest level and h6 the lowest • Web browsers typically use font-size and font-weight to distinguish between headings at different levels
COMP519 Web Programming Lecture 28 Slide L28 – 10 Available Information and Input Form Data Forms in PHP: Example (1)
extraction.php $number) { $table .= "
$name
$number
"; } $table = "
Name
No of occur". "rences
".$table."
"; return $table; }} ?> http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/extraction.php COMP519 Web Programming Lecture 28 Slide L28 – 11 Available Information and Input Form Data Web Applications Revisited
Request • An interaction between a user App and a server-side web application Response often requires a sequence of Select Request requests and responses Item App • For each request, the application Response starts from scratch Enter • Request it does not maintain a state Address between consecutive requests App • it does not know whether the Response Enter requests come from the same user Payment Request or different users App Response data needs to be Confirm ; Request transferred from one execution Order App of the application to the next
COMP519 Web Programming Lecture 28 Slide L28 – 12 Available Information and Input Form Data Transfer of Data: Example
• Assume for a sequence of requests we do not care whether they come from the same user or different users • Then hidden inputs can be used for the transfer of data from one request / page to the next form1.php
• Assume for a sequence of requests we do care whether they come from the same user or different users • Sessions help to solve this problem by associating client requests with a specific user and maintaining data over a sequence of requests from that user • Sessions are often linked to user authentication but are independent of it, for example, eCommerce websites maintain a ‘shopping basket’ without requiring user authentication first However, sessions are the mechanism that is typically used to allow or deny access to web pages based on a user having been authenticated
• Servers keep track of a user’s sessions by using a session identifier, which • is generated by the server when a session starts and • is then used by the browser when the user requests a page from the server The session identifier can be sent through a cookie or by passing the session identifier in client requests
• In addition, one can use session variables for storing information to relate to a user and her session (session data), for example, the items of an order
• Sessions only store information temporarily If one needs to preserve information between visits by the same user, one needs to consider a method such as using a cookie or a database to store such information
COMP519 Web Programming Lecture 28 Slide L28 – 15 PHP Sessions Cookies
Browser −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−→ Server GET /index.html HTTP/1.1 Host: intranet.csc.liv.ac.uk
Browser ←−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− Server HTTP/1.0 200 OK Content-type: text/html Set-Cookie: name1=value1 Set-Cookie: name2=value2; Expires= Thu, 20 Mar 2014, 14:00 GMT (content of index.html)
Browser −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−→ Server GET /teaching.html HTTP/1.1 Host: intranet.csc.liv.ac.uk Cookie: name1=value1; name2=value2 Accept: */*
Browser ←−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− Server HTTP/1.0 200 OK Content-type: text/html Set-Cookie: name1=value3 Set-Cookie: name2=value4; Expires= Fri, 21 Mar 2014, 14:00 GMT Set-Cookie: name3=value5; Expires= Fri, 28 Mar 2014, 20:00 GMT (content of teaching.html)
Wikipedia Contributors: HTTP Cookie. Wikipedia, The Free Encyclopedia, 5 March 2014 20:50. http://en.wikipedia.org/wiki/HTTP_cookie [accessed 6 Mar 2014]
Sesssions proceed as follows 1 Start a PHP session – bool session_start() – string session_id([id]) – bool session_regenerate_id([delete_old]) 2 Maintain session data – bool session_start() – $_SESSION array – bool isset($_SESSION[key]) – (interacting with a database) 3 End a PHP session – bool session_destroy() – void session_unset() – bool setcookie(name, value, expires, path)
COMP519 Web Programming Lecture 28 Slide L28 – 17 PHP Sessions Start a PHP Session Start a Session
• bool session_start() • creates a session • creates a session identifier(session id) when a session is created • sets up $_SESSION array that stores session variables and session data • the function must be executed before any other header calls or output is produced
• string session_id([id]) • get or set the session id for the current session • the constant SID can also be used to retrieve the current name and session id as a string suitable for adding to URLs • string session_name([name]) • returns the name of the current session • if a name is given, the current session name will be replaced with the given one and the old name returned COMP519 Web Programming Lecture 28 Slide L28 – 18 PHP Sessions Start a PHP Session Start a PHP Session
• bool session_regenerate_id([delete_old]) • replaces the current session id with a new one • by default keeps the current session information stored in $_SESSION • if the optional boolean agument is TRUE, then the current session information is deleted regular use of this function alleviates the risk of a session ; being ‘hijacked’ "; echo "Session name: ",session_name()," ";
COMP519 Web Programming Lecture 28 Slide L28 – 19 PHP Sessions Maintain Session Data Maintain Session Data
• bool session_start() • resumes the current session based on a session identifier passed via a GET or POST request, or passed via a cookie • restores session variables and session data into $_SESSION • the function must be executed before any other header calls or output is produced • $_SESSION array • an associative array containing session variables and session data • you are responsible for choosing keys(session variables) and maintaining the associated values(session data) • bool isset($_SESSION[key]) returns TRUE iff $_SESSION[key] has already been assigned a value
COMP519 Web Programming Lecture 28 Slide L28 – 20 PHP Sessions Maintain Session Data Maintain Session Data
COMP519 Web Programming Lecture 28 Slide L28 – 21 PHP Sessions End a PHP Session End a PHP Session
• bool session_destroy() • destroys all of the data associated with the current session • it does not unset any of the global variables associated with the session, or unset the session cookie • void session_unset() • frees all session variables currently registered • bool setcookie(name, value, expires, path) • defines a cookie to be sent along with the rest of the HTTP headers • must be sent before any output from the script • the first argument is the name of the cookie • the second argument is the value of the cookie • the third argument is time the cookie expires (as a Unix timestamp), and • the fourth argument is the parth on the server in which the cookie will be available
COMP519 Web Programming Lecture 28 Slide L28 – 22 PHP Sessions End a PHP Session End a PHP Session
• bool session_destroy() • destroys all of the data associated with the current session • void session_unset() • frees all session variables currently registered • bool setcookie(name, value, expires, path) • defines a cookie to be sent along with the rest of the HTTP headers
Note: Closing your web browser will also end a session COMP519 Web Programming Lecture 28 Slide L28 – 23 PHP Sessions Session Management More on Session Management
The following code tracks whether a session is active and ends the session if there has been no activity for more then 30 minutes if(isset($_SESSION[’LAST_ACTIVITY’]) && (time() - $_SESSION[’LAST_ACTIVITY’] > 1800)) { // last request was more than 30 minates ago session_destroy(); // destroy session data in storage session_unset(); // unset session variables if(session_id() != "" || isset($_COOKIE[session_name()])) setcookie(session_name(),session_id(),time()-2592000,’/’); } else{ // update last activity time stamp $_SESSION[’LAST_ACTIVITY’] = time(); } The following code generates a new session identifier every 30 minutes if(!isset($_SESSION[’CREATED’])) { $_SESSION[’CREATED’] = time(); } else if(time() - $_SESSION[’CREATED’] > 1800) { // session started more than 30 minates ago session_regenerate_id(true); $_SESSION[’CREATED’] = time(); } http://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session-after-30-minutes
COMP519 Web Programming Lecture 28 Slide L28 – 24 PHP Sessions Example PHP Sessions: Example
COMP519 Web Programming Lecture 28 Slide L28 – 25 PHP Sessions Example PHP Sessions: Example
page1.php:
\n"; echo "Hello visitor! This is your page request no "; echo count_requests()." from this site. \n"; echo ’Continue | Finish’; ?> finish.php: \n"; echo "Goodbye visitor! \n"; echo ’Start again’; ?>
http://cgi.csc.liv.ac.uk/~ullrich/COMP284/examples/page1.php COMP519 Web Programming Lecture 28 Slide L28 – 26 PHP Sessions Example PHP and Cookies
Cookies can survive a session and transfer information from one session to the next cmylibrary.php:
function count_requests() { if(!isset($_COOKIE[’requests’])) { setcookie(’requests’, 1, time()+31536000, ’/’); return 1; } else{ // $_COOKIE[’requests’]++ would not survive, instead use setcookie(’requests’, $_COOKIE[’requests’]+1, time()+31536000, ’/’); // valid for 1 year return $_COOKIE[’requests’]+1; }} ?>
http://cgi.csc.liv.ac.uk/~ullrich/COMP284/examples/cpage1.php COMP519 Web Programming Lecture 28 Slide L28 – 27 Authentication Overview PHP Sessions and Authentication
• Sessions are the mechanism that is typically used to allow or deny access to web pages based on a user having been authenticated • Outline solution: • We want to protect a page content.php from unauthorised use • Before being allowed to access content.php, users must first authenticate themselves by providing a username and password on the page login.php • The system maintains a list of valid usernames and passwords in a database and checks usernames and passwords entered by the user against that database If the check succeeds, a session variable is set • The page content.php checks whether this session variable is set If the session variable is set, the user will see the content of the page If the session variable is not set, the user is redirected to login.php • The system also provides a logout.php page to allow the user to log out again
COMP519 Web Programming Lecture 28 Slide L28 – 28 Authentication Example PHP Sessions and Authentication: Example
Second part of login.php:
Login
Login
http://cgi.csc.liv.ac.uk/~ullrich/COMP519/examples/login.php COMP519 Web Programming Lecture 28 Slide L28 – 29 Authentication Example PHP Sessions and Authentication: Example
First part of login.php:
function checkCredentials($user,$passwd) { // Check whether $user and $passwd are non-empty // and match an entry in the database }
$error =’’; if(isset($_POST[’submit’])) { if (checkCredentials($_REQUEST[’user’],$_REQUEST[’passwd’])) { $_SESSION[’user’]=$_REQUEST[’user’]; header("location:content.php"); // Redirecting to Content } else{ $error = "Username or Password is invalid. Try Again"; } } if(isset($_SESSION[’user’])){ header("location:content.php"); } ?> COMP519 Web Programming Lecture 28 Slide L28 – 30 Authentication Example PHP Sessions and Authentication: Example
http://cgi.csc.liv.ac.uk/~ullrich/COMP284/examples/logout.php COMP519 Web Programming Lecture 28 Slide L28 – 32 Further Reading Revision and Further Reading
Read • Chapter 31: Using PHP of S. Schafer: Web Standards Programmer’s Reference. Wiley Publishing, 2005. Harold Cohen Library 518.532.S29 or E-book http://library.liv.ac.uk/record=b2174141
COMP519 Web Programming Lecture 28 Slide L28 – 33 COMP519 Web Programming Lecture 29: PHP (Part 5) Handouts
Ullrich Hustadt
Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Contents
96 Classes Defining and Instantiating a Class Visibility Class Constants Static Properties and Methods Destructors Inheritance Interfaces Introspection Functions 97 The PDO Class Introduction Connections Queries and Processing of Results Prepared Statements Transactions 98 Revision and Further Reading
COMP519 Web Programming Lecture 29 Slide L29 – 1 Classes Defining and Instantiating a Class Defining and Instantiating a Class
• PHP is an object-oriented language with classes • A class can be defined as follows: class identifier { property_definitions function_definitions }
• The class name identifier is case-sensitive • The body of a class consists of property definitions and function definitions • The function definitions may include the definition of a constructor • An object of a class is created using new identifier (arg1,arg2,...) where arg1,arg2,... is a possibly empty list of arguments passed to the constructor of the class identifier
COMP519 Web Programming Lecture 29 Slide L29 – 2 Classes Defining and Instantiating a Class A Closer Look at Class Definitions
In more detail, the definition of a class typically looks as follows class identifier { • Every instance obj of this # Properties class will have attributes vis $attrib1 ... attrib1,. . . and methods vis $attribN = value method1(), . . . accessible as obj->attrib1 and # Constructor obj->method1(a1...) function __construct( p1 ,...){ statements • __construct is the } constructor of the class and # Methods will be called whenever vis function method1 (p1 ,...){ statements new identifier(a1,...) } is executed vis function methodN (p1 ,...){ • vis is a declaration of the statements } visibility of each attribute } and method COMP519 Web Programming Lecture 29 Slide L29 – 3 Classes Defining and Instantiating a Class A Closer Look at Class Definitions
• The pseudo-variable $this is available when a method is called from within an object context and is a reference to the calling object • Inside method definitions, $this can be used to refer to the properties and methods of the calling object • The object operator -> is used to access methods and properties of the calling object
class Rectangle { protected $height; protected $width;
• Properties and methods can be declared as public accessible everywhere private accessible only within the same class protected accessible only within the class itself and by inheriting and parent classes
• For properties, a visibility class Vis { public $public = 1; declaration is required private $private = 2; • For methods, a visibility protected $protected = 3; declaration is optional protected function proFc() {} by default, methods private function priFc() {} } ; are public $v = new Vis(); • Accessing a private or echo $v->public; # prints 1 protected property / echo $v->private; # Fatal Error echo $v->protected; # Fatal Error method outside its visibility echo $v->priFc(); # Fatal Error is a fatal error echo $v->proFc(); # Fatal Error COMP519 Web Programming Lecture 29 Slide L29 – 5 Classes Class Constants Constants
• Classes can have their own constants and constants can be declared to be public, private or protected by default, class constants are public ;vis const identifier = value ; • Accessing a private or protected constant outside its visibility is a fatal error execution of the script stops • Class; constants are allocated once per class, and not for each class instance • Class constants are accessed using the scope resolution operator ::
class MyClass { const SIZE = 10; } echo MyClass::SIZE; # prints 10 $o = new MyClass(); echo $o::SIZE; # prints 10
COMP519 Web Programming Lecture 29 Slide L29 – 6 Classes Static Properties and Methods Static Properties and Methods
• Class properties or methods can be declared static • Static class properties and methods are accessed (via the class) using the scope resolution operator :: • Static class properties cannot be accessed via an instantiated class object, but static class methods can • Static class method have no access to $this class Employee { static $totalNumber = 0; public $name;
function __construct($name) { $this->$name = $name; Employee::$totalNumber++; }} $e1 = new Employee("Ada"); $e2 = new Employee("Ben"); echo Employee::$totalNumber # prints 2
• A class can have a destructor method __destruct that will be called as soon as there are no other references to a particular object class Employee { static $totalNumber = 0; public $name;
function __construct($name) { $this->name = $name; Employee::$totalNumber++; } function __destruct() { Employee::$totalNumber--; } } $e1 = new Employee("Ada"); $e2 = new Employee("Ben"); echo Employee::$totalNumber # prints 2 $e1 = null ; echo Employee::$totalNumber # prints 1 COMP519 Web Programming Lecture 29 Slide L29 – 8 Classes Inheritance Inheritance
• In a class definition it is possible to specify one parent class from which a class inherits constants, properties and methods: class identifier1 extends identifier2 {...}
• The constructor of the parent class is not automatically called it must be called explicitly from the child class • Inherited constants, properties and methods can be overridden by redeclaring them with the same name defined in the parent class • The declaration final can be used to prevent a method from being overriden • Using parent:: it is possible to access overridden methods or static properties of the parent class • Using self:: it is possible to access static properties and methods of the current class
class Rectangle { protected $height; protected $width;
function __construct($height,$width) { $this->width = $width; $this->height = $height; } function area() { return $this->width * $this->height; }}
class Square extends Rectangle { function __construct($size) { parent::__construct($size,$size); }}
$rt1 = new Rectangle(3,4); echo "\$rt1 area = ",$rt1->area(),"\n"; $sq1 = new Square(5); echo "\$sq1 area = ",$sq1->area(),"\n"; $rt1 area = 12 $sq1 area = 15 COMP519 Web Programming Lecture 29 Slide L29 – 10 Classes Interfaces Interfaces
• Interfaces specify which methods a class must implement without providing an implementation • Interfaces are defined in the same way as a class with the keyword class replaced by interface • All methods in an interface must be declared public • A class can declare that it implements one ore more interfaces using the implements keyword
interface Shape { public function area(); } class Rectangle implements Shape { ... }
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
There are functions for inspecting objects and classes: bool property_exists(object obj,string property) returns TRUE iff object has a property named property property_exists($sq1,’size’) # returns FALSE get_object_vars(object) returns an array with the accessible non-static properties of object mapped to their values get_object_vars($e2) # returns ["name" => "Ben"] get_class_methods(class) returns an array of method names defined for class get_class_methods(’Square’) # returns ["__construct", "area"]
COMP519 Web Programming Lecture 29 Slide L29 – 13 The PDO Class Introduction The PDO Class
• The PHP Data Objects (PDO) extension defines an interface for accessing databases in PHP • Various PDO drivers implement that interface for specific database management systems • PDO_MYSQL implements the PDO interface for MySQL 3.x to 5.x • PDO_SQLSRV implements the PDO interface for MS SQL Server and SQL Azure
COMP519 Web Programming Lecture 29 Slide L29 – 14 The PDO Class Connections Connections
• Before we can interact with a DBMS we need to establish a connection to it • A connection is established by creating an instance of the PDO class • The constructor for the PDO class accepts arguments that specify the database source (DSN), username, password and additional options $pdo = newPDO( dsn , username , password , options );
• Upon successful connection to the database, the constructor returns an instance of the PDO class • The connection remains active for the lifetime of that PDO object • Assigning NULL to the variable storing the PDO object destroys it and closes the connection $pdo =NULL
COMP519 Web Programming Lecture 29 Slide L29 – 15 The PDO Class Connections Connections: Example
# Connection information for the Departmental MySQL Server $host = "mysql"; $user = "ullrich"; $passwd = "------"; $db = "ullrich"; $charset = "utf8mb4"; $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
try { $pdo = new PDO($dsn,$user,$passwd,$opt); } catch (PDOException $e) { echo ’Connection failed: ’,$e->getMessage(); } COMP519 Web Programming Lecture 29 Slide L29 – 16 The PDO Class Queries and Processing of Results Queries
• The query() method of PDO objects can be used to execute an SQL query $result = $pdo->query(statement) $result = $pdo->query("SELECT * FROM meetings") • query() returns the result set (if any) of the SQL query as a PDOStatement object
• The exec() method of PDO objects executes an SQL statement, returning the number of rows affected by the statement $rowNum = $pdo->exec(statement) $rowNum = $pdo->exec("DELETE * FROM meetings")
COMP519 Web Programming Lecture 29 Slide L29 – 17 The PDO Class Queries and Processing of Results Processing Result Sets
• To get a single row as an array from a result set stored in a PDOStatement object, we can use the fetch() method • By default, PDO returns each row as an array indexed by the column name and 0-indexed column position in the row $row = $result->fetch() array(’slot’ => 1, ’name’ => ’Michael North’, ’email’ => ’[email protected]’, 0 => 1, 1 => ’Michael North’, 2 => ’[email protected]’) • After the last call of fetch() the result set should be released using $rows = $result->closeCursor() • The get all rows as an array of arrays from a result set stored in a PDOStatement object, we can use the fetchAll() method $rows = $result->fetchAll() COMP519 Web Programming Lecture 29 Slide L29 – 18 The PDO Class Queries and Processing of Results Processing Result Sets
• We can use a while-loop together with the fetch() method to iterate over all rows in a result set while ($row = $result->fetch()){ echo "Slot: ",$row["slot"], " \n"; echo "Name: ",$row["name"], " \n"; echo "Email: ",$row["email"],"
\n"; } • Alternatively, we can use a foreach-loop foreach($result as $row) { echo "Slot: ",$row["slot"], " \n"; echo "Name: ",$row["name"], " \n"; echo "Email: ",$row["email"],"
\n"; }
COMP519 Web Programming Lecture 29 Slide L29 – 19 The PDO Class Queries and Processing of Results Processing Result Sets
• Using bindColumn() we can bind a variable a particular column in the result set from a query • columns can be specified by number (starting with 1!) • columns can be specified by name (matching case) • Each call to fetch() and fetchAll() will then update all the variables that are bound to columns • The binding needs to be renewed after each query execution
$result->bindColumn(1, $slot); # bind by column no $result->bindColumn(2, $name); $result->bindColumn(’email’, $email); # bind by column name while ($row = $result->fetch(PDO::FETCH_BOUND)){ echo "Slot: ",$slot, " \n"; echo "Name: ",$name, " \n"; echo "Email: ",$email,"
\n"; }
COMP519 Web Programming Lecture 29 Slide L29 – 20 The PDO Class Prepared Statements Prepared Statements
• The use of parameterised prepared statements is preferable over queries • Prepared statements are are parsed, analysed, compiled and optimised only once • Prepared statements can be executed repeatedly with different arguments • Arguments to prepared statements do not need to be quoted and binding of parameters to arguments will automatically prevent SQL injection • PDO can emulate prepared statements for a DBMS that does not support them • MySQL supports prepared statements natively, so PDO emulation should be turned off $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,FALSE);
COMP519 Web Programming Lecture 29 Slide L29 – 21 The PDO Class Prepared Statements Prepared Statements: SQL Templates
• An SQL template is an SQL query (as a string) possibily containing either • named parameters of the form :name, where name is a PHP identifier, or • question marks ? for which values will be substituted when the query is executed $tpl1 = "select slot from meetings where name=:name and email=:email"; $tpl2 = "select slot from meetings where name=?"; • The PDO method prepare() turns an SQL template into prepared statement (by asking the DBMS to do so) • on success, a PDOStatement object is returned • on failure, FALSE or an error will be returned
$stmt1 = $pdo->prepare($tpl1); $stmt2 = $pdo->prepare("select * from fruit where col=?");
COMP519 Web Programming Lecture 29 Slide L29 – 22 The PDO Class Prepared Statements Prepared Statements: Binding
• We can bind the parameters of a PDOStatement object to a value using the bindValue() method • Named parameters are bound by name • Question mark parameters are bound by position (starting from 1!) • the datatype of the value can optionally be declared (to match that of the corresponding database field) • the value is bound to the parameter at the time bindValue() is executed
COMP519 Web Programming Lecture 29 Slide L29 – 23 The PDO Class Prepared Statements Prepared Statements: Binding
• We can bind the parameters of a PDOStatement object to a variable using the bindParam() method • Named parameters are bound by name • Question mark parameters are bound by position (starting from 1!) • the datatype of the value can optionally be declared (to match that of the corresponding database field) • the variable is bound to the parameter as a reference • a value is only substituted when the statement is executed
• It is possible to mix bindParam() and bindValue()
COMP519 Web Programming Lecture 29 Slide L29 – 24 The PDO Class Prepared Statements Prepared Statements: Execution
• Prepared statements are executed using execute() method • Parameters must • previously have been bound using bindValue() or bindParam(), or • be given as an array of values to execute take precedence over previous bindings ; are bound using bindValue() • execute; () returns TRUE on success or FALSE on failure • On success, the PDOStatement object stores a result set (if appropriate)
COMP519 Web Programming Lecture 29 Slide L29 – 25 The PDO Class Transactions Transactions
• There are often situations where a single ‘unit of work’ requires a sequence of database operations e.g., bookings, transfers • By; default, PDO runs in ”auto-commit” mode successfully executed SQL statements cannot be ‘undone’ • ;To execute a sequence of SQL statements whose changes are • only committed at the end once all have been successful or • rolled back otherwise, PDO provides the methods • beginTransaction() • commit() • rollBack()
COMP519 Web Programming Lecture 29 Slide L29 – 26 The PDO Class Transactions Transactions
To support transactions, PDO provides the methods beginTransaction() – turns off auto-commit mode; changes to the database are not committed until commit() is called – returns TRUE on success or FALSE on failure – throws an exception if another transaction is already active commit() – changes to the database are made permanent; auto-commit mode is turned on – returns TRUE on success or FALSE on failure – throws an exception if no transaction is active rollBack() – discard changes to the database; auto-commit mode is restored – returns TRUE on success or FALSE on failure – throws an exception if no transaction is active
COMP519 Web Programming Lecture 29 Slide L29 – 27 The PDO Class Transactions Transactions: Example
//Query 1: Attempt to insert a payment record $sql = "INSERT INTO payments (user_id, amount) VALUES (?, ?)"; $stmt = $pdo->prepare($sql); $stmt ->execute(array($userId,$paymentAmount));
//Query 2: Attempt to update the user’s account $sql = "UPDATE accounts SET balance = balance + ? WHERE id = ?"; $stmt = $pdo->prepare($sql); $stmt ->execute(array($paymentAmount,$userId));
// Commit the transaction $pdo ->commit(); } catch(Exception $e){ echo $e->getMessage(); //Rollback the transaction $pdo ->rollBack(); } Based on http://thisinterestsme.com/php-pdo-transaction-example/ COMP519 Web Programming Lecture 29 Slide L29 – 28 Revision and Further Reading Revision and Further Reading
Read • Language Reference: Classes and Objects http://php.net/manual/en/language.oop5.php • The PDO Class http://php.net/manual/en/class.pdo.php of M. Achour, F. Betz, A. Dovgal, et al: PHP Manual. The PHP Group, 2017. http://uk.php.net/manual/en [accessed 07 Dec 2017]