Web Dev
Web Dev
Web Development
! What is it?
! Broad term for the work involved in developing a web site for the Internet (World Wide Web) or an intranet (a private network). ! This can include web design, web content development, client liaison, client-side/server-side scripting, web server and network security configuration, and e-commerce development. ! However, among web professionals, "web development" usually refers to the main non-design aspects of building web sites: writing markup and coding. ! Web development can range from developing the simplest static single page of plain text to the most complex web-based internet applications, electronic businesses, or social network services.
Typical Areas
! Basic Technologies
! HTTP, HTML, CSS, XML, XPath, XLink, XPointer, XSLT, ...
! Database Technology
! ...
HTTP
! Quick Facts:
! ! ! ! HTTP stands for HyperText Transfer Protocol Standardized by IETF Current Version: HTTP/1.1 Relevant documents:
! RFC2616 (June 1999) ! RFC2068 (January 1997)
! What it is:
! Application layer protocol for distributed, collaborative, hypermedia information systems ! Request / Response typical for Client Server model ! Web browsers or spiders [user agents] act as clients and access resources located on a origin server.
! In between, there can be intermediaries: proxies, gateways, tunnels
Definitions
! Hypertext
! "Text displayed on a computer or other electronic device with references (hyperlinks) to other text that the reader can immediately access, usually by a mouse click or keypress sequence"
! Hypermedia
! "Used as a logical extension of the term hypertext in which graphics, audio, video, plain text and hyperlinks intertwine to create a generally non-linear medium of information. This contrasts with the broader term multimedia, which may be used to describe non-interactive linear presentations as well as hypermedia."
Message body
! An HTTP message may have a body of data sent after the header lines
! In responses, usually the resource returned to the client ! In requests, usually user entered data or uploaded files
Header Lines
! Header lines provide information about the request or response, or about the object sent in the message body.
Last-Modified: Fri, 31 Dec 1999 23:59:59 GMT
! HTTP 1.0 defines 16 headers (none mandatory) ! HTTP 1.1 defines 46 headers (Host: mandatory)
HTTP Methods
! ! ! HEAD
! Asks for the response identical to the one that would correspond to a GET request, but without the response body.
GET
! Requests a representation of the specified resource. ! Note: GET should not be used for operations that cause side-effects.
POST
! Submits data to be processed (e.g., from an HTML form) to the identified resource. ! Note: Data is sent in the body of the request
! ! ! ! !
PUT
! Uploads a representation of the specified resource.
DELETE
! Deletes the specified resource.
TRACE
! Echoes back the received request, so that a client can see what intermediate servers are adding or changing in the request.
OPTIONS
! Returns the HTTP methods that the server supports for specified URL.
CONNECT
! Converts the request connection to a transparent TCP/IP tunnel
! The status code is a three-digit integer, and the first digit identifies the general category of response:
! ! ! ! ! 1xx indicates an informational message only 2xx indicates success of some kind 3xx redirects the client to another URL 4xx indicates an error on the client's part 5xx indicates an error on the server's part
HTTP Proxies
! ! ! An HTTP Proxy mediates the access between the client browser and the destination web server Most proxies provide additional services: caching, authentication, authorization, etc. Two main differences when using a proxy:
1.! The browser sends the full URL (including protocol prefix http://) 2.! If HTTPS is used, the browser acts as a pure TCP relay:
! ! ! Browser sends CONNECT to proxy If proxy authorizes, will respond with 200 OK From here, proxy keeps connection open and acts as pure TCP relay
Cookies
! What are cookies?
! A small piece of text stored on a users computer by a web browser ! It consists of one or more name-value pairs ! It contains user information (preferences, shopping cart contents, etc.)
! Why Cookies?
! Because the HTTP protocol is stateless ! A server can not identify a user that performs several requests ! Without cookies it is nearly impossible to implement an shopping cart application
GET /index.html HTTP/1.1 Host: www.example.org HTTP/1.1 200 OK Content-type: text/html Set-Cookie: RMID=732423sdfs73242; expires=Fri, 31-Dec-2010 23:59:59 GMT; path=/; domain=.example.org (content of page) GET /spec.html HTTP/1.1 Host: www.example.org Cookie: name=value Accept: */*
!! !! !! !!
name = value
!! Cookie content
expires
!! Valability of the cookie
domain
!! The valability domain
path
!! The URL for which it is valid
!! Secure !! Only submit it over HTTPS !! HttpOnly !! Not possible to access it via JavaScript
HTTPS
! HTTP is a plain text protocol
! All data can be eavesdropped easily ! HTTP is subject to man-in-the-middle
! What is HTTPS?
! The same protocol (HTTP) ! SSL/TLS is used to provide:
! Authentication (two-sides authentication possible) ! Encryption of data
HTTP Authentication
! What is it?
! A mechanism included in HTTP for authenticating users ! It is defined in RFC1945 (HTTP/1.0), RFC2616 (HTTP/1.1) and RFC2617 (HTTP Authentication)
! NTLM
! Challenge-response mechanism, using a version of the Windows NTLM protocol
! Digest
! Challenge-response mechanism using MD5 checksums
! Quick facts:
! It is rare to see Web applications using HTTP Authentication on the Internet
! However, it is common in corporate Intranet
HTTP/1.0 401 UNAUTHORIZED Server: HTTPd/1.0 Date: Sat, 27 Nov 2004 10:18:15 GMT WWW-Authenticate: Basic realm="Secure Area" Content-Type: text/html Content-Length: 311 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/1999/REChtml401-19991224/loose.dtd"> <HTML> <HEAD> <TITLE>Error</TITLE> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1"> </HEAD> <BODY><H1>401 Unauthorised.</H1></BODY> </HTML>
HTTP/1.0 200 OK Server: HTTPd/1.0 Date: Sat, 27 Nov 2004 10:19:07 GMT Content-Type: text/html Content-Length: 10476
User Agent
Server
User Agent
Server
! qop
! !
! nonce
User-agent message:
! username
! ! ! ! ! Name of the user in clear text Name of the authentication realm Nonce, generated by the client Nonce count, the number of nonces generated by the user agent The password, as MD5 [to avoid replay attacks, the hash contains nonce, cnonce and nc]
Conclusions
Conclusions
! HyperText Transfer Protocol
! ! ! ! HTTP is a plain text protocol HTTP is request reply oriented HTTP is stateless Main HTTP methods are HEAD, GET, POST, ...
! GET should be used in an idempotent context ! POST can be used in a non-idempotent context
* Idempotence is the property of certain operations in mathematics and computer science, that they can be applied multiple times without changing the result
Resources
! Web Development ! Web Development, http://en.wikipedia.org/wiki/Web_development ! Web Development timeline, http://en.wikipedia.org/wiki/File:Web_development_timeline.png HTTP ! HTTP, http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol ! HTTP tutorial, http://www.jmarshall.com/easy/http
URIs
Academia Tehnic! Militar!, 2011
URIs
! What are URIs?
! A string of characters used to identify a name or a resource on the Internet. ! Such identification enables interaction with representations of the resource over a network (typically the World Wide Web) using specific protocols. ! Schemes specifying a concrete syntax and associated protocols define each URI.
An example
! The ISBN system for uniquely identifying books provides a typical example of the use of URNs. ! ISBN 0486275574 (urn:isbn:0-486-27557-4) cites unambiguously a specific edition of Shakespeare's play Romeo and Juliet. ! To gain access to this object and read the book, one needs its location: a URL address. ! A typical URL for this book on a Unix-like operating system would be a file path such as file:///home/ username/RomeoAndJuliet.pdf, identifying the electronic book saved in a file on a local hard disk. ! URNs and URLs have complementary purposes.
Technical view
! Both URLs and URNs uniquely identify a resource ! An URL specifies the means of acting upon or obtaining the representation of the resource
! For example, the URL http://www.wikipedia.org/ identifies a resource (Wikipedia's home page) and implies that a representation of that resource (such as the home page's current HTML code, as encoded characters) is obtainable via HTTP from a network host named www.wikipedia.org.
! A Uniform Resource Name (URN) is a URI that identifies a resource by name, in a particular namespace. ! One can use a URN to talk about a resource without implying its location or how to access it.
! For example, the URN urn:isbn:0-395-36341-1 is a URI that specifies the identifier system, i.e. International Standard Book Number (ISBN), as well as the unique reference within that system and allows one to talk about a book, but doesn't suggest where and how to obtain an actual copy of it.
Generic Syntax
! RFC3986 defines the generic syntax for all URI schemes:
<scheme name> : <hierarchical part> [ ? <query> ] [ # <fragment> ]
! Scheme name is terminated with colon : ! The hierarchical part is intended for hierarchical information
! It usually begins with // ! Followed by an authority part (e.g. hostname) ! Followed by an optional path
Examples of URIs
! URNs (ISBN)
urn:isbn:0451450523
! TEL
tel:<phonenumber>
! SMS
sms:<phone number>?<action> sms:+15105550101,+15105550102?body=hello%20there
! GEO
geo:<lat>,<lon>[,<alt>][;u=<uncertainty>] geo:37.786971,-122.399677
! One can not categorize many schemes as either locators or names ! The term URI is more appropriate in these cases
Encoding of URIs
! RFC1630 defines a uniform encoding scheme using ASCII characters ! The characters used are part of the ISO-Latin-1 set
! 256 characters in total ! Of these, the upper 128 characters and some other characters (ex. space, @) are considered unsure characters ! For these, an %HH encoding is used, where HH is the character code according to the ISO-Latin-1 set, in hex ! Exemple:
! Ein schner Name ! Ein%20sch%F6ner%20Name
! Fragment is not used to identify the resource itself, but to indicate a specific fragment or a part of it
! It is commonly used in the http scheme to indicate a specific part of a web page to a browser
! It is possible to specify the host ! However it is not possible to specify what protocol to use to access the resource
file://opincaru.ro/usr/oppy/doc/phd.tex file://localhost/usr/oppy/doc/phd.tex file:///usr/oppy/doc/phd.tex file://c:/Documents%20and%20Settings/oppy/My%20Documents/phd.doc
! FTP
ftp://[<user>[:<password>]@]<host>[:<port>]/<url-path> ftp://anonymous:cristian.opincaru%[email protected]/pub/phd/phd.zip ftp://ftp.opincaru.ro:21/pub/phd/phd.zip
Relative URLs
! All mentioned earlier were absolute URLs ! According to RFC1808 in the case of a relative URL, the prefix is not given, this is taken from the context (base URL) ! Base URL:
! Specified in the resource:
<HEAD> <TITLE>Example Document</TITLE> <BASE href="http://example.com/example.html"> </HEAD> ! If the resource is included in another resource
Relative URLs
Base URL: http://r/a/b/c;p?q#f //xxx /xxx xxx . .. ../xxx ;xxx ?xxx #xxx http://xxx http://r/xxx http://r/a/b/xxx http://r/a/b/ http://r/a/ http://r/a/xxx http://r/a/b/c;xxx http://r/a/b/c;p?xxx http://r/a/b/c;p?q#xxx
??????? ??
Design Failures
! Transcribable, but not easily spoken
! aitch tee tee pee colon slash slash double-you double-you double-you dot eye see es dot you see eye dot ee dee you slash tilde fielding slash
Conclusions
Conclusions
! URI = URL + URN ! The generic syntax for URLs:
<scheme> // <host> / <path> ; <parameter> ? <query string> # <fragment>
References
! URI
! URIs, http://en.wikipedia.org/wiki/Uniform_Resource_Identifier ! Relative URIs, http://www.webreference.com/html/tutorial2/3.html ! Presentation of Roy Fielding, http://www.ics.uci.edu/~fielding/talks/uri_twist99/uri_twist99.ppt ! Article about URIs, http://www.ltg.ed.ac.uk/~ht/WhatAreURIs/
http://romania.startupweekend.org/
Introduction
What is HTML?
HTML stands for Hyper Text Markup Language HTML is not a programming language, it is a markup language A markup language is a set of markup tags HTML uses markup tags to describe web pages
HTML Tags
HTML tags are keywords surrounded by angle brackets like <html> HTML tags normally come in pairs like <b> and </b> The first tag in a pair is the start tag, the second tag is the end tag Start and end tags are also called opening tags and closing tags
Markup
A markup language is
a modern system for annotating a text in a way that is syntactically distinguishable from that text. The idea and terminology evolved from the "marking up" of manuscripts, i.e. the revision instructions by editors, traditionally written with a blue pencil on authors' manuscripts.
Document Structure
<html> <head> <title>My Page</title> </head> <body> <h1>My First Heading</h1> <p>My first paragraph.</p> </body> </html>
HTML Basics
<h1>This is a heading</h1> <h2>This is a heading</h2> <h3>This is a heading</h3> <p>This is a paragraph</p> <p>This is another paragraph</p> <a href="http://www.w3schools.com">This is a link</a> <img src="w3schools.jpg" width="104" height="142" />
HTML Elements
Syntax
An HTML element starts with a start tag / opening tag An HTML element ends with an end tag / closing tag The element content is everything between the start and the end tag Some HTML elements have empty content Empty elements are closed in the start tag Most HTML elements can have attributes
What if the end tag is missing? Empty HTML elements Lower case vs. Upper case
HTML Attributes
HTML Attributes HTML elements can have attributes Attributes provide additional information about the element Attributes are always specified in the start tag Attributes come in name/value pairs like: name="value"
Quotes in HTML attributes: both and are allowed Lowercase vs. Uppercase HTML Core attributes:
Keyboard attributes
Headings
HTML Headings Must show document structure not display mode Search engines use this information for indexing
<h1>This is a heading</h1> <h2>This is a heading</h2>
Paragraphs
Paragraphs
Browsers add an empty line before and after a paragraph
Line breaks
Start a new line without defining a paragraph
<p>This is <br> a paragraph</p> <p>This is </br> a paragraph</p>
Formatting
Formatting tags
HTML uses tags like <b> and <i> for formatting output, like bold or italic text. These HTML tags are called formatting tags.
Formatting tags
Styles
Why?
Provide a common way to style all HTML elements Introduced in HTML 4 to separate content from display Can be either specified through attribute or stylesheet
style="background-color:yellow" style="font-size:10px" style="font-family:Times" style="text-align:center"
Links
Hyperlink
In web terms, a hyperlink is a reference (an address) to a resource on the web. Can be any resource type: movie, picture, text, etc.
Anchor
An anchor is a term used to define a hyperlink destination inside a document.
The HTML anchor element <a>, is used to define both hyperlinks and anchors.
<a href="http://www.w3schools.com/ target="_blank> Visit W3Schools!</a>
href attribute
The target address
target attribute
Where the link should open
name attribute
The name of the anchor (for named anchors) If a browser cannot find a named anchor that has been specified, it goes to the top of the document.
Link examples
<a href="http://www.w3schools.com/ target="_blank> Visit W3Schools!</a> <a href="http://www.w3schools.com/ target="_top">Click here</a> <a name="tips">Useful Tips Section</a> <a name="tips/> <a href="#tips>Jump to the Useful Tips Section</a> <a href="http://www.w3schools.com/html_tutorial.htm#tips"> Jump to the Useful Tips Section</a> <a href="lastpage.htm"> <img border="0" src="buttonnext.gif" width="65" height="38"> </a> <a href="mailto:[email protected]?subject=Hello%20again"> Send Mail</a>
Images
The <img> tag
Empty tag, image is referred via src
Background images
Use the background attribute
<html> <body background="background.jpg>
Image maps
In order to define clickable regions inside an image
Image maps
<img src="planets.gif width="145" height="126 usemap="#planetmap"> <map id="planetmap" name="planetmap"> <area shape="rect coords="0,0,82,126 alt="Sun" href="sun.htm"> <area shape="circle coords="90,58,3 alt="Mercury" href="mercur.htm"> <area shape="circle coords="124,58,8 alt="Venus" href="venus.htm"> </map>
Tables
Tables
Are defined with a <table> tag A table is divided in rows (<tr> tag) Each row is divided into cells (data, <td> tag) Cells may contain text, images, paragraphs, forms, tables, etc.
<table border="1"> <tr> <td>row 1, cell 1</td> <td>row 1, cell 2</td> </tr> <tr> <td>row 2, cell 1</td> <td>row 2, cell 2</td> </tr> </table>
Table tags
thead, tbody, and tfoot are used seldom because of bad browser support Cells with no content are not displayed in most brosers To force the browser to display a cell, use  
Cells spanning
<table border="1"> <tr> <th>Name</th> <th colspan="2">Telephone</th> </tr> <tr> <td>Bill Gates</td> <td>555 77 854</td> <td>555 77 855</td> </tr> </table> <table border="1"> <tr> <th>First Name:</th> <td>Bill Gates</td> </tr> <tr> <th rowspan="2">Telephone:</th> <td>555 77 854</td> </tr> <tr> <td>555 77 855</td> </tr> </table>
More tables
Lists
Unordered lists (bullets different types)
<ul>, <li>
Definition lists
<dl>, <dt>, <dd>
Forms
Forms
Are used to collect user input A form is defined with the <form> tag A form may contain different input types:
Text Fields Radio buttons Checkboxes Dropdown box Text area
<form name="input" action="html_form_submit.asp" method="get"> Username: <input type="text" name="user" /> <input type="submit" value="Submit" /> </form>
The action attribute specifies where the information is sent Forms usually contain a Submit button Forms may also be submitted via scripting
Form tags
Colors
Colors
Are defined via the hex codes of Red Green and Blue components Hex values are written as 3 double digit numbers, starting with a # sign.
#000000 for black #FFFFFF for white
Layout
For the layout of the page one can use:
Tables (remember, table cells can contain many HTML elements) Frames Floats (CSS)
Frames
Frames
With frames you can display more than one HTML document in the same page Each document is called a frame and is independent from the other Disadvantage: printing is difficult
Frameset
A frameset divides the browser window in rows or columns One can specify the space occupied by each frame
As percentage (ex. cols="25%,75%") As fixed width in pixels (ex. cols="200,500")
<noframes> can be specified for browsers with no frames support <body> can not be used together with frames However <iframe> can be used inside an HTML document
Frames
<html> <frameset rows="50%,50%"> <frame src="frame_a.htm"> <frameset cols="25%,75%"> <frame src="frame_b.htm"> <frame src="frame_c.htm"> </frameset> </frameset> </html>
Inline frames
<html> <body> <iframe src="default.html"> </iframe> <p>Some older browsers don't support iframes.</p> <p>If they don't, the iframe will not be visible.</p> </body> </html>
Character entities
Some characters are reserved for HTML (i.e. <)
If used can be mistaken for markup
To display a less than sign we must write: < or < Commonly used character entities:
Conclusions
HTML 4.0
Main goal: formatting can be completely removed from the document and kept in a separate stylesheet Separation between the presentation and document structure
XHTML
Is almost identical to HTML 4.01 Is a stricter and cleaner version of HTML Is an XML language (can be validated)
HTML5
New features
The canvas element for drawing The video and audio elements for media playback Better support for local offline storage New content specific elements, like article, footer, header, nav, section New form controls, like calendar, date, time, email, url, search
Status:
Working Draft at W3C (25 May 2011) The latest versions of all major browsers Safari, Chrome, Firefox, Opera and Internet Explorer 9 support some HTML5 features
References
HTML on Wikipedia
http://en.wikipedia.org/wiki/HTML
Cheat Sheet
Acknowledgement
Slides containing the w3schools.com logo contain information taken from www.w3schools.com The use is permitted for academic purposes and these materials shall not be freely made available on the internet.
Introduction [1]
What is CSS?
CSS stands for Cascading Style Sheets Styles define how to display HTML elements Styles were added to HTML 4.0 to solve a problem External Style Sheets can save a lot of work External Style Sheets are stored in CSS files CSS is mostly used use HTML, however it can be applied to any XML
History
Style sheets are around since SGML (1970s), in one form or another CSS level 1 was published by W3C in 1996 CSS level 2 was published by W3C in 1998
Recommendation on 07 June 2011
Introduction [2]
Why cascading?
The style of one document can be influenced by several style sheets One style can inherit or cascade from another
Main advantages
Separation of content from presentation Site wide consistency Bandwidth Table-less design
Accessibility
Web page design using tables changes the structure of the document For normal humans it makes no difference, however special user agents (spiders, text-to-speech, etc.) have difficulties
Maintainability
A single style file can be used for a whole web site
Syntax
selector [, selector2, ...][:pseudo-class] { property: value; [property2: value2; ...] } /* comment*/
Selector
Usually, the HTML element / tag you wish to define
Property
The attribute you wish to change Several properties can be specified
p { text-align:center; color:black; font-family:arial }
Selectors
The class selector
p.right {text-align:right} p.center {text-align:center} .center {text-align:center} /* all elements of one class */ <p class="right">This paragraph will be right-aligned.</p> <p class="center">This paragraph will be center-aligned.</p> <p class="center bold>Two styles</p>
The id selector
#green {color:green} p#para1 { text-align:center; color:red } <p id="para1">This paragraph will be right-aligned.</p> <p>This paragraph is not affected by the style.</p>
Inline style
<p style="color:sienna;margin-left:20px">This is a paragraph.</p>
Cascading order
Browser default External style sheet Internal style sheet Inline style
Background
Properties
background-color background-image background-repeat background-attachment background-position
body { background-color:#ffffff; background-image:url('img_tree.png'); background-repeat:no-repeat; background-position:top right; } body { background:#ffffff url('img_tree.png') no-repeat top right; }
Text
Text color
body {color:blue} h1 {color:#00ff00} h2 {color:rgb(255,0,0)} h1 {text-align:center} p.date {text-align:right} p.main {text-align:justify} h1 h2 h3 h4 {text-decoration:overline} {text-decoration:line-through} {text-decoration:underline} {text-decoration:blink}
Text alignment
Text decoration
Text transformation
Text indentation
Other: vertical align, letter spacing, word spacing, text direction, ...
Font
Font family
Font style
p.normal {font-style:normal} p.italic {font-style:italic} p.oblique {font-style:oblique} h1 {font-size:40px} h2 {font-size:30px} p {font-size:14px} h1 {font-size:2.5em} /* 40px/16=2.5em */ h2 {font-size:1.875em} /* 30px/16=1.875em */ p {font-size:0.875em} /* 14px/16=0.875em */
Font size
Using em
Font [2]
Generic property
Size: when setting the size you only specify the size of the content
Border
Border style
none, dotted, dashed, solid, double, groove, ridge, inset, outset
Border width
The width of the border
Border color
The color of the border
p { border-top-style:dotted; border-right-style:solid; border-bottom-style:dotted; border-left-style:solid; } p { border-style:solid; border-top:thick double #ff0000; }
Margin
Possible values
p { margin:100px 50px; }
Padding
Possible values
p { padding:100px 50px; }
Lists
list-style-type
none, disc, circle, square, decimal, decimal-leading-zero, armenian, georgian, lower-alpha, upper-alpha, lower-greek, lower-latin, upper-latin, lower-roman, upper-roman, inherit
list-style-image
ul { list-style-image:url('arrow.gif'); list-style-type:square; }
Other possibility:
Table
Advanced features
Sizes, positioning, pseudo elements/classes
Sizes
height
<head> <style type="text/css"> img.normal {height:auto} img.big {height:120px} </style> </head> <body> <img class="normal" src="logocss.gif" width="95" height="84" /><br /> <img class="big" src="logocss.gif" width="95" height="84" />
is is is is
display / visibility
display
Sets how/if an element is displayed Possible values: none, inline, block, list-item, ..
visibility
Sets if an element should be visible or invisible Possible values: visible, hidden, collapse
Block elements
A block element is an element that takes up the full width available, and has a line break before and after it. Examples: <h1>, <p>, <div>
Inline elements
An inline element only takes up as much width as necessary, and does not force line breaks. Examples: <a>, <span>
display / visibility
<html> <head> <style type="text/css"> h1.hid {visibility:hidden} </style> </head> <body> <h1>This is a visible heading</h1> <h1 class="hid">This is a hidden heading</h1> <p>Notice that the hidden heading still takes up space.</p> </body> </html>
Positioning [1]
Static positioning
HTML elements are positioned static by default. A static positioned element is always positioned according to the normal flow of the page. Static positioned elements are not affected by the top, bottom, left, and right properties.
Fixed positioning
An element with fixed position is positioned relative to the browser window. Fixed positioned elements are removed from the normal flow. The document and other elements behave like the fixed positioned element does not exist. Fixed positioned elements can overlap other elements.
p.pos_fixed { position:fixed; top:30px; right:5px; }
Positioning [2]
Relative positioning
A relative positioned element is positioned relative to its normal position. The content of a relatively positioned elements can be moved and overlap other elements, but the reserved space for the element is still preserved in the normal flow.
h2.pos_left { position:relative; left:-20px; }
Absolute positioning
An absolute position element is positioned relative to the first parent element that has a position other than static. If no such element is found, the containing block is <html> Absolutely positioned elements are removed from the normal flow. The document and other elements behave like the absolutely positioned element does not exist. Absolutely positioned elements can overlap other elements.
h2 { position:absolute; left:100px; top:150px; }
Overlapping elements
z-index
Specifies the stack order of an element. An element with greater stack order is always in front of an element with a lower stack order.
img { position:absolute; left:0px; top:0px; z-index:-1; } <h1>This is a heading</h1> <img src="../images/w3css.png" width="100" height="140" /> <p>Because the image has a z-index of -1, it will be placed behind the text.</p>
Floating
How?
Elements are floated horizontally, this means that an element can only be floated left or right, not up or down. The elements after the floating element will flow around it. The elements before the floating element will not be affected.
<style type="text/css"> img { float:right; } </style> <p>In the paragraph below, we have added an image with style <b>float:right</ b>. The result is that the image will float to the right in the paragraph.</p> <p> <img src="logocss.gif" width="95" height="84" /> This is some text. This is some text. This is some text. ....................
Floating
<style type="text/css"> .thumbnail { float:left; width:110px; height:90px; margin:5px; } .text_line { clear:both; margin-bottom:2px; } </style>
Align
Using the margin property
p.right { margin-left:auto; width:70%; background-color:#b0e0e6; } p.right { position:absolute; right:0px; width:300px; background-color:#b0e0e6; } p.right { float:right; width:300px; background-color:#b0e0e6; }
Pseudo-class
CSS pseudo-classes are used to add special effects to some selectors.
selector:pseudo-class {property:value} selector.class:pseudo-class {property:value}
Examples:
a:link {color:#FF0000} a:visited {color:#00FF00} a:hover {color:#FF00FF} a:active {color:#0000FF} /* /* /* /* unvisited link */ visited link */ mouse over link */ selected link */
p:first-child { /* first element in a paragraph */ color:blue; } p > i:first-child { /* first i element in a paragraph */ font-weight:bold }
Pseudo-elements
CSS pseudo-elements are used to add special effects to some selectors.
selector:pseudo-element {property:value} selector.class:pseudo-element {property:value}
Examples:
Media property
Media Types allow you to specify how documents will be presented in different media. The document can be displayed differently on the screen, on the paper, with an aural browser, etc.
<html> <head> <style> @media screen { p.test {font-family:verdana,sans-serif;font-size:14px} } @media print { p.test {font-family:times,serif;font-size:10px} } @media screen,print { p.test {font-weight:bold} } </style> </head>
Conclusions
CSS 1, 2, 3, ...
CSS Level 1
Font properties such as typeface and emphasis Color of text, backgrounds, and other elements Text attributes such as spacing between words, letters, and lines of text Alignment of text, images, tables and other elements Margin, border, padding, and positioning for most elements Unique identification and generic classification of groups of attributes Superset of CSS Level 1 Positioning (absolute, relative, fixed, z-index) Support for media types Some new properties (font, etc.)
CSS Level 2
CSS Level 3
Under development Will consist of several separate recommendations As of March 2011, there are over 40 CSS modules published from the CSS Working Group
Limitations
Vertical control limitations
While horizontal placement of elements is generally easy to control, vertical placement is frequently unintuitive, convoluted, or impossible.
Absence of expressions
There is currently no ability to specify property values as simple expressions (such as margin-left: 10% - 3em + 4px;).
Lack of ortogonality
Multiple properties often end up doing the same job. For instance, position, display and float specify the placement model, and most of the time they cannot be combined meaningfully.
References
CSS on Wikipedia
http://en.wikipedia.org/wiki/CSS
Cheat Sheet
PHP
Academia Tehnic Militar, 2011
Introduction
What is PHP?
PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server PHP supports many databases (MySQL, Informix, Oracle, etc.) PHP is an open source software
Why PHP?
PHP runs on different platforms (Windows, Linux, Unix, etc.) PHP is compatible with almost all servers used today (Apache, IIS, etc.) PHP is FREE to download PHP is easy to learn and runs efficiently on the server side
History [1]
PHP originally stood for Personal Home Page
History [2]
#define ishex(x) (((x) >= '0' && (x) <= '9') || ((x) >= 'a' && (x) <= 'f') || ((x) >= 'A' && (x) <= 'F')) int htoi(char *s) { int value; char c; c = s[0]; if(isupper(c)) c = tolower(c); value=(c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10) * 16; c = s[1]; if(isupper(c)) c = tolower(c); value += c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10; return(value); }
PHP Alternative
<html> <head> <title>Form Example</title> </head> <body> <h1>My Example Form</h1> <form action="form.phtml" method="POST"> Name: <input type="text" name="name"> Age: <input type="text" name="age"> <br><input type="submit"> </form> <?if($name):?> Hi <?echo $name?>, you are <?echo $age?> years old <?endif?> </body> </html>
Template processing
PHP is server-side and all PHP tags will be replaced by the server before anything is sent to the web browser.
<html> <?php echo "Hello World" ?> </html>
Ruby on Rails
Open Source
Velocity
Apache Software Foundation
Tags in PHP
Four types of tags available:
Short-style Long-style ASP-style Block-style
<html> <body> <? echo 'Short Tags - Most common' ?> <br /> <?php echo 'Long Tags - Portable' ?> <br /> <%= 'ASP Tags' %> <br /> <script language="php"> echo 'Really Long Tags - rarely used'; </script> <br /> </body> </html>
Language Basics
<?php // Variables $foo = 1; $bar = "Testing"; $xyz = 3.14; $foo = $foo + 1; ?> <?php // Functions phpinfo(); foo(); $len = strlen($foo); ?> <?php // Output echo $foo; printf(".2f",$price); ?> <?php // Arrays $foo[1] = 1; $foo[2] = 2; $bar[1][2] = 3; ?>
Constants in PHP
Definition
Constants, are variables which cannot be modified during the execution of the script. Constants are typically recognizable by their recommended naming convention of ALL_CAPS. Constants are defined via the define() function
Predefined constants
PHP_VERSION, PHP_OS, PHP_INT_MIN, M_PI, See http://www.php.net/manual/en/reserved.constants.php
<?php define('CONSTANT', 'Hello'); echo CONSTANT; // Would echo 'Hello' ?>
Variables in PHP
Basic Syntax
All variables in PHP start with a dollar $ sign symbol Usually variable name start with lower letter
Dynamic Typing
C, C++, Java and other use static variable typing
Variables have a given data type that remains the same until they are destroyed
PHP automatically converts the variable to the correct data type, depending on its value
A variable does not need to be declared before adding a value to it You do not need to tell PHP which data type a variable is
$name = 'Rasmus $last'; $str = "Hi $name\n"; echo $str; $greeting = true; if($greeting) { echo "Hi Carl"; $greeting = false; } echo 5 + "1.5" + "10e2"; ?>
Hi Rasmus $last
Hi Carl
1006.5
<?php $var = 1; require 'another_page.php'; // another_page.php has full // access to $var ?>
<?php $var = 'Test'; function test() { echo $var; // var not visible here } test(); ?>
Global variables
<?php $var = 'Test'; function test() { global $var; echo $var; // var visible here } test(); ?> <?php $GLOBALS['var'] = 'Test'; function test() { echo $GLOBALS['var']; } test(); ?>
References
What are references?
References are means to access the same variable content by different names References are NOT C-pointers: they are not memory addresses
You can not do pointer arithmetic, etc. with PHP references
<?php $foo = 'Hello'; $bar = 'World'; ?> <?php $bar = & $foo; ?>
Pass by reference
Return by reference
Return a reference instead of a copy of the data
IF ELSE ELSEIF
Syntax:
if (condition) code to be executed if condition is true; if (condition) code to be executed if condition is true; else code to be executed if condition is false; if (condition) code to be executed if condition is true; elseif (condition) code to be executed if condition is true; else code to be executed if condition is false;
IF ELSE ELSEIF
<html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; ?> </body> </html> <html> <body> <?php $d=date("D"); if ($d=="Fri") { echo "Hello!<br />"; echo "Have a nice weekend!"; echo "See you on Monday!"; } ?> </body> </html> <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; else echo "Have a nice day!"; ?> </body> </html>
Switching mode
It is possible to combine PHP tags with HTML, also in decision statements
<? if(strstr($_SERVER['HTTP_USER_AGENT'],"MSIE")) { echo '<b>You are using Internet Explorer</b>' else echo '<b>You are not using Internet Explorer</b>' ?>
<? if(strstr($_SERVER['HTTP_USER_AGENT'],"MSIE")) { ?> <b>You are using Internet Explorer</b> <? } else { ?> <b>You are not using Internet Explorer</b> <? } ?>
Arrays
Three kinds of arrays:
Numeric array Associative array Multidimensional array
$cars=array("Saab","Volvo","BMW","Toyota"); // or $cars[0]="Saab"; $cars[1]="Volvo"; $cars[2]="BMW"; $cars[3]="Toyota"; $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34); // or $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34";
Multidimensional arrays
$families = array ( "Griffin"=>array ( "Peter", "Lois", "Megan" ), "Quagmire"=>array ( "Glenn" ), "Brown"=>array ( "Cleveland", "Loretta", "Junior" ) );
WHO?
Loops
<?php // While $i = 0; while($i < 5) { echo $i."<br>"; $i++; } ?> <?php // Do-While $i = 0; do { echo $i."<br>"; $i++; } while($i < 0); ?> <?php // For for($i = 0; $i < 5; $i++) { echo $i."<br />"; } ?>
<?php // For Each $animals = array("Dog", "Cat", "Snake", "Tiger"); foreach($animals as $animal) echo $animal . "<br />"; ?>
Form handling
<form action="action.php" method="POST"> Your name: <input type=text name=name><br> You age: <input type=text name=age><br> <input type=submit> </form>
Action PHP Hi <?php echo $_POST['name']?>. You are <?php echo $_POST['age']?> years old.
???
Exercise
Write HTML code and PHP script for an authentication form Passwords are maintained in an array, declared in the script
<HTML> <?php
</HTML>
?>
Examples
<?php function head($title) {?> <HTML><HEAD><TITLE> <? echo $title ?> </TITLE></HEAD><BODY><? } head(Welcome to my home page!); ?> <?php function head($title=default) {?> <HTML><HEAD><TITLE> <? echo $title ?> </TITLE></HEAD><BODY><? } head(); ?> <?php function add($x, $y) { $total = $x + $y; return $total; } echo "1 + 2 = " . add(1,2); ?>
<?php $pi = 3.14; function area($radius) { return $pi * $radius * $radius; } echo 5m circle area:" . area(5); ?>
Built in functions
Array functions Calendar functions Date functions Directory functions Error functions Filesystem functions Filter functions FTP functions HTTP functions LibXML functions Mail functions Math functions Math functions Misc functions MySQL functions SimpleXML functions String functions XML Parser functions Zip functions
Array manipulation
Sorting:
sort(), rsort(), ksort(), usort(), array_multisort()
Traversal:
reset(), end(), next(), each(), current(), key(), array_walk()
Advanced:
array_diff(), array_intersect(), array_merge(), array_merge_recursive(), array_slice(), array_splice() ....
<?php $my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse"); sort($my_array); print_r($my_array); ?> Array ( [0] => Cat [1] => Dog [2] => Horse )
sort: sorts the array, does not maintain associations asort: sorts the array and maintains associations rsort: reverse sort ksort: sorts an array by key, maintaining key to data correlations.
Strings
The concatenation operator is .
<?php $str = "Fast String Manipulation"; echo substr($str,0,4) . substr($str,-9); ?> Fastipulation
Chear sheet
References
Wikipedia
http://en.wikipedia.org/wiki/PHP
PHP Manual
http://php.net/manual/en/index.php
Tutorials
http://www.w3schools.com/PHP http://en.wikiversity.org/wiki/PHP http://talks.php.net/show/oscon2002 http://www.php5-tutorial.com/
Cheat sheet
http://www.emezeta.com/weblog/emezeta-php-card-v0.2.png
Acknowledgement
Slides containing the w3schools.com logo contain information taken from www.w3schools.com The use is permitted for academic purposes and these materials shall not be freely made available on the internet.
Type = file
The input should be processed as a file. For example, when viewed in a browser, there will be a browse-button next to the input field
<html> <body> <form action="upload_file.php" method="post" enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="file" id="file" /> <br /> <input type="submit" name="submit" value="Submit" /> </form> </body> </html>
File Upload
When a file is uploaded, PHP stores it in a temporary location $_FILES global variable, contains all the uploaded file information
$_FILES["file"]["name"] The name of the uploaded file $_FILES["file"]["type"] The type of the uploaded file $_FILES["file"]["size"] The size in bytes of the uploaded file $_FILES["file"]["tmp_name"] The name of the temporary copy of the file stored on the server $_FILES["file"]["error"] The error code resulting from the file upload move_uploaded_file(string $filename, string $destination)
File handling
File functions are similar to C
// Open a file $file = fopen("welcome.txt", "r"); // Check for EOF [End-Of-File] if (feof($file)) echo "End of file"; // Read a line fgets($file) // Read a character fgetc($file) // Close the file fclose($file)
<? // Read all lines from a file $file = fopen(users.txt", "r) or exit("Unable to open file!"); //Output a line of the file until the end is reached while(!feof($file)) { echo fgets($file). "<br />"; } fclose($file); ?>
Server-side log
<?php $ip = $_SERVER['REMOTE_ADDR']; //Get there ip address. $agent = $_SERVER['HTTP_USER_AGENT']; //Get there user agent $ref = $_SERVER['HTTP_REFERER']; // Referer, how they got to your website, who // linked them, where they clicked that link. $date = date("H:i dS F"); //Get the date and time. $file = "log.txt"; //Where the log will be saved. $open = fopen($file, "a+"); //open the file, (log.htm). fwrite($open, "$date || $ip || $agent || $ref\n"); fclose($file);
?>
08:39 20th November || 188.25.154.233 || Mozilla/5.0 (Macintosh; Intel Mac OS X 10_5_8) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2 || http://opincaru.ro/tmp/ 08:41 20th November || 188.25.154.233 || Mozilla/5.0 (Macintosh; Intel Mac OS X 10.5; rv:6.0.2) Gecko/20100101 Firefox/6.0.2 || GET /tmp/log.php HTTP/1.1 Host: opincaru.ro Connection: keep-alive Cache-Control: max-age=0 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_5_8) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
HTTP Headers
HTTP headers can be added to the response Because the headers are sent before the actual response, headers have to be added before outputting any data
HTTP/1.1 200 OK Date: Mon, 23 May 2005 22:38:34 GMT Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux) Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT Etag: "3f80f-1b6-3e1cb03b" Accept-Ranges: bytes Content-Length: 438 Connection: close Content-Type: text/html; charset=UTF-8
// Redirection <?php header('Location: http://www.php.net')?> // Setting the Last-Modified Header <?php header('Last-Modified: '. gmdate('D, d M Y H:i:s',getlastmod()).' GMT')?> // Avoid all caching <?php Header('Cache-Control: no-cache, must-revalidate'); Header('Pragma: no-cache'); Header('Expires: Mon,26 Jul 1980 05:00:00 GMT'); ?>
Cookies
What are cookies? A small piece of text stored on a users computer by a web browser It consists of one or more name-value pairs It contains user information (preferences, shopping cart contents, etc.) Why Cookies? Because the HTTP protocol is stateless A server can not identify a user that performs several requests Without cookies it is nearly impossible to implement an shopping cart application
GET /index.html HTTP/1.1 Host: www.example.org HTTP/1.1 200 OK Content-type: text/html Set-Cookie: RMID=732423sdfs73242; expires=Fri, 31-Dec-2010 23:59:59 GMT; path=/; domain=.example.org (content of page) GET /spec.html HTTP/1.1 Host: www.example.org Cookie: name=value Accept: */*
name = value
Cookie content
expires
Valability of the cookie
domain
The valability domain
path
The URL for which it is valid
Secure Only submit it over HTTPS HttpOnly Not possible to access it via JavaScript
Cookies in PHP
Setting a cookie
// Syntax setcookie(name, value, expire, path, domain); // Example Setting a session cookie setcookie("user", "copincar); // Example - Setting a persistent cookie // expiration time is given in seconds setcookie("user", "copincar", time()+3600); <? echo $_COOKIE["user"]; ?>
<?php // isset: determines if a variable is not NULL if (isset($_COOKIE["user"])) echo "Welcome " . $_COOKIE["user"] . "!"; else echo "Welcome guest!"; ?> <? SetCookie('Cookie_Name',''); ?> <? SetCookie('Cookie_Name','', mktime(12,0,0,11,22,1970) ); ?>
Deleting cookies
???
Sessions
PHP implements session management
It creates a unique ID (UID) for each visitor This is stored in a cookie or propagated through the URL
$_SESSION
Allows to associate user information with one session Is available to all pages in one application
<?php session_start(); ?> <html> <body> </body> </html> <?php session_start(); // store session data $_SESSION['views']=1; ?> .................................. <?php //retrieve session data echo "Pageviews=". $_SESSION['views']; ?>
???
Error handling
By default, on error PHP will:
Display an error message with filename, line number and a message describing the error
<?php $file=fopen("welcome.txt","r"); ?>
Warning: fopen(welcome.txt) [function.fopen]: failed to open stream: No such file or directory in C:\webfolder\test.php on line 2
Error handlers
An error handler is a function that is called when an error occurs Syntax: error_function(error_level, error_message, error_file,
error_line, error_context)
Custom handlers
Functions for error handlers:
set_error_handler(callback, error_types) restore_error_handler() trigger_error(error_msg, error_type)
<?php //error handler function function customError($errno, $errstr) { echo "<b>Error:</b> [$errno] $errstr<br />"; echo "Ending Script"; die(); } //set error handler set_error_handler("customError",E_USER_WARNING); //trigger error $test=2; if ($test>1) { trigger_error("Value must be 1 or below",E_USER_WARNING); } ?>
Filter Input
<?php // Filter an email address if(!filter_has_var(INPUT_GET, "email")) { echo("Input type does not exist"); } else { if (!filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL)) { echo "E-Mail is not valid"; } else { echo "E-Mail is valid"; } } ?> <?php // Filter a URL from a form transmitted via POST if(!filter_has_var(INPUT_POST, "url")) { echo("Input type does not exist"); } else { $url = filter_input(INPUT_POST, "url", FILTER_SANITIZE_URL); } ?>
Filter Input
All input to the application must be checked for special characters In order to prevent Cross-Site Scripting attacks all output of the application is escaped The following example shows how to properly use filtering to avoid Cross-Site Scripting in a Web search form:
<?php $search_html = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_SPECIAL_CHARS); $search_url = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_ENCODED); echo "You have searched for $search_html.\n"; echo "<a href='?search=$search_url'>Search again.</a>"; ?> You have searched for Me & son. <a href='?search=Me%20%26%20son'>Search again.</a>
<?php $color = 'blue'; if (isset( $_GET['COLOR'] ) ) $color = $_GET['COLOR']; require( $color . '.php' ); ?> $myfunc = $_GET['myfunc']; $myfunc();
Debugging in PHP
Useful functions for debugging: print_r($var) displays information about a variable in a way that's readable by humans var_dump($var) same as print_r, but it also shows type information die($msg) exit($msg) halts the execution of further code
<?php $variable="Hello World"; print_r($variable); $array=array('a', 'c', 'd', 'b'); print_r($array); ?> Hello World Array ([0] => a [1] => c [2] => d [3] => b) <?php echo "Hello"; die(); // or exit(), or exit("Text to output") or die("Text to output"); echo " World"; ?> <?php $variable="Hello World"; var_dump($variable); ?> string(23) "Hello World"
Reverse Proxy
A proxy server that is installed in the neighborhood of one or more web servers All traffic coming from the Internet and with a destination of one of the web servers goes through the proxy server
Squid
GNU Open-source http://www.squid-cache.org/ Can be configured as both Caching Proxy and Reverse Proxy
single-server accelerator
front-end cache
Conclusions
Extensions
GD (GIF, JPEG, PNG, WBMP) LDAP SNMP IMAP (POP, NNTP) FTP MCAL IMSP IPTC BC/GMP (arbitrary precision math) Hyperwave XML parser PDF generation FDF (PDF forms) System V Semaphores and Shared memory DCOM (Win32 only) Java Connectivity mnogosearch (udmsearch support) Cybermut Iconv Satellite Curl gettext (GNU internationalization) zlib (compressed IO) Charset/text conversion (UTF-8, Cyrillic, Hebrew) Browser capabilities extension EXIF SWF (Flash) ASPELL/PSPELL MCRYPT Cybercash Recode Readline XSLT (Sablotron, libxslt, Xalan) WDDX NIS YAZ (Z39.50 client) Payflow Pro CCVS (Credit Card Verification System) Fribidi Ncurses Muscat
Conclusions
Today we learned about:
File uploads & File handling HTTP headers, Cookies and Sessions Error handling Data filtering and Security Proxies & Reverse proxies (Squid) Object Oriented PHP
Chear sheet
References
Wikipedia, http://en.wikipedia.org/wiki/PHP PHP Manual, http://php.net/manual/en/index.php Code Injection, http://en.wikipedia.org/wiki/Code_injection Tutorials
http://www.w3schools.com/PHP http://en.wikiversity.org/wiki/PHP http://talks.php.net/show/oscon2002 http://www.php5-tutorial.com/
Cheat sheet
http://www.emezeta.com/weblog/emezeta-php-card-v0.2.png
Acknowledgement
Slides containing the w3schools.com logo contain information taken from www.w3schools.com The use is permitted for academic purposes and these materials shall not be freely made available on the internet.
Abstract classes and methods Final classes and methods Magic methods
__construct, __destruct, __toString, __get, __set, etc.
<?php // Static method calls class foo { function bar() { echo "bar() called"; } } foo::bar(); ?>
class bar extends foo2 { function bar() { echo "Constructor for bar<br/>"; $name = get_parent_class($this); parent::$name(); } } $a = new bar(); ?>
} } ?>
Exceptions
Exception model is similar to other programming languages Exceptions can be:
Thrown Caught Extended from the base class Exception
<?php try { // some operations } catch (Exception $e) { // deal with the error } // Continue execution ?>
Exceptions - example
<?php function inverse($x) { if (!$x) { throw new Exception('Division by zero.'); } else return 1/$x; } try { echo inverse(5) . "\n"; echo inverse(0) . "\n"; } catch (Exception $e) { echo 'Caught exception: ', } // Continue execution echo 'Hello World'; ?>
$e->getMessage(), "\n";
Custom exceptions
Custom exceptions extend the base class Exception
<?php // Custom Exception Class class customException extends Exception { public function errorMessage() { $errorMsg = $this->getMessage().' is not a valid E-Mail address.'; return $errorMsg; } } try { try { // check for "example" in mail address if(strpos($email, "example") !== FALSE) { // throw exception if email is not valid throw new CustomException($email); } } catch (customException $e) { //display custom message echo $e->errorMessage(); } ?>
public function __construct($message = null, $code = 0, Exception $previous = null); final private function __clone(); final final final final final final final public public public public public public public function function function function function function function getMessage(); getCode(); getFile(); getLine(); getTrace(); getPrevious(); getTraceAsString(); // Inhibits cloning of exceptions. // // // // // // // message of exception code of exception source filename source line an array of the backtrace() previous exception formatted string of trace
Exception handlers
User-defined exception handlers can be defined These will be called if an exception is not caught via try/catch
<?php function exception_handler($exception) { echo "Uncaught exception: " , $exception->getMessage(), "\n"; } set_exception_handler('exception_handler'); throw new Exception('Uncaught Exception'); echo "Not Executed\n"; ?>
DHTML
Dynamic HTML Collection of technologies to create interactive and animated web pages DHTML is NOT a different version of HTML
JavaScript - Introduction
What is JavaScript?
JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language A scripting language is a lightweight programming language JavaScript is usually embedded directly into HTML pages JavaScript is an interpreted language (means that scripts execute without preliminary compilation) Everyone can use JavaScript without purchasing a license
Amateurs
"Most of the people writing in JavaScript are not programmers. They lack the training and discipline to write good programs. JavaScript has so much expressive power that they are able to do useful things in it, anyway. This has given JavaScript a reputation of being strictly for the amateurs, that it is not suitable for professional programming. This is simply not the case."
For more, read JavaScript: The World's Most Misunderstood Programming Language, http://javascript.crockford.com/javascript.html
JScript was introduced by Microsoft in 1996 (IE 3.0) ECMA standardizes currently JavaScript as ECMA-262 ECMAScript is also a ISO standard (ISO/IEC 16262)
History
Edition 1, 1997: First edition Edition 2, 1998: Editorial changes for ISO/IEC 16262 Edition 3, 1999: Added regular expressions, control statements, try/catch and other features Edition 4: Abandoned work split between Edition 5 and Harmony Edition 5, December 2009 Adds strict mode, new language features (getters / setters, JSON and others). Harmony, work in progress: Multiple new concepts and language features
ActionScript
A scripting language based on ECMAScript used by Adobe Flash player
ECMA International is the European Computer Manufacturers Association (ECMA)
JScript
Trademark by Microsoft Further developed into JScript .NET
ECMA Script
Standardized by ECMA International Current version 5.1 from June 2011
No script
Alternate content if scripts can not be executed Can contain any HTML elements
<script type="text/javascript"> document.write("Hello World!") </script> <noscript>Your browser does not support JavaScript!</noscript>
JavaScript Syntax
JavaScript is caSe seNsitive
Unlike HTML, but like most programming language
Variables
Like all identifiers in JavaScript, the name of variables:
Must begin with a letter, dollar sign or underscore Can contain letters (upper and lower case), numbers or underscore Naming conventions are inherited from Java:
Use myVariable, threeWordsName, etc. Not my_variable, three_words_name, etc.
Declaration (recommended):
var myVariable; var anotherVariable = 5;
Constants:
const CURRENT_VERSION = 1.0; const YEAR = 2010;
Null
Similar to C, Java, etc.
Boolean
True / False
Number
Double precision Includes two special values Infinity, NaN
String
Both single as well as double quotes are allowed
var var var var var var var birthday = true; min = -Infinity; hex = 0xFF; oct = 077; msg1 = 'This is a string'; msg2 = "Message='abc'" variable; Boolean / true Number / -Infinity Number / 255 Number / 63 String / This is a string String / Message='abc' Undefined
Scope of variables
A variable can be:
Local to a specific function
A variable with local scope is one that's defined, initialized, and used within a function; when the function terminates, the variable ceases to exist
Statements
// if else else if if (condition) { code to be executed } if (condition) { code to be executed } else { code to be executed } // switch switch (n) { case 1: execute code block 1 break; case 2: execute code block 2 break; default: code to be executed if n is different from case 1 and 2 } // do-while, while, for, for-in do { code to be executed } while (var<=endvalue); while (var <= endvalue) { code to be executed } for (var = start; var <= end; var++) { code to be executed } for (variable in object) { code to be executed } // break & continue in loops for (i = 0; i < 10; i++) { // some code here if (i == 3) continue; if (i == 7) break; }
var sorted = false; while (!sorted) { sorted = true; for (var i = 0; i < total 1; i++) if (list[i] > list[i+1]) { var tmp = list[i]; list[i] = list[i+1]; list[i+1] = tmp; sorted = false; } } alert(list);
Example:
JavaScript Objects
JavaScript is an Object Oriented Language An Object in JavaScript contains:
Properties
Only readable Both readable and writable
// Create a new instance of an object item = new Object(); myArray = new Array(10); // Access methods and properties len = myArray.length; myArray.sort();
Methods
money = { 'quarters': 10 };
When developing a Web Application, the following objects are also accessible:
Browser Objects (Window, Navigator, History, ...) HTML DOM Objects (Document, Button, Form, ...)
encodeURI
Syntax: encodeURI ( uri ) Encodes the given string as URI, escaping the special characters
parseInt
Syntax: parseInt ( string, radix)
parseFloat
Syntax: parseFloat ( string )
Array
Declaration:
// Regular array definition myArray = new Array(10); // 10 = initial capacity // Without specifying the size foo = new Array(); // With initialization var myCars=new Array("Saab","Volvo","BMW"); // Literal array var myCars=["Saab","Volvo","BMW"]; // Read element alert(Today I drive a + myCars[0]); // Modify element myCars[1] = Benz;
Access:
String
Declaration:
var txt = Hello; var txt = Hello; var txt = new String(hello);
Concatenation:
Properties:
length
Methods:
charAt(), indexOf(), lastIndexOf(), search() concat(), match(), split() replace(), slice(), substring(), toLowerCase(), toUpperCase()
Extend the function above to validate the domain using a list of Top Level Domains.
Types of Error:
EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError, NativeError
Try / Catch:
<html> <body> <script type="text/javascript"> try { eval("var a='abc'alert(a);"); } catch (err) { alert("Error: " + err.name + ":" + err.message); } </script> </body> </html>
Firefox:
Debugging JavaScript
For large non-trivial scripts access to a debugger is invaluable
Start / Stop scripts, Add breakpoints Step over, Step into, Step out, ... Inspect values / types of variables
Debuggers in Firefox
Firebug Venkman
Debuggers in Opera
DragonFly
Debuggers in Chrome
Built in
Input-Output functions
(provided by the browser via the Window object)
Alert Box
Syntax: alert(message);
Displays the message in a dialog box containing an OK button
<script type="text/javascript"> // Celsius - Fahrenheit function fahrenheit(celsius) { return celsius * 9 / 5 + 32; } var c = prompt("Enter a \ temperature in Celsius","0"); if (c != null) { alert(Fahrenheit value:" + fahrenheit(c)); } else { alert("You canceled"); } </script>
Confirm Box
Syntax: confirm(question);
Displays the message in a dialog box containing OK and Cancel buttons Returns true / false
Prompt Box
Syntax: prompt(some text, defalut value);
Opens a prompt popup, asking the user for input Returns the input of the user or null if the user pressed Cancel
Acknowledgement
Slides containing the w3schools.com logo contain information taken from www.w3schools.com The use is permitted for academic purposes and these materials shall not be freely made available on the internet.
HTML DOM
Academia Tehnic Militar, 2011
The HTML DOM is a standard for how to get, change, add or delete HTML elements.
DOM Nodes
In the DOM, everything in an HTML document is a node:
The entire document is a document node Every HTML element is an element node The text in the HTML elements are text nodes Every HTML attribute is an attribute node Comments are comment nodes
<html> <head> <title>My title</title> </head> <body> <h1>My header</h1> <a href=...>My link</a> </body> </html>
nodeValue
nodeValue for element nodes is undefined nodeValue for text nodes is the text itself nodeValue for attribute nodes is the attribute value
nodeType
getElementById()
Returns the element with the given ID
getElementsByTagName()
Returns all elements with a given tag name
Exercise:
Capitalize first word of each paragraph in a web page
<html> <head> <script type="text/javascript"> function capitalize() { // Get all paragraphs list = document.getElementsByTagName("p"); for (i=0; i < list.length; i++) { text = list[i].innerHTML; // Split the text in words words = text.split(" "); // Uppercase the first word newText = words[0].toUpperCase(); // Add the other words for (j = 1; j < words.length; j++) newText = newText + " " + words[j]; // Modify the text list[i].innerHTML = newText; } } </script> </head> <body onLoad="capitalize();"> <p>This is the first paragraph.</p> <p>This is the second one.</p> <p>Yet another one.</p> </body>
* Hints * 1) The innerHTML property gives the HTML content of an element. 2) The split() method splits a string (returns a list of substrings). 3) The toUpperCase() method transforms a string to upper case.
Objects in JavaScript
JavaScript Objects Array String Date Math etc. Browser Objects Window Navigator Screen History Location HTML DOM Objects Document Anchor Body Button Form Image etc.
There is no public standard that applies to the Browser Objects, but most browser implement them.
Important properties:
frames[] document history location name opener status top
Important Methods:
alert(message) close() confirm(message) open(URL, name, specs, replace) prompt(text, default) resizeBy() resizeTo()
Browser detection:
Important methods:
back() forward() go(number)
ex: window.history.go(-1);
Important methods:
reload() replace(newURL)
Important methods:
getElementById(id) getElementByName(name) getElementByTagName(tag) write(exp1, exp2, exp3, ...)
Events
What are events?
Events are actions that can be detected by the browser Events are associated with an HTML element Events can be associated with a custom handler Events are defined as attributes for HTML elements
<input type="text" size="20" onchange="validateEmail()>
Form Validation
HTML Code
<html> <body> <form action="target.php" method="post" onsubmit="return validateForm(this)"> Email: <input type="text" name="email" size="30"> <br> Password: <input type="password" name="password"> <br> Retype: <input type="password" name="retype"> <br> <input type="submit"> </form> </body> </html>
Form Validation
JavaScript Code <script
type="text/javascript"> function validateField(field, text) { with (field) { if ((value == null) || (value == "")) { alert(text); focus(); return false; } } return true; } function validateForm(f) { with (f) { if (!validateField(email, "Email is empty")) return false; if (!validateField(password, "Passwords is empty")) return false; if (!validateField(retype, "Retype is empty")) return false; if (password.value != retype.value) { alert("Passwords don't match"); return false; } } return true; } </script>
The style object contains properties for all style properties defined by css Examples:
document.body.style.background="#FFCC80 url(bgdesert.jpg) repeat-y"; document.getElementById("p1").style.visibility="hidden"; document.getElementById("p1").style.font="italic bold 12px arial,serif"; document.getElementById("p1").style.pageBreakAfter="always";
<HTML> <HEAD> <TITLE>Sliding Frame Example</TITLE> </HEAD> <FRAMESET cols="250,10,*" id="frameset" frameborder="no"> <FRAME src="l-frm.html" name="l-frm"> <FRAME src="sliding.html" name="s-frm" scrolling="no"> <FRAME src="r-frm.html" name="r-frm"> </FRAMESET> </FRAMESET> </HTML>
<script type=text/javascript src=slide.js></script> </head> <body onLoad="init();"> <div id="div-toggle" onClick="toggleFrame();"> </div> </body> </html>
<script type="text/javascript" src="http://www.google.com/jsapi?key=ABCDEFG"> </ script> <script type="text/javascript"> google.load("maps", "2.x"); // Call this function when the page has been loaded function initialize() { var map = new google.maps.Map2(document.getElementById("map")); map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 13); } google.setOnLoadCallback(initialize); </script>
JavaScript Frameworks
Existing JavaScript frameworks provide numerous features:
User Interface (Widgets)
Example: Progress bar, Tree, etc.
Special FX:
Example: Animations, etc.
AJAX
Asynchronous JavaScript and XML
AJAX
What is AJAX?
Asynchronous JavaScript with XML A technique used for client-side programming (not a technology) Web applications retrieve data asynchronously, in the background Usually, the XMLHttpRequest object is used Despite the name, JavaScript and XML are not required
Nor does it need to be asynchronous
Technologies used:
HTML/XHTML and CSS for presentation Document Object Model for dynamic display and interaction with data XML (sometimes JSON) for data interchange The XMLHttpRequest for asynchronous communication JavaScript to glue the technologies together
Example applications:
Google Maps, Google Reader, Google Suggest
Attributes:
readyState
HTTP status The loaded data as String The loaded data as XML (DOM can be used) Handler for the ready event
Methods:
open(mode, url, asyncMode) mode GET / POST url The URL to open asyncMode true (asynchronous) / false (synchronous) send(string) Sends the request to the server
Suggest Example
Client HTML code
<html> <head> <script src="clienthint.js"></script> </head> <body> <form> First Name: <input type="text" id="txt1" onkeyup="showHint(this.value)" /> </form> <p>Suggestions: <span id="txtHint"></span></p> </body> </html>
Suggest Example
Client JavaScript code
var xmlhttp function showHint(str) { if (str.length==0) { document.getElementById("txtHint").innerHTML=""; return; } xmlhttp=GetXmlHttpObject(); if (xmlhttp==null) { alert ("Your browser does not support XMLHTTP!"); return; } var url="gethint.php"; url=url+"?q="+str; xmlhttp.onreadystatechange=stateChanged; xmlhttp.open("GET",url,true); xmlhttp.send(null); } function stateChanged() { if (xmlhttp.readyState==4) { document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } }
Suggest Example
Server PHP code
You write it!
Drawbacks of AJAX
If JavaScript is not activated, AJAX wont work Because data is loaded dynamically
Content will not be indexed by search engines It is hard to bookmark the content
AJAX pages are substantially harder to develop than static pages Pages do not automatically register with the browser history engine.
The back button may not work This may be overcome.
Acknowledgement
Slides containing the w3schools.com logo contain information taken from www.w3schools.com The use is permitted for academic purposes and these materials shall not be freely made available on the internet.
Introduction
What is XML?
XML stands for eXtensible Markup Language XML is not itself a markup language
It is a specification for defining markup languages
XML was designed to carry data, not to display data XML tags are not predefined. You must define your own tags XML is designed to be self-descriptive XML has strong support via Unicode for many languages XML is a W3C Recommendation There are hundreds of XML-based languages
RSS, SOAP, XHTML, SVG, SMIL, Office Open XML, OpenDocument, etc.
XML Technologies
XML Languages
Languages defined on top of XML
XHTML, SOAP, WSDL, RSS, SMIL, SVG
XML Processing
Languages for processing XML
XPath, XQuery, XSLT, XSL-FO
XML APIs
Programming interfaces for dealing with XML
DOM, SAX, StAX
XML Applications
Applications using any of the above technologies
Web Services (SOAP, WSDL, UDDI)
HTML
Simplified and specialized version of SGML Not powerful enough, not rigorous enough
XML
Developed and maintained by W3C Actual versions:
XML 1.0, 5th edition (published on 26.11.2008) XML 1.1, 2nd edition (published on 16.08.2006)
First example
<?xml version="1.0"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
XML does not DO anything XML is used for data serialization XML is just plain text With XML you invent your own tags XML is a complement (not replacement) for HTML
General structure
An XML document consists of the following: Prolog
Contains meta-information about the XML document
XML Version File encoding - ex. UTF-8, ISO-8859-1, etc. Processing instructions
Instance
Consists of the actual XML data
<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE greeting SYSTEM "hello.dtd"> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
XML Tree
XML documents must contain a single root element All elements can have sub-elements
<root> <child> <sub-child> ... </subchild> ... </child> </root>
XML Tree
<bookstore> <book category="COOKING"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <book category="CHILDREN"> <title lang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book category="WEB"> <title lang="en">Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book> </bookstore>
Syntax
1. 2. 3. 4. 5. 6. 7. 8. All elements must have a closing tag XML tags are case-sensitive XML documents must be properly nested XML documents must have one single root element XML attribute values must be quoted Entity references are similar to HTML Comments in XML have the same syntax as in HTML White spaces are preserved in XML
All elements must have a closing tag (1) XML tags are case-sensitive (2) XML documents must be properly nested (1) XML documents must have one single root element (1) XML attribute values must be quoted (3) <?xml version="1.0"?> Entity references are similar to HTML (1) <book category="COOKING"> Comments in XML have the same syntax as in HTML (0) <title lang=de>Everyday Italian</title> W <author>Giada De hite spaces are preserved in XML (0) Laurentiis</author>
<year>2005</year> <price>30.00</price> <!-- No description for this book --> </book> <book category="CHILDREN"> <title lang=en>Harry Potter</title> <author>J K. Rowling & Other</author> <year>2005</year> <price>29.99</price> <description>Children <i> book</description> </Book> <book category="WEB"> <title lang=en>Learning XML</title> <author>Erik T. Ray</author> <year>2003</Year> <price>39.95</price> <description>The best <b><i>XML Book</b></i> on the market < 50$</description> </book>
XML Elements
What is an element?
An XML element is everything from (including) the element's start tag to (including) the element's end tag An element can contain other elements, simple text or a mixture of both Elements can also have attributes
Naming rules
Names can contain letters, numbers, and other characters Names cannot start with a number or punctuation character Names cannot start with the letters xml (or XML, or Xml, etc) Names cannot contain spaces No names are reserved, all names can be used Non-English characters are perfectly legal
XML Elements
Elements can be easily extended
Most applications will support such data changes without modifications
<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE greeting SYSTEM "hello.dtd"> <note> <to>Tove</to> <from>Jani</from> <body>Don't forget me this weekend!</body> </note> <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE greeting SYSTEM "hello-new.dtd"> <note date="2008-01-10" > <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
Attributes
XML elements can have attributes in the start tag
Similar to HTML
XML attributes provide more information about elements XML Attributes must be quoted
<person sex="female"> <person sex='female'> <gangster name='George "Shotgun" Ziegler'> <gangster name="George "Shotgun" Ziegler">
There are no rules if an information shall be element or attribute When deciding, consider the following: Attributes cannot contain multiple values (elements can) Attributes cannot contain tree structures (elements can) Attributes are not easily expandable (for future changes)
Use elements for data. Use attributes for information that is not relevant to the data.
XML Namespaces
<table> <tr> <td>Apples</td> <td>Bananas</td> </tr> </table> <table> <name>African Coffee Table</name> <width>80</width> <length>120</length> </table>
Elements in XML are not fixed, but defined by developers Assume you want to combine the two, in one single document
A name conflict can occur:
Table has a different meaning in the two documents
XML Namespaces
<root> <h:table xmlns:h="http://www.w3.org/TR/html4/"> <h:tr> <h:td>Apples</h:td> <h:td>Bananas</h:td> </h:tr> </h:table> <f:table xmlns:f="http://www.w3schools.com/furniture"> <f:name>African Coffee Table</f:name> <f:width>80</f:width> <f:length>120</f:length> </f:table> </root>
Name conflicts are resolved with prefixes The namespace is defined by the xmlns attribute in the start tag of an element. The namespace declaration has the following syntax:
xmlns:prefix="URI"
XML Namespaces
Some rules:
The namespace is defined by the xmlns attribute in the start tag of an element When a namespace is defined for an element, all child elements with the same prefix are associated with the same namespace. Namespaces can be declared in the elements where they are used or in the XML root element The namespace URI is not used by the parser, it is simply an identifier A default namespace can be defined for all child elements xmlns="namespaceURI"
<table xmlns="http://www.w3.org/TR/html4/"> <tr> <td>Apples</td> <td>Bananas</td> </tr> </table>
Namespaces
<?xml version="1.0" encoding="UTF-8"?> <in:Invoice xmlns:in="http://www.example.ro/invoice"> <in:Date> <in:Month>July</in:Month> <in:Day>15</in:Day> <in:Year>2001</in:Year> </in:Date> <in:Item discount="promotion" price="57"> <in:description>high speed 3D graphics card</in:description> </it:Item> </in:Invoice>
<?xml version="1.0" encoding="UTF-8"?> <other:Invoice xmlns:other="http://www.example.ro/invoice"> <other:Date> <other:Month>July</other:Month> <other:Day>15</other:Day> <other:Year>2001</other:Year> </other:Date> <other:Item discount="promotion" price="57"> <other:description>high speed 3D graphics card</other:description> </other:Item> </other:Invoice>
Valid XML
Valid: An XML document is called valid if it is well formed and it conforms to the rules of a Document Type Definition (DTD) or an XML Schema
<?xml version="1.0" encoding="ISO-8859-1"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE note SYSTEM "Note.dtd"> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
Well-Formed
Valid
XML DTD
The purpose of a DTD (Document Type Definition) is to define the legal building blocks of an XML document. A DTD defines the document structure with a list of legal elements and attributes. DTD is part of the XML Specification
<!DOCTYPE <!ELEMENT <!ELEMENT <!ELEMENT <!ELEMENT <!ELEMENT <!ELEMENT <!ELEMENT <!ATTLIST <!ATTLIST <!ATTLIST <!ATTLIST ]> NEWSPAPER [ NEWSPAPER (ARTICLE+)> ARTICLE (HEADLINE,BYLINE,LEAD,BODY,NOTES)> HEADLINE (#PCDATA)> BYLINE (#PCDATA)> LEAD (#PCDATA)> BODY (#PCDATA)> NOTES (#PCDATA)> ARTICLE ARTICLE ARTICLE ARTICLE AUTHOR CDATA #REQUIRED> EDITOR CDATA #IMPLIED> DATE CDATA #IMPLIED> EDITION CDATA #IMPLIED>
DTD declaration
Internal Declaration: <!DOCTYPE root-element [element-declarations]> External Declaration: <!DOCTYPE root-element SYSTEM "filename">
<?xml version="1.0"?> <!DOCTYPE note [ <!ELEMENT note (to,from,heading,body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT heading (#PCDATA)> <!ELEMENT body (#PCDATA)> ]> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Hy there!</body> </note> <?xml version="1.0"?> <!DOCTYPE note SYSTEM "note.dtd"> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Hi there!</body> </note> <!ELEMENT <!ELEMENT <!ELEMENT <!ELEMENT <!ELEMENT note (to,from,heading,body)> to (#PCDATA)> from (#PCDATA)> heading (#PCDATA)> body (#PCDATA)>
Attribute Type:
Default Value:
<square width="100" /> <square width="-10" /> <person number="5677" /> <person /> <contact fax="555-667788" /> <contact /> <sender company="Microsoft" /> <sender company="W3Schools" /> <payment type="check" /> <payment type="cash" /> <payment type="credit" />
DTD Entities
Entities are variables used to define shortcuts to standard text or special characters.
Entity references are references to entities Entities can be declared internal or external
External entity
To make things more complicated, you can even have entities inside entities
AUTHOR CDATA #REQUIRED> EDITOR CDATA #IMPLIED> DATE CDATA #IMPLIED> EDITION CDATA #IMPLIED> <?xml version="1.0" standalone="no" ?> <NEWSPAPER> <!ENTITY NEWSPAPER "Vervet Logic Times"> <!ENTITY PUBLISHER "Vervet Logic<ARTICLE AUTHOR="Cristian"> Press"> <HEADLINE>University today</HEADLINE> <!ENTITY COPYRIGHT "Copyright 1998 Vervet Logic <BYLINE/> Press"> ]> <LEAD>An survey on the quality of education</LEAD> <BODY>The body of the article</BODY> <NOTES>Published by &PUBLISHER; ©RIGHT;</NOTES> </ARTICLE> </NEWSPAPER>
XML Schema
What is XML Schema?
XML Schema is an XML-based alternative to DTD. An XML Schema describes the structure of an XML document.
Status
ML Schema became a W3C Recommendation 02. May 2001.
Example
<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="note"> <xs:complexType> <xs:sequence> <xs:element name="to" type="xs:string"/> <xs:element name="from" type="xs:string"/> <xs:element name="heading" type="xs:string"/> <xs:element name="body" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> <?xml version="1.0"?> <note xmlns="http://www.w3schools.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3schools.com note.xsd"> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
XML Editors
XML is text based, can be edited with any editor Notepad
You can edit XML, However it laks:
Syntax highlighting Validation
Notepad ++ [http://notepad-plus.sourceforge.net]
Syntax highlighting No validation
Other:
Most IDEs today come with an intelligent XML editor For example: Eclipse [http://www.eclipse.org/]
Conclusions
Conclusion
Well formed: An XML document is well formed if it conforms to the XML specification. Valid: An XML document is called valid if it is well formed and it conforms to the rules of a Document Type Definition (DTD) or an XML Schema DTD: A DTD defines the document structure with a list of legal elements and attributes. XML Schema: XML Schema is an XML-based alternative to DTD
Cheat Sheet
References
XML and XML Schema on Wikipedia:
http://en.wikipedia.org/wiki/XML http://en.wikipedia.org/wiki/XML_Schema_(W3C)
Acknowledgement
Slides containing the w3schools.com logo contain information taken from www.w3schools.com The use is permitted for academic purposes and these materials shall not be freely made available on the internet.
The XML DOM is a standard for how to get, change, add or delete XML documents from a scripting / programming language.
Example:
txt = xmlDoc.getElementsByTagName("title") [0].childNodes[0].nodeValue
Object)
// Loads an XML document via XMLHttpRequest function loadXMLDoc(docName) { if (window.XMLHttpRequest){ xhttp=new XMLHttpRequest(); } else { xhttp=new ActiveXObject("Microsoft.XMLHTTP"); } try { xhttp.open("GET",docName,false); xhttp.send(); } catch (e) { alert("Unable to load XML: " + e); return null; } return xhttp.responseXML;
<html> <head> <script src="clienthint.js"></script> </head> <body> <h1>Online Music Library</h1> <form> Search Title: <input type="text" id="txt1" onkeyup="showHint(this.value)" /> </form> <p>Suggestions: <span id="txtHint"></span></p> </body> </html>
The JavaScript
//Load the CD data-base var library = loadXMLDoc("cd.xml"); // Called on each update of search field function showHint(str) { var suggest = ""; var upperStr = str.toUpperCase(); var list = library.getElementsByTagName("TITLE"); for (var i=0; i<list.length; i++) { if (list[i].firstChild.nodeValue.toUpperCase().indexOf(upperStr) == 0) { if (suggest.length > 0) suggest += ", "; suggest += list[i].firstChild.nodeValue; } } } document.getElementById("txtHint").innerHTML = suggest;
What is RSS?
What is RSS?
RSS stands for Really Simple Syndication RSS allows you to syndicate your site content RSS defines an easy way to share and view headlines and content RSS files can be automatically updated RSS allows personalized views for different sites RSS is written in XML
Benefits.
Benefits
Users do not disclose their email address when subscribing to a feed No spam, viruses, phishing, and identity theft. Users do not have to send an unsubscribe request to stop receiving news The feed items are automatically sorted in that each feed URL has its own sets of entries (unlike an email box)
History
1999 2000 2003 Netscape develops RSS 0.90 Userland develops RSS 0.92 RSS 2.0 is published
Status
RSS is an informal specification, not published by a standards consortium
Syntax
RSS is XML
All XML syntax rules apply
<?xml version="1.0" encoding="ISO-8859-1" ?> <rss version="2.0"> <channel> <title>W3Schools Home Page</title> <link>http://www.w3schools.com</link> <description>Free web building tutorials</description> <item> <title>RSS Tutorial</title> <link>http://www.w3schools.com/rss</link> <description>New RSS tutorial on W3Schools</description> </item> <item> <title>XML Tutorial</title> <link>http://www.w3schools.com/xml</link> <description>New XML tutorial on W3Schools</description> </item> </channel> </rss>
Channel
The distribution channel describes the RSS feed. Mandatory: <title>
Defines the title of the channel
<link>
Defines the hyperlink to the channel
<description>
Describes the channel
<item>
Each <item> element defines an article or "story" in an RSS feed
Optional: <category>
Defines one or more categories for the feed
<copyright> Notifies about copyrighted material <image> Allows an image to be displayed when aggregators present a feed
Channel - example
<?xml version="1.0" encoding="ISO-8859-1" ?> <rss version="2.0"> <channel> <title>W3Schools Home Page</title> <link>http://www.w3schools.com</link> <description>Free web building tutorials</description> <category>Web development</category> <copyright>2006 Refsnes Data as. All rights reserved.</copyright> <image> <url>http://www.w3schools.com/images/logo.gif</url> <title>W3Schools.com</title> <link>http://www.w3schools.com</link> </image> <item> <title>RSS Tutorial</title> <link>http://www.w3schools.com/rss</link> <description>New RSS tutorial on W3Schools</description> </item> </channel> </rss>
Items
Each <item> element defines an article or "story" in an RSS feed Mandatory: <title>
Defines the title of the item
<link>
Defines the hyperlink to the item
<description>
Describes the item
Optional: <author>
Is used to specify the e-mail address of the author of an item
<comments>
Allows an item to link to comments about that item
Item - example
<?xml version="1.0" encoding="ISO-8859-1" ?> <rss version="2.0"> <channel> <title>W3Schools Home Page</title> <link>http://www.w3schools.com</link> <description>Free web building tutorials</description> <item> <title>RSS Tutorial</title> <link>http://www.w3schools.com/rss</link> <description>New RSS tutorial on W3Schools</description> <author>[email protected]</author> <comments>http://www.w3schools.com/comments</comments> <enclosure url="http://www.w3schools.com/rss/rss.mp3" length="5000" type="audio/mpeg" /> </item> </channel> </rss>
RSS in practice
RSS is used for:
News feeds
http://www.hotnews.ro/rss http://rss.cnn.com/rss/cnn_topstories.rss http://rss.slashdot.org/Slashdot/slashdot
Podcasts
http://www.manager-tools.com/feeds/mt_podcasts.xml http://www.radioguerrilla.ro/rss/podcast
Video podcasts
http://feeds.feedburner.com/tedtalks_video
References
Wikipedia
http://en.wikipedia.org/wiki/Web_feed http://en.wikipedia.org/wiki/RSS
Tutorials
http://www.w3schools.com/rss/ http://www.xul.fr/en-xml-rss.html
Feed validator
http://www.feedvalidator.org/
Acknowledgement
Slides containing the w3schools.com logo contain information taken from www.w3schools.com The use is permitted for academic purposes and these materials shall not be freely made available on the internet.
XPath
Academia Tehnic Militar, 2012
XPath
XPath
What is XPath?
XPath is a syntax for defining parts of an XML document XPath uses path expressions to navigate in XML documents XPath contains a library of standard functions XPath is a major element in XSLT XPath is a W3C recommendation
XPath uses path expressions to select nodes or nodesets in an XML document. XPath includes over 100 built-in functions. Status:
Edition 1.0, W3C Recommendation, 16.11.1999 Edition 2.0, W3C Recommendation, 23.01.2007
Terminology
Relationships
Parent Each element or attribute has one parent Children Element nodes can have zero or more children Sibling Nodes that have the same parent Ancestor A node's parent, parent's parent, etc. <bookstore> Descendant <book> <title>Harry A node's children, children's children, etc. Potter</title> <author>J K. Rowling</author>
<year>2005</year> <price>29.99</price> </book> </bookstore>
Abbreviated Syntax
XPath uses expressions to select nodes or node-sets in an XML document A very simple example:
<A> <B> <C/> </B> </A> /A/B/C
??????????????? ???????????
Predicates
Predicates are used to find a specific node or a node that contains a specific value Predicates are always embedded in square brackets There is no limit to the number of predicates in a step
<?xml version="1.0" encoding="ISO-8859-1"?> <bookstore> <book> <title lang="eng">Harry Potter</title> <price>29.99</price> </book> <book> <title lang="eng">Learning XML</title> <price>39.95</price> </book> </bookstore>
Predicates (answers)
????????????
????????????
Functions
The available operators are:
The "/", "//" and "[...]" operators, used in path expressions, as described A union operator, "|", which forms the union of two node-sets. Boolean operators "and" and "or", and a function "not()" Arithmetic operators "+", "-", "*", "div" (divide), and "mod" Comparison operators "=", "!=", "<", ">", "<=", ">="
Jones</CUSTOMER> Johnson</CUSTOMER>
//item[@price > 2*@discount] //EXAMPLE/CUSTOMER[@id='2' or @type='C'] //EXAMPLE/CUSTOMER[@id='1' and (@type='B' or @type='C')] //EXAMPLE/CUSTOMER[. !='EggHeadCafe']" //EXAMPLE/CUSTOMER[substring(@type,1,2) ='DE'] //EXAMPLE/CUSTOMER[contains(@type,'DECEA')]
XPath 2.0 was developed together with XSLT 2.0 and XQuery 1.0
Conclusions
References
Wikipedia
http://en.wikipedia.org/wiki/XPath_1.0 http://en.wikipedia.org/wiki/XPath_2.0
Cheat Sheet
Acknowledgement
Slides containing the w3schools.com logo contain information taken from www.w3schools.com The use is permitted for academic purposes and these materials shall not be freely made available on the internet.