Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

Internet Programming 3rd Year

The document is a comprehensive guide on internet programming, covering topics such as the Internet and World Wide Web (WWW), web design fundamentals, HTML, CSS, and client-server communication. It explains the roles of web browsers and servers, the structure of web pages, and the protocols involved in data transmission. Additionally, it provides insights into static and dynamic web pages, scripting languages, and essential HTML tags and attributes.

Uploaded by

Alehegn Zurbet
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Internet Programming 3rd Year

The document is a comprehensive guide on internet programming, covering topics such as the Internet and World Wide Web (WWW), web design fundamentals, HTML, CSS, and client-server communication. It explains the roles of web browsers and servers, the structure of web pages, and the protocols involved in data transmission. Additionally, it provides insights into static and dynamic web pages, scripting languages, and essential HTML tags and attributes.

Uploaded by

Alehegn Zurbet
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 389

Wollo University ,Kombolicha Institute of Technology

Department of Software Engineering


Internet programming
By Daniel Getaye(BSc.) Apr, 2022

KIOT@SE by Daniel Getaye


Chapter One
Overview of The Internet And WWW

By Daniel Getaye
BSc.In Information System
Chapter Outline
1 Chapter 1: Overview of The Internet and WWW
2 Chapter 2: Web Design and Development Fundamentals
3 Chapter 3:Cascading Style Sheets (CSS)
4 Chapter 4: Client-Side Programming –JavaScript
5 Chapter 5: Server-Side Programming –PHP and MySQL

Daniel Getaye(BSc)
Basics

Browser is software on your computer which you use to 'surf' the


internet and visit webpages
A web page is a hypertext document on the World Wide Web. Web
pages are delivered by a web server to the user and displayed in a
web browser

Daniel Getaye(BSc)
Web Essential
• Client: web browsers, used to surf the Web
• Server systems: used to supply information to these browsers
• Computer networks: used to support the browser-server
communication

Request “document A”

document A

5
Web Essential

Browser is software on your computer which you use to 'surf' the


internet and visit webpages
A web page is a hypertext document on the World Wide Web. Web
pages are delivered by a web server to the user and displayed in a
web browser

6
Internet VS. Web

 The Internet: a inter-connected computer networks, linked by


wires, cables, wireless connections, etc.
 Web: a collection of interconnected documents and other
resources.
 The world wide web (WWW) is accessible via the Internet, as
are many other services including email, file sharing, etc.

7
How does the Internet Work?
 Through communication protocols
 A communication protocol is a specification of how
communication between two computers will be carried out
• IP (Internet Protocol): defines the packets that carry blocks of data
from one node to another
• TCP (Transmission Control Protocol) and UDP (User Datagram
Protocol): the protocols by which one host sends data to another.
• Other application protocols: DNS (Domain Name Service), SMTP
(Simple Mail Transmission Protocol), and FTP (File Transmission
Protocol)

8
The Internet Protocol (IP)
 A key element of IP is IP address, a 32-bit number
 The Internet authorities assign ranges of numbers to different organizations
 IP is responsible for moving packet of data from node to node
 A packet contains information such as the data to be transferred, the source
and destination IP addresses, etc.
 Packets are sent through different local network through gateways.
 A checksum is created to ensure the correctness of the data; corrupted
packets are discarded
 IP-based communication is unreliable.

9
The Transmission Control Protocol (TCP)

HTTP, FTP, Telnet,


DNS, SMTP, etc.

TCP, UDP

IP (IPv4, IPv6)

10
TCP/IP Protocol Suites
 TCP is a higher-level protocol that extends IP to provide additional
functionality: reliable communication
 TCP adds support to detect errors or lost data and to trigger
retransmission until the data is correctly and completely received
 Connection
• Acknowledgment

11
The World Wide Web (WWW)
• WWW is a system of interlinked, hypertext documents that
runs over the Internet
• Two types of software:
• Client: a system that wishes to access the information provided by
servers must run client software (e.g., web browser)
• Server: an internet-connected computer that wishes to provide
information to others must run server software
• Client and server applications communicate over the Internet by
following a protocol built on top of TCP/IP – HyperText Transport
Protocol (HTTP)

12
Basics of WWW
 Hypertext: a format of information which allows one to move from one
part of a document to another or from one document to another
through hyperlinks
 Uniform Resource Locator (URL): unique identifiers used to locate a
particular resource on the network
 Markup language: defines the structure and content of hypertext
documents

13
Web Client: Browser
 Makes HTTP requests on behalf of the user
• Reformat the URL entered as a valid HTTP request
• Use DNS to convert server’s host name to appropriate IP address
• Establish a TCP connection using the IP address
• Send HTTP request over the connection and wait for server’s response
• Display the document contained in the response
• If the document is not a plain-text document but instead is written in
HTML.
• This involves rendering the document (positioning text, graphics,
creating table borders, using appropriate fonts, etc.)

14
Web Server
 Main functionalities:
• Server waits for connect requests
• When a connection request is received, the server creates a new process to
handle this connection
• The new process establishes the TCP connection and waits for HTTP requests
• The new process invokes software that maps the requested URL to a resource on
the server
• If the resource is a file, creates an HTTP response that contains the file in the
body of the response message.
• If the resource is a program, runs the program, and returns the output.

15
Static Web: HTML/XHTML, CSS
 HTML stands for HyperText Markup Language
• It is a text file containing small markup tags that tell the Web browser how to
display the page
 XHTML stands for eXtensible HyperText Markup Language
• It is identical to HTML 4.01
• It is a stricter and cleaner version of HTML
 CSS stands for Cascading Style Sheets
• It defines how to display HTML elements

16
26
In what sectors you join after end up this course

17
26
A front-end development required solid skills on

18
26
Scripting vs Programming language

19
26
Scripting vs Programming language

20
26
Scripting vs Programming language cont.d

21
26
Any ambiguous

Questions

22
Chapter Two
Web Design and Development Fundamentals

By Daniel Getaye
BSc. In Information System
Static Web pages
 Web Pages exist as individual files
• some file types that may be familiar
• MS WORD DOC .doc, .docx
• MS EXCEL .xls, xlsx
• ADOBE FILES: .pdf, .psd, .ai.
• Digital Camera Files .jpg, .tiff
• Examples of typical static web page files
• .htm
• .html
• A static web page will always show the same content every time
unless the actual web page file itself is edited
32
24
Static Vs Dynamic Web pages
Static Web pages
 Web development software can automate Navigation Menu maintenance,
but pages will still need to be re-published for changes to take effect.
 Static Web Page Files are published by physical transfer from the
development PC to a Web Hosting Computer
Dynamic Web pages
• A dynamic web page is constantly changing
• Example files with extensions used.
– .jsp, .php, .asp, .aspx
• can draw ever changing Content from external information
sources.
25
35
Web-related technologies:
• Web-related technologies:
– Hypertext Markup Language (HTML)
– Cascading Style Sheets (CSS)
– JavaScript and DOM scripting
– Server-side programming and database management

26
35
IDE, Editor and browser
 WHERE WE WRITE CODE :
1. Text Editor
 Sublime text
 VS code
 Notepad,notepad++
 Wordpad (In Windows OS)
2.Gedit Text Editor (Ubundu in LINUX)
2. FrontPage or Dreamweaver
 WHERE WE EXECUTE :
 Double Click that HTML File. (or)
 Right click – Open With Internet Explorer
27
35
Introduction to HTML
 HTML stands for Hyper Text Markup Language.
 Standard documents designed to be displayed in a web browser.
 HTML is used to create web pages.
 HTML is widely used language on the web.
 We can create static website by HTML only.
 HTML documents describe web pages (Static Web Page)
 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 (opening tags), the second tag is the end
tag(closing tags)
28
36
Introduction to HTML
• HTML uses tags to instruct the browser how to display the text on the
screen.
• Most tags come in pairs, one before the text on which they work, and
one immediately after.
• The first line of a file to be displayed as a Web page is <HTML> ; the
last line of the file is </HTML>
• A Web page is typically divided into two parts - the HEAD and the
BODY. The HEAD is delimited by <HEAD> and </HEAD>, the
BODY by <BODY> and </BODY>.

29
36
Introduction to HTML
 The head includes information about the document (possibly the title, author,
date of creation, software used to create the document) and the body contains
the content of the document.
 There are tags used to identify these sections:
 <head> </head> these tags surround the head of the document and come first
(before the body tags).
 <body> </body> these tags surround the content of the document.
 The head and body tags are actually required by the latest version of HTML.
 Within the title tags the document should contain a document title - this title is
typically shown in the title bar of the browser window. Document titles should
convey something useful about the content of the document.
30
36
General form of an HTML document

Opening tag <html> Displayed on


The title bar of
<head> A page!!!

Head <title> Title of the document </title>


Section </head> Title is not
A heading!!!
Body
<body>
Section Content of the page goes here
</body>

Corresponding </html>
Closing tag
Introduction to HTML
• HTML uses tags to instruct the browser how to display the text on the
screen.
• Most tags come in pairs, one before the text on which they work, and
one immediately after.
• The first line of a file to be displayed as a Web page is <HTML> ; the
last line of the file is </HTML>
• A Web page is typically divided into two parts - the HEAD and the
BODY. The HEAD is delimited by <HEAD> and </HEAD>, the
BODY by <BODY> and </BODY>.

32
40
HTML Tags

 For example: <b>, <font>,<title>, <p> etc.


 Tag usually goes with pair: an open tag (<b>) and an end tag (</b>)
Effect Code Code Used What It Does
Bold B <B>Bold</B> Bold
Italic I <I>Italic</I> Italic

 Single tag: <hr>,<br>


 Tags are NOT case sensitive

33
40
HTML commonly used character

Result Description Entity Name


Non-breaking space &nbsp;
< Less than &lt;
> Greater than &gt;
& Ampersand &amp;
“ Quotation mark &quot;
© Copyright &copy;

34
40
Sample example
<html>
O/P :
<body>

<h1>First Planet</h1>
First Planet
<h6>First Planet</h6> First Planet
</body>

</html>
 <html> .... </html> describes the web page

 <body> ..... </body> is the visible page content


35
40
Link Tags
Html Links : Html links are defined with the <a> tag

Syntax : <a href="http://www.gmil.com">Gmail</a>

Example :
<html>
<body>

<a href="http://www.gmail.com">Gmail</a>

</body>
</html>

O/P : If we click this link it goes to gmail


Gmail account

36
44
Image Tags
HTML Images :
HTML images are defined with the <img> tag.
Syntax : <img src "123.jpg" width="104" height="142" />
which supports several image formats, including Graphics Interchange Format (GIF),
Portable Network Graphics (PNG) and Joint Photographic Experts Group (JPEG).
File names for each of these types end with .gif, .png or .jpg (or .jpeg), respectively

<html>
<body>
O/P:
<img src="word.jpg" width="104" height="142" />

</body>
</html>
37
45
HTML Rule line
HTML Rules (Lines) :
The <hr /> tag is used to create an horizontal rule (line).

Example:
<html><body>
O/P :
informatics
<h3>informatics</h3>
<hr /> Our college
<h3>Our college</h3>
</body></html>

38
46
HTML Comments
HTML Comments :
Comments can be inserted in the HTML code to make it more readable and
understandable. Comments are ignored by the browser and are not displayed.

Syntax : <!-- some text →

Example : <html><body>

Plant Trees
<!--It will not be displayed here is the commnet -->
<h3>Plant Trees </h3>

</body></html>

39
46
Text Formatting Tags
Some Formatting Tags are 1,b-Bold, 2.i-Italic, 3.code-Computer code,4.sub-
Subscript & 5.sup-Superscript

<html><body>

<b>Confidence</b><br />
Write output?
<big>Hardwork</big><br />
<i>Preseverance</i><br />
<code>Samsung CRT</code><br />
This is<sub> subscript</sub><br />
This is<sup> superscript</sup>
</body></html>
40
48
HTML Style attributes
Tags Description

<center> Defines centered content

<font> Defines HTML fonts

<s> and <strike> Defines strikeout text

<u> Defines underlined text

Attributes Description

Align Defines the alignment of text

Bgcolor Defines the background color

Color Defines the text color


41
49
HTML Heading
• There are 6 heading commands.
• A number of tags are defined to be used to indicate section headings within a document.
• Typically a document contains a number of sections (chapters), and within each section are
subsections, and within subsections are sub-subsections, and so on.
• The heading tags are <h1>, <h2>, <h3>, ... <h6>,
• with H1 being the highest level heading (usually rendered the largest) and H6 the lowest
level heading.

<H1>This is Heading 1</H1>


<H2>This is Heading 2</H2>
<H3>This is Heading 3</H3>
<H4>This is Heading 4</H4>
<H5>This is Heading 5</H5>

<H6>This is Heading 6</H6>

42
50
Headings, <Hx> </Hx>
<HTML>
<HEAD>
<TITLE> Example Page</TITLE>
</HEAD>
<BODY> Heading 1
<H1> Heading 1 </H1>
<H2> Heading 2 </H2> Heading 2
<H3> Heading 3 </H3> Heading 3
<H4> Heading 4 </H4>
Heading 4
<H5> Heading 5 </H5>
Heading 5
<H6> Heading 6 </H6>
Heading 6
</BODY>
</HTML>

43
50
Paragraphs, <P> </P>
<HTML><HEAD>
<TITLE> Example Page</TITLE>
Heading 1
Paragraph 1,….
</HEAD>
<BODY></H1> Heading 1 </H1> Heading 2
<P> Paragraph 1, ….</P> Paragraph 2,….
<H2> Heading 2 </H2> Heading 3
<P> Paragraph 2, ….</P> Paragraph 3,….
<H3> Heading 3 </H3>
Heading 4
<P> Paragraph 3, ….</P>
Paragraph 4,….
<H4> Heading 4 </H4>
Heading 5
<P> Paragraph 4, ….</P>
Paragraph 5,….
<H5> Heading 5 </H5> Heading 6
<P> Paragraph 5, ….</P> Paragraph 6,….
<H6> Heading 6</H6>
<P> Paragraph 6, ….</P>
</BODY></HTML>
44
52
Break, <BR>
<HTML>
<HEAD>
<TITLE> Example Page</TITLE>
</HEAD> Heading 1
<BODY> Paragraph 1,….
<H1> Heading 1 </H1> Line 2
<P>Paragraph 1, <BR> Line 3
Line 2 <BR> Line 3 <BR>…. ….
</P>
</BODY>
</HTML>
45
53
Horizontal Rule, <HR>
 The <HR> element causes the browser to display a
horizontal line (rule) in your document.
 <HR> does not use a closing tag, </HR>.
Attribute Description Default Value
SIZE Height of the rule in pixels 2 pixels
Width of the rule in pixels or percentage of
WIDTH 100%
screen width
Draw the rule with a flat look instead of a 3D Not set
NOSHADE
look (3D look)

ALIGN Aligns the line (Left, Center, Right) Center

COLOR Sets a color for the rule (IE 3.0 or later) Not set 46
54
Horizontal Rule, <HR>
<HTML>
<HEAD>
<TITLE> Example Page</TITLE>
</HEAD>
<BODY> Heading 1
<H1> Heading 1 </H1> Paragraph 1,….
<P>Paragraph 1, <BR>
Line 2 <BR> Line 2
<HR>Line 3 <BR>
</P>
</BODY>
</HTML>
Line 3

47
62
Bold, Italic and other Character Formatting Elements
<FONT SIZE=“+2”> Two sizes bigger</FONT>
 The size attribute can be set as an absolute value from 1 to 7 or as a relative value
using the “+” or “-” sign. Normal text size is 3 (from -2 to +4).
<B> Bold </B>
<I> Italic </I>
<U> Underline </U>
 Color = “#RRGGBB” The COLOR attribute of the FONT element. E.g., <FONT
COLOR=“#RRGGBB”>this text has color</FONT>
 <PRE> Preformatted </PRE> Text enclosed by PRE tags is displayed in a mono-
spaced font. Spaces and line breaks are supported without additional elements or
special characters.

48
62
Bold, Italic and other Character Formatting Elements

<EM> Emphasis </EM> Browsers usually display this as italics.


<STRONG> STRONG </STRONG> Browsers display this as bold.
<TT> TELETYPE </TT> Text is displayed in a mono-spaced font. A
typewriter text, e.g. fixed-width font.
<CITE> Citation </CITE> represents a document citation (italics).
For titles of books, films, etc. Typically displayed in italics. (A
Beginner's Guide to HTML)

49
62
Bold, Italic and other Character Formatting Elements

<P> <FONT SIZE=“+1”> One Size Larger One Size Larger - Normal – One Size
</FONT> - Normal – Smaller
<FONT SIZE=“-1”> One Size Smaller </FONT> Bold - italics - Underlined -
<BR> Colored
<B> Bold</B> - <I> italics</I> - <U> Underlined Emphasized - Strong - Tele Type
</U> -
<FONT COLOR=“#FF0000”> Colored </FONT>
<BR>
<EM> Emphasized</EM> -
<STRONG> Strong </STRONG> -
<TT> Tele Type </TT> <BR>

50
62
Alignment
Some elements have attributes for alignment (ALIGN)
e.g. Headings, Paragraphs and Horizontal Rules.
The Three alignment values are : LEFT, RIGHT, CENTER.
<CENTER></CENTER> Will center elements.
<DIV ALIGN=“value”></DIV> Represents a division in the document and
can contain most other element type. The alignment attribute of the DIV
element is well supported.
<TABLE></TABLE> Inside a TABLE, alignment can be set for each individual
cell.

51
62
Special Characters & Symbols
Special Character Entity Name Special Character Entity Name

Ampersand &amp; & Greater-than sign &gt; >


Asterisk &lowast; ∗∗ Less-than sign &lt; <
Cent sign &cent; ¢ Non-breaking &nbsp;
space
Copyright &copy; © Quotation mark &quot; "
Fraction one qtr &frac14; ¼ Registration mark &reg; ®
Fraction one half &frac12; ½ Trademark sign &trade; ™

52
62
Additional Character Formatting Elements

<P><STRIKE> strike-through text </STRIKE></BR>

<BIG>places text in a big font </BIG><BR>

<SMALL> places text in a small font</SMALL><BR>

<SUB> places text in subscript position </SUB>


Normal
<SUP> places text in superscript style position </SUP><BR> </P>

53
62
Style Example
<html>
<h1 style="text-align:center">NATURE</h1>

<body style="background-color:yellow">

<p style="font-family:Purisa;color:red">Plant Tree</p>

<p style="font-family:times;color:red">Save Our Generation</p>

<p style="font-size:40">Value Our Environment</p>


</body> </html>

NATURE
Plant Tree
O/P :
Save Our Generation
Value Our Environment
54
62
Background
• Bgcolor
• Background
• Specifies a background-color for a HTML page.
• Specifies a background-image for a HTML
<body bgcolor="#000000"> <body page
bgcolor="rgb(0,0,0)"> <body bgcolor="black">
<body background="clouds.gif">
<body
background="http://www.w3schools.com
/clouds.gif">

55
62
HTML Table
 Tables are defined with the <table> tag.
 A table is divided into rows (with the <tr> tag),
Each row is divided into data cells (with the <td> tag). The letters td stand
for "table data," which is the content of a data cell.
 Headings in a table are defined with the <th> tag.
<table border="1">
<tr> <td>row 1, cell 1</td> row1,cell1 row1,cell2
<td>row 1, cell 2</td> </tr>
<tr> <td>row 2, cell 1</td>
<td>row 2, cell 2</td></tr> row2,cell1 row2,cell2
64
64 </table>
HTML Table

The <TABLE></TABLE> element has four sub-elements: <table border=“1”>


Table Row<TR></TR>. <tr>
Table Header <TH></TH>. <th> Column 1 header </th>
Table Data <TD></TD>. <th> Column 2 header </th>
Caption <CAPTION></CAPTION>. </tr>
The table row elements usually contain table header <tr>
elements or table data elements. <td> Row1, Col1 </td>
<td> Row1, Col2 </td>
</tr>
<tr>
<td> Row2, Col1 </td>
<td> Row2, Col2 </td>
</tr>
</table>
6
5
57
HTML Table
<table border=“1”>
<tr> Column 1 Header Column 2 Header
<th> Column 1 header </th>
<th> Column 2 header </th>
</tr> Row1, Col1 Row1, Col2
<tr>
<td> Row1, Col1 </td> Row2, Col1 Row2, Col2
<td> Row1, Col2 </td>
</tr>
<tr>
<td> Row2, Col1 </td>
<td> Row2, Col2 </td>
</tr>
</table>
58
66
Table attributes
 BGColor: Some browsers support background colors in a table.
Width: you can specify the table width as an absolute number of pixels
or a percentage of the document width. You can set the width for the
table cells as well.
Border: You can choose a numerical value for the border width, which
specifies the border in pixels.
CellSpacing: Cell Spacing represents the space between cells and is
specified in pixels.

59
66
Table attributes
CellPadding: Cell Padding is the space between the cell
border and the cell contents and is specified in pixels.
Align: tables can have left, right, or center alignment.
Background: Background Image, will be titled in IE3.0 and
above.
BorderColor, BorderColorDark.

60
66
Table Caption
A table caption allows you to specify a line of text that will appear
centered above or bellow the table.
<TABLE BORDER=1 CELLPADDING=2>
<CAPTION ALIGN=“BOTTOM”> Label For My Table </CAPTION>
The Caption element has one attribute ALIGN that can be either TOP
(Above the table) or BOTTOM (below the table).

61
66
Table Data and Table Header Attributes
 Colspan: Specifies how many cell columns of the table this cell should span.
 Rowspan: Specifies how many cell rows of the table this cell should span.
 Align: cell data can have left, right, or center alignment.
 Valign: cell data can have top, middle, or bottom alignment.
 Width: you can specify the width as an absolute number of pixels or a percentage
of the document width.
 Height: You can specify the height as an absolute number of pixels or a
percentage of the document height.

62
66
Table Data and Table Header Attributes
<TABLE BORDER=1 width=50%>
<CAPTION> <h1>Spare Parts <h1> </Caption>
<TR><TH>Stock Number</TH><TH>Description</TH><TH>List
Price</TH></TR>
<TR><TD bgcolor=red>3476-AB</TD><TD>76mm
Socket</TD><TD>45.00</TD></TR>
<TR><TD >3478-AB</TD><TD><font color=blue>78mm Socket</font>
</TD><TD>47.50</TD></TR>
<TR><TD>3480-AB</TD><TD>80mm Socket</TD><TD>50.00</TD></TR>
</TABLE>

63
66
Table Data and Table Header Attributes
<Table border=1 cellpadding =2>
<tr> <th> Column 1 Header</th> <th> Column 2 Header</th> </tr>
<tr> <td colspan=2> Row 1 Col 1</td> </tr>
<tr> <td rowspan=2>Row 2 Col 1</td>
<td> Row 2 Col2</td> </tr>
<tr> <td> Row 3 Col2</td> </tr>
</table>

Column 1 Header Column 2 Header


Row 1 Col 1

Row 2 Col 2
Row 2 Col 1
Row 3 Col 2 6
72
4
Special Things to Note about table Table
• TH, TD and TR should always have end tags.
Although the end tags are formally optional, many browsers will mess up the formatting of the table if you omit
the end tags. In particular, you should always use end tags if you have a TABLE within a TABLE -- in this
situation, the table parser gets hopelessly confused if you don't close your TH, TD and TR elements.

• A default TABLE has no borders


By default, tables are drawn without border lines. You need the BORDER attribute to draw the lines.

• By default, a table is flush with the left margin


TABLEs are plopped over on the left margin. If you want centered tables, You can either: place the table inside
a DIV element with attribute ALIGN="center".
Most current browsers also supports table alignment, using the ALIGN attribute. Allowed values are "left",
"right", or "center", for example: <TABLE ALIGN="left">. The values "left" and "right" float the table to the left or
right of the page, with text flow allowed around the table. This is entirely equivalent to IMG alignment
73
73
Special Things to Note about table Table
<TABLE BORDER width=“750”>
<TR> <TD colspan=“4” align=“center”>Page Banner</TD></TR>
<TR> <TD rowspan=“2” width=“25%”>Nav Links</TD><TD
colspan=“2”>Feature Article</TD> <TD rowspan=“2”
width=“25%”>Linked Ads</TD></TR>
<TR><TD width=“25%”>News Column 1 </TD> <TD
width=“25%”><News Column 2 </TD></TR>
</TABLE>

66
80
Table features
1. Table with a caption : 4.Cell spacing :

<caption>My Caption</caption> <table border="1" cellspacing="10">

2.Table cells that span more than 5.Add a background color or a background
one row/column : image to a table :

<th colspan="2">Telephone</th> <table border="1" bgcolor="red">


<th rowspan="2">Telephone:</th>

3.Cell padding :

<table border="1" cellpadding="10">

67
80
HTML List
HTML supports ordered, unordered and definition lists.

 Ordered Lists :
An ordered list is also a list of items. The list items are marked with numbers.

An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.

 Unordered Lists :
An unordered list is a list of items. The list items are marked with bullets (typically small
black circles).

An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.

68
80
HTML List

• Unordered list • Ordered list


– Code: – Code:
<ol>
<ul>
<li>Coffee</li>
<li>Coffee</li> <li>Milk</li>
<li>Milk</li> </ol>
</ul> Output:
Output: 1. Coffee
2. Milk
• Coffee
• Milk

69
80
HTML List

TYPE Numbering Styles


1 Arabic numbers 1,2,3, ……
a Lower alpha a, b, c, ……
A Upper alpha A, B, C, ……
i Lower roman i, ii, iii, ……
I Upper roman I, II, III, ……

70
80
HTML List
 You can specify a starting number for an ordered
list.
<OL TYPE =“i”>
<LI> List item …</LI>
<LI> List item …</LI>
</OL>
<P> text ….</P>
<OL TYPE=“i” START=“3”>
<LI> List item …</LI>
</OL>

71
80
HTML List
 DL: Definition List. This kind of list is different from the others. Each item in a DL
consists of one or more Definition Terms (DT elements), followed by one or
more Definition Description (DD elements).
<DL>
<DT> HTML </DT>
<DD> Hyper Text Markup Language </DD>
<DT> DOG </DT>
<DD> A human’s best friend!</DD>
</DL>

HTML
Hyper Text Markup Language
DOG
A human’s best friend!

72
80
Nesting Lists
 You can nest lists by inserting a UL, OL, etc., inside a list item (LI).
EXample
<UL TYPE = “square”>
<LI> List item …</LI>
<LI> List item …
<OL TYPE=“i” START=“3”>
<LI> List item …</LI>
<LI> List item …</LI>
<LI> List item …</LI>
<LI> List item …</LI>
<LI> List item …</LI>
</OL>
</LI>
<LI> List item …</LI>
</UL> 81
81
What is the output of these source code?

<H1 ALIGN="CENTER">SAFETY TIPS FOR CANOEISTS</H1>


<OL TYPE=“a” START=“2”>
<LI>Be able to swim </LI>
<LI>Wear a life jacket at all times </LI>
<LI>Don't stand up or move around. If canoe tips,
<UL>
<LI>Hang on to the canoe </LI>
<LI>Use the canoe for support and </LI>
<LI>Swim to shore
</UL> </LI>
<LI>Don't overexert yourself </LI>
<LI>Use a bow light at night </LI>
</OL>
82
82
What is the output of these source code?

83
75
What is the output of these source code?
<H1 ALIGN="CENTER">SAFETY TIPS FOR CANOEISTS</H1>
<OL TYPE="a" START="2">
<LI>Be able to swim </LI>
<LI>Wear a life jacket at all times </LI>
<LI>Don't stand up or move around. If canoe tips,
<UL>
<LI>Hang on to the canoe </LI>
<LI>Use the canoe for support
<OL type="I" start="4">
<LI> Be careful </LI>
<LI> Do not look around</LI>
</LI> </OL>
<LI>Swim to shore
</UL> </LI>
<LI>Don't overexert yourself </LI>
<LI>Use a bow light at night </LI>
</OL> 84
76
What is the output of these source code?

85
77
HTML List
Definition Lists :
 A definition list is not a list of single items. It is a list of items (terms), with a description of each
item (term).

 A definition list starts with a <dl> tag (definition list). Definition List :
 Each term starts with a <dt> tag (definition term).
Success
 Each description starts with a <dd> tag (definition description). Fail First,
Happy
Smile Always
Unordered List : Ordered List :
 ThinkPositve
1.Fail
 Never Depressed
2.Work Hard
 Keep Smiling
3.Win
86
86
4.Teach
HTML With images
<IMG>This element defines a graphic image on the page.
Image File (SRC:source): This value will be a URL (location of the image) E.g.
http://www.domain.com/dir/file.ext or /dir/file.txt.

Alternate Text (ALT): This is a text field that describes an image or acts as a
label. It is displayed when they position the cursor over a graphic image.
Alignment (ALIGN): This allows you to align the image on your page.
<img src=“abc,jpg alt=“’image is not foud’ align=“Left”>

79
89
HTML With images
Width (WIDTH): is the width of the image in pixels.
Height (HEIGHT): is the height of the image in pixels.
Border (BORDER): is for a border around the image, specified in pixels.
HSPACE: is for Horizontal Space on both sides of the image specified in pixels. A
setting of 5 will put 5 pixels of invisible space on both sides of the image.
VSPACE: is for Vertical Space on top and bottom of the image specified in pixels.
A setting of 5 will put 5 pixels of invisible space above and bellow the image.

80
89
More on images
<IMG SRC=“jordan.gif“ border=4>
<IMG SRC=" jordan.gif" width="60" height="60">
<IMG SRC=“jordan.gif" ALT="This is a text that goes with the image">
<IMG SRC=" jordan.gif “ Hspace="30" Vspace="10" border=20>
< IMG SRC =" jordan.gif“ align="left">
blast blast blast blast blast

81
89
HTML layout
 A part of this page is formatted with two columns, like a newspaper page.

 The trick is to use a table without borders, and maybe a little extra cell-
padding.

 No matter how much text you add to this page, it will stay inside its
column borders.

82
89
HTML Frames
 A framed page is actually made up of multiple HTML pages.
 There is one HTML document that describes how to break up the single browser
window into multiple windowpanes. Each windowpane is filled with an HTML
document.

 For Example to make a framed page with a windowpane on the left and one on the
right requires three HTML pages. Doc1.html and Doc2.html are the pages that
contain content.

 Frames.html is the page that describes the division of the single browser window
into two windowpanes.
91
91
HTML frames
With frames, you can display more than one HTML document in the same
browser window.

Each HTML document is called a frame, and each frame is independent of the
others.

The Frameset Tag

* The <frameset> tag defines how to divide the window into frames

* Each frameset defines a set of rows or columns

* The values of the rows/columns indicate the amount of screen area each
row/column will occupy

92
84
HTML frames page architecture
A <FRAMESET> element is placed in the <HTML>
html document before the <BODY> <HEAD>
element. <TITLE> Framed Page </TITLE>
The <FRAMESET> describes the amount <FRAMeSET COLS=“23%,77%”>
of screen real estate given to each <FRAME SRC=“Doc1.html”>
windowpane by dividing the screen into
<FRAME SRC=“Doc2.html”>
ROWS or COLS.
</FRAMeSET >
The <FRAMESET> will then contain
<FRAME> elements, one per division of </HEAD>
the browser window. </HTML>
Note: Because there is no BODY
container, FRAMESET pages can't have
background images and background
colors associated with them.
93
85
Frames

FRAMESET COLS=”23%, 77%”


Doc1.html Doc2.html FRAME FRAME

NAME= NAME=right_pane
left_pane SRC= Doc2.html
SRC=Doc1.h
tml

Doc1.html Doc2.html

86
95
Vertical and horizontal frameset
<html>
<frameset cols="30%,40%,30%">
<frame src="frame_a.htm">
<frame src="frame_b.htm">
<frame src="frame_c.htm">
</frameset>
</html>

<html>
<frameset rows="30%,40%,30>
<frame src="frame_a.htm">
<frame src="frame_b.htm">
<frame src="frame_c.htm">
</frameset>
</html>
87
95
Frame

 <FRAME>: This element defines a single frame within a frameset. There will
be a FRAME element for each division created by the FRAMESET element.
This tag has the following attributes:
SRC: Required, as it provides the URL for the page that will be displayed in the
frame.
NAME: Required for frames that will allow targeting by other HTML
documents.
Works in conjunction with the target attribute of the <A>, <AREA>, <BASE>,
and <FORM> tags.

96 96
Frame attributes

 MARGINWIDTH: Optional attribute stated in pixels. Determines horizontal


space between the <FRAME> contents and the frame’s borders.
 MARGINHEIGHT: Optional attribute stated in pixels. Determines vertical
space between the <FRAME> contents and the frame’s borders.
 SCROLLING: Displays a scroll bar(s) in the frame. Possible values are:
1. Yes – always display scroll bar(s).
2. No – never display scroll bar(s).
3. Auto – browser will decide based on frame contents.
97 97
By default: scrolling is auto.
No Frame
<NOFRAMES>: Frame – capable browsers ignore all
HTML within this tag including the contents of the BODY
element. This element does not have any attributes.
<HTML>
<HEAD>
<TITLE> Framed Page </TITLE>
</HEAD>

90 100
Compound FRAMESET Divisions
<NOFRAMES>: Frame – capable browsers ignore all
HTML within this tag including the contents of the BODY
element. This element does not have any attributes.
<HTML>
<HEAD>
<TITLE> Framed Page </TITLE>
</HEAD>

91 100
Compound FRAMESET Divisions
<NOFRAMES>: Frame – capable browsers ignore all
HTML within this tag including the contents of the BODY
element. This element does not have any attributes.
<HTML>
<HEAD>
<TITLE> Framed Page </TITLE>
</HEAD>

92 100
Compound FRAMESET Divisions
<html> <noframes>
<head>
<title> Compound Frames Page</title> <p>
</head> Default message
<body> </p>
<frameset rows=“120,*”>
<frame src=“banner_file.html” name”banner”> </noframes>
<frameset cols=“120,*”> </frameset>
<frame src=“links_file.html” name=“links”> </frameset>
<frame src=“content_file.html” name=“content”>
</body> </head>
</html>

101
Compound FRAMESET Divisions

Banner File

Links
File Contents File

You may want to create a frames design with a combination of rows and
columns. 102
95 103
96 103
97 103
What is the output?

<FRAMESET ROWS="*, 2*, *" COLS="2*, *">


<FRAME SRC=“”>
<FRAME SRC=“”>
<FRAME SRC=“”>
<FRAME SRC=“”>
<FRAME SRC=“”>
<FRAME SRC=“”>
</FRAMESET>

98 103
HTML Forms

To insert a form we use the <FORM></FORM> tags. The rest of the form
elements must be inserted in between the form tags.
<HTML> <HEAD>
<TITLE> Sample Form</TITLE>
</HEAD>
<BODY BGCOLOR=“FFFFFF”>
<FORM ACTION = http://www.xnu.com/formtest.asp>
<P> First Name: <INPUT TYPE=“TEXT” NAME=“fname” MAXLENGTH=“50”>
</P>
<P> <INPUT TYPE=“SUBMIT” NAME=“fsubmit1” VALUE=“Send Info”> </P>
</FORM>
</BODY> </HTML>
107 107
<FORM> element attributes
ACTION: is the URL of the CGI (Common Gateway Interface) program that is
going to accept the data from the form, process it, and send a response back to
the browser.
METHOD: GET (default) or POST specifies which HTTP method will be used to
send the form’s contents to the web server. The CGI application should be
written to accept the data from either method.
NAME: is a form name used by VBScript or JavaScripts.
TARGET: is the target frame where the response page will show up.
100 108
<FORM> element attributes
Form elements have properties:
Text boxes,
 Password boxes,
 Checkboxes,
Option(Radio) buttons,
 Submit,
Reset,
 File,
Hidden and Image.
The properties are specified in the TYPE Attribute of the HTML element
<INPUT></INPUT>.

101 108
Abebe Alemu

Wollo university

102
<INPUT> Element’s Properties
<INPUT> Element’s Properties

TYPE= Type of INPUT entry field.

NAME = Variable name passed to CGI application


VALUE= The data associated with the variable
name to be passed to the CGI application

CHECKED= Button/box checked

SIZE= Number of visible characters in text field

MAXLENGHT= Maximum number of characters


accepted.

103
HTML Forms
HTML Forms are used to select different kinds of user input.

 A form is an area that can contain form elements.

 Form elements are elements that allow the user to enter information like,

1. text fields,

2. textarea fields,
3.drop-down menus,

4.radio buttons,

5. checkboxes,

6. Action Attribute and the Submit Button,etc.


112
104
HTML Forms
Text Fields:

Text fields are used when you want the user to type letters, numbers, etc. in a
form.Example :

<form>

First name: <input type="text" name="firstname" /> <br />

Last name: <input type="text" name="lastname" />

</form>
First name :

OUTPUT :
Last name :
113
105
Working with forms
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html xmlns="http://www.w3.org/1999/xhtml">
<head> <title>Web Tech: Chapter 1 - Introduction to HTML </title>
<meta content ="text/html"; http-equiv = "Content-type">
<meta name ="keywords" content ="registration, admission, employee">
<script language=“ " runat = "“> </script>
<style> </style> </head>
<body>
<form action="Default.aspx" method ="get">
<table><tr><td>first name:</td><td><input type = "text" name ="firstname"/></td></tr>
<tr><td>last name:</td><td><input type ="text" name = "lastname"/></td></tr>
<tr><td>Gender:</td> <td>
<input id="Radio1" name ="radio1" type="radio" checked ="checked">Male</input>
<input id="Radio2" name ="radio1" type="radio">Female</input></td></tr>
<tr><td>Latest Education:</td> <td><select id="Edu">
<option value="BSC">BSc</option> <option value ="BA"> BA</option>
<option value ="MSC">MSc</option><option value ="MA">MA</option>
<option value ="Certificate">Professional Certificate</option>
<option value ="oth">others</option>
</select></td></tr>
<tr><td></td><td><input name ="submit" type = "submit" value ="Submit" / ></ td> </tr>
</table>
</form> 114
</11b4ody>
</html>
RADIO & CHECK BOX
Radio Buttons :

<form> Male
<input type="radio" name="sex" value="male" /> Male <br />
Female
<input type="radio" name="sex" value="female" /> Female

</form>
Bike
Checkboxes :
Car
<form>

Bike: <input type="checkbox" name="vehicle" value="Bike"/> <br />

Car: <input type="checkbox" name="vehicle" value="Car"/><br />

</form> 115
107
RADIO button
• Used when you want the user to select one of a limited number of
choices.
<form>
<table>
<tr><td>Gender:</td>
<td>
<input id="Radio1" name ="radio1" type="radio" checked= "checked">
Male</input> </td>
<td>
<input id="Radio2" name ="radio1" type="radio"> Female </input>
</td></tr></table>
</form>

10
8
116
Form submission
• When user clicks on the “ Submit” button, the content of the
form is sent to server side page.
<form name="input" action="html_form_action.asp"
method="get">
Username: <input type="text" name="user"/><br>
Password: <input type ='password' id ="pwd" name ='pwdd'/><br>
<input type="submit" value="Submit">
</form>

10
9
116
More on check box
• Used when you want the user to select one or more options of a limited
number of choices.
<form> Mark all you use for travel: <br / >
<input type="checkbox" name="bike" value ="bike"> Bike </input>
<br>
<input type="checkbox" name="car" value="car"> Car </input>
<br>
<input type="checkbox" name="Publictrans" value="PublicTrans"> Public Transport
</input>
</form>

110
116
Form Action Attribute
Action Attribute and the Submit Button :

 When the user clicks on the "Submit" button, the content of the form is sent to the server.

 The form's action attribute defines the name of the file to send the content to.

 It depends on PHP File.

<form name="input" action="html_form_submit.php/jsp/asp" method="get">

Username:<input type="text" name="user"/>

<input type="submit" value="Submit" />


Username :
</form>
Submit

111
116
More one forms
 The best way to pass data from client to server

 Can contain form elements such as

o Input elements

o Select lists

o Buttons

 Wrapped inside a <form> tag

<form action=“.." method="GET">


<fieldset>
<legend>Client Info:</legend>
<label for="txtName">Name: </label><input type="text" id="txtName" name="txtName" /><br />
<input type="submit" value="Submit" name="btnSubmit" name="btnSubmit" />
120
</fieldset>
</form>
120
TextBox
Text boxes: Used to provide input fields for text, phone numbers, dates, etc.

<INPUT TYPE= " TEXT " >


Browser will display
Textboxes use the following attributes:
TYPE: text.
SIZE: determines the size of the textbox in characters. Default=20 characters.
MAXLENGHT : determines the maximum number of characters that the field will
accept.
NAME: is the name of the variable to be sent to the CGI application.

VALUE: will display its contents as the default value. 121 121
TextBox Example
<TITLE>Form_Text_Type</TITLE>
</HEAD> <BODY>
<h1> <font color=blue>Please enter the following bioData</font></h1>
<FORM name="fome1" Method= " get " Action= " URL " >
First Name: <INPUT TYPE="TEXT" NAME="FName"
SIZE="15" MAXLENGTH="25"><BR>
Last Name: <INPUT TYPE="TEXT" NAME="LName"
SIZE="15" MAXLENGTH="25"><BR>
Nationality: <INPUT TYPE="TEXT" NAME="Country"
SIZE="25" MAXLENGTH="25"><BR>
The Phone Number: <INPUT TYPE="TEXT" NAME="Phone"
SIZE="15" MAXLENGTH="12"><BR>
</FORM> </BODY> </HTML>

122 114
Output

123 115
Password

 Password: Used to allow entry of passwords.


<INPUT TYPE= " PASSWORD " >
Browser will display
Text typed in a password box is starred out in the browser
display.
Password boxes use the following attributes:
 TYPE: password.
 SIZE: determines the size of the textbox in characters.
 MAXLENGHT: determines the maximum size of the password in characters.
 NAME: is the name of the variable to be sent to the CGI application.
 VALUE: is usually blank.
124 124
Password
<HTML><HEAD>
<TITLE>Form_Password_Type</TITLE></HEAD>
<BODY>
<h1> <font color=red>To Access, Please
enter:</font></h1>
<FORM name="fome2" Action="url" method="get">
User Name: <INPUT TYPE="TEXT" Name="FName“ SIZE="15" MAXLENGTH="25">
<BR>
Password: <INPUT TYPE="PASSWORD" NAME="PWord" value="" SIZE="15”
MAXLENGTH="25"><BR>
</FORM></BODY> </HTML>

125 125
 Hidden: Used to send data to the CGI application that you don’t want the web surfer
to see, change or have to enter but is necessary for the application to process the
form correctly.
<INPUT TYPE=“HIDDEN”>
Nothing is displayed in the browser.
Hidden inputs have the following attributes:
 TYPE: hidden.
 NAME: is the name of the variable to be sent to the CGI application.
 VALUE: is usually set a value expected by the CGI application.

118 126
Check Box

 Check Box: Check boxes allow the users to select more than one option.
<INPUT TYPE=“CHECKBOX”>
Browser will display

Checkboxes have the following attributes:


 TYPE: checkbox.
CHECKED: is blank or CHECKED as the initial
status.
NAME: is the name of the variable to be sent to the
CGI application.
 VALUE: is usually set to a value.

119
<HTML> <HEAD><TITLE>CheckBoxType</TITLE> </HEAD>
<BODY>
<h1> <font color=green>Please check one of the following</font></h1>
<FORM name="fome3" Action="url" method="get">
<font color=red> Select Country: </font><BR>
jordan:<INPUT TYPE="CheckBox" Name="country" CHECKED><BR>
Yemen<INPUT TYPE="CheckBox" Name="country"><BR>
Qatar:<INPUT TYPE="CheckBox" Name="country"><BR> <BR>
<font color=blue>Select Language:</font><BR>
Arabic:<INPUT TYPE="CheckBox" Name="language" CHECKED><BR>
English:<INPUT TYPE="CheckBox" Name="language"><BR>
French:<INPUT TYPE="CheckBox" Name="language"> <BR></FORM>
</BODY></HTML>
120
Radio Button
 Radio Button: Radio buttons allow the users to select
only one option.
<INPUT TYPE=“RADIO”>
Browser will display

Radio buttons have the following attributes:


 TYPE: radio.
 CHECKED: is blank or CHECKED as the initial
status. Only one radio button can be checked
 NAME: is the name of the variable to be sent to the
CGI application.
 VALUE: usually has a set value.

121
<HTML> <HEAD><TITLE>CheckBoxType</TITLE> </HEAD>
<BODY>
<h1> <font color=green>Please check one of the
following</font></h1>
<FORM name="fome3" Action="url" method="get">
<font color=red> Select Country: </font><BR>
jordan:<INPUT TYPE= "RADIO" Name="country" CHECKED><BR> Yemen<INPUT
TYPE="RADIO " Name="country"><BR> Qatar:<INPUT TYPE="RADIO"
Name="country"><BR> <BR>
<font color=blue>Select Language:</font><BR>
Arabic:<INPUT TYPE="RADIO" Name="language" CHECKED><BR> English:<INPUT
TYPE=" RADIO " Name="language"><BR> French:<INPUT TYPE=" RADIO "
Name="language"> <BR></FORM>
</BODY></HTML>
130 130
<HTML><HEAD>
<TITLE>RADIOBox</TITLE> </HEAD>
<BODY>
Form #1:
<FORM>
<INPUT TYPE="radio" NAME="choice" VALUE="one"> Yes.
<INPUT TYPE="radio" NAME="choice" VALUE="two"> No.
</FORM>
<HR color=red size="10" >
Form #2:
<FORM>
<INPUT TYPE="radio" NAME="choice" VALUE="three" CHECKED> Yes.
<INPUT TYPE="radio" NAME="choice" VALUE="four"> No.
</FORM> 131
131
</BODY></HTML>
Output

132 132
Push Button

 Push Button: This element would be used with


JavaScript to cause an action to take place.
<INPUT TYPE=“BUTTON”>
Browser will display

Push Button has the following attributes:


 TYPE: button.
 NAME: is the name of the button to be used
in scripting.
 VALUE: determines the text label on the button.

133 133
<DIV align=center><BR><BR>
<FORM>
<FONT Color=red>
<h1>Press Here to see a baby crying:<BR>
<INPUT TYPE="button" VALUE="PressMe"><BR><BR>
<FONT Color=blue>
Click Here to see a baby shouting:<BR>
<INPUT TYPE="button" VALUE="ClickMe" > <BR><BR>
<FONT Color=green>
Hit Here to see a baby eating:<BR>
<INPUT TYPE="button" VALUE="HitME" > <BR><BR>
<FONT Color=yellow>
</FORM></DIV>
134 134
Submit Button
 Submit: Every set of Form tags requires a Submit button. This is the element
causes the browser to send the names and values of the other elements to the CGI
Application specified by the ACTION attribute of the FORM element.
<INPUT TYPE=“SUBMIT”>
The browser will display
Submit has the following attributes:
 TYPE: submit.
 NAME: value used by the CGI script for processing.
 VALUE: determines the text label on the button, usually Submit Query.

127 135
<FORM Action="URL" method="get">
First Name: <INPUT TYPE="TEXT" Size=25 name="firstName"><BR>
Family Name: <INPUT TYPE="TEXT" Size=25 name="LastName"><BR>
<BR>
<FONT Color=red>
Press Here to submit the data:<BR>
<INPUT TYPE="submit" VALUE="SubmitData " >
</FORM>

128 135
Reset Button
• Reset: It is a good idea to include one of these for each form where
users are entering data. It allows the surfer to clear all the input in
the form.

• <INPUT TYPE=“RESET”>

• Browser will display



• Reset buttons have the following attributes:
• TYPE: reset.
• VALUE: determines the text label on the button, usually Reset.

137 137
<FORM Action="URL" method="get">
First Name: <INPUT TYPE="TEXT" Size=25 name="firstName"> <BR>
Family Name: <INPUT TYPE="TEXT" Size=25
name="LastName"><BR>
<BR>
<FONT Color = red>
<STRONG><font size=5>Press Here to submit the
data:</font></STRONG><BR>
<INPUT TYPE="submit" VALUE="SubmitData">
<INPUT TYPE="RESET" VALUE="Reset">
</FORM>
130 138
131 138
Image Submit Button

 Image Submit Button: Allows you to substitute an image for the standard
submit button.

<INPUT TYPE=“IMAGE” SRC=“jordan.gif”>

Image submit button has the following attributes:


 TYPE: Image.
 NAME: is the name of the button to be used in scripting.
 SRC: URL of the Image file.

132 138
File
• File Upload: You can use a file upload to allow surfers to upload files to your web
server.
• <INPUT TYPE=“FILE”>
• Browser will display

• File Upload has the following attributes:


• TYPE: file.
• SIZE: is the size of the text box in characters.
• NAME: is the name of the variable to be sent to the
CGI application.
• MAXLENGHT: is the maximum size of the input in the
textbox in characters.
141 141
<BODY bgcolor=lightblue>
<form>
<H3><font color=forestgreen>
Please attach your file here to for uploading to
My <font color =red>SERVER...<BR>

<INPUT TYPE="File" name="myFile" size="30">

<INPUT TYPE="Submit" value="SubmitFile">


</form>
</BODY>
142 142
Other Elements used in Forms

 <TEXTAREA></TEXTAREA>: is an element that allows for free form text


entry.

Browser will display

Textarea has the following attributes:


 NAME: is the name of the variable to be sent to the CGI application.
 ROWS: the number of rows to the textbox.
 COLS: the number of columns to the textbox.

143 143
<BODY bgcolor=lightblue>
<form>
<TEXTAREA COLS=40 ROWS=20 Name="comments" >
From observing the apathy of those
about me during flag raising I
concluded that patriotism if not
actually on the decline is at least
in a state of dormancy.
Written by Khaled Al-Fagih
</TEXTAREA>:
</form>
</BODY>
144 144
Other Elements used in Forms

 The two following examples are <SELECT></SELECT> elements,


where the attributes are set differently.
The Select elements attributes are:
 NAME: is the name of the variable to be sent to the CGI application.
 SIZE: this sets the number of visible choices.
 MULTIPLE: the presence of this attribute signifies that the user can
make multiple selections. By default only one selection is allowed.

145 145
<BODY bgcolor=lightblue>
<form>
Select the cities you have visited:
<SELECT name=“list” size=5>
<option> London</option>
<option> Tokyo</option>
<option> Paris</option>
<option> New York</option>
<option> LA</option>
<option> KL</option>
</SELECT>
</form>
146
</BODY> 146
</HEAD>
<BODY>
<h2><font color=blue>What type of Computer do you have?</font><h2>
<FORM>
<SELECT NAME="ComputerType" size=4>
<OPTION value="IBM" SELECTED> IBM</OPTION>
<OPTION value="INTEL"> INTEL</OPTION>
<OPTION value=" Apple"> Apple</OPTION>
<OPTION value="Compaq"> Compaq</OPTION>
</SELECT>
</FORM></BODY></HTML>
147 147
<HEAD> <TITLE>SELECT with Mutiple </TITLE> </HEAD>
<BODY>
<h2><font color=blue>What type of Computer do you
have?</font><h2>
<FORM>
<SELECT NAME="ComputerType" size=5 multiple>
<OPTION value="IBM" > IBM</OPTION>
<OPTION value="INTEL"> INTEL</OPTION>
<OPTION value=" Apple"> Apple</OPTION>
<OPTION value="Compaq" SELECTED> Compaq</OPTION>
<OPTION value=" other"> Other</OPTION>
</SELECT>
</FORM></BODY></HTML>
148 148
149 149
More one forms
• Used when you want user to respond with one specific answer
with choices you given.
Latest Education:<br>
<select id="Edu">
<option value="BSC">BSc</option>
<option value ="BA">BA</option>
<option value ="MSC">MSc</option>
<option value ="MA">MA</option>
<option value ="Certificate">Professional Certificate</option>
<option value ="oth">others</option>
</select>
The SELECT and OPTION tags can be used to create pull-down menus and scrolling lists of choices. The
SELECT tag must include a NAME attribute (this is the name of the form field sent by the browser). Between
150
t1h5e0 <SELECT> tag and the corresponding end tag </SELECT> there can be number of OPTION tags
Field set and legends
• The FIELDSET element allows authors to group thematically related
controls and labels.
Syntax:
<FIELDSET> legend-definition
field-definition* </FIELDSET>
Where:
<LEGEND> Content </LEGEND>

143
152
Form Submission methods
• The method attribute of the FORM element specifies the HTTP
method used to send the form to the processing agent.
• This attribute may take two values:
 get: the form data set is appended to the URI specified by the action
attribute (with a question-mark ("?") as separator) and this new URI is sent
to the processing agent.
 post: the form data set is included in the body of the form and sent to the
processing agent.

144
152
Form Submission methods
• A successful control is "valid" for submission. Every successful control has its control name paired with its current
value as part of the submitted form data set. A successful control must be defined within a FORM element
and must have a control name.
• Notice:
– Controls that are disabled cannot be successful.
– If a form contains more than one submit button, only the activated submit button is successful.
– All "on" checkboxes may be successful.
– For radio buttons that share the same value of the name attribute, only the "on" radio button may be
successful.
– For menus, the control name is provided by a SELECT element and values are provided by OPTION
elements. Only selected options may be successful. When no options are selected, the control is not
successful and neither the name nor any values are submitted to the server when the form is submitted.
– The current value of a file select is a list of one or more file names. Upon submission of the form, the
contents of each file are submitted with the rest of the form data. The file contents are packaged
according to the form's content type. 145
153
– The current value of an object control is determined by the object's implementation.
Processing form data
• When the user submits a form (e.g., by activating a submit button), the user agent processes it as follows.
• Step one: Identify the successful controls
• Step two: Build a form data set
– A form data set is a sequence of control-name/current-value pairs constructed from successful controls
• Step three: Encode the form data set
– The form data set is then encoded according to the content type specified by the enctype attribute of the FORM
element.
• Step four: Submit the encoded form data set
– Finally, the encoded data is sent to the processing agent designated by the action attribute using the protocol specified
by the method attribute.
• Notice, this specification does not specify all valid submission methods or content types that may be used with forms.
However, HTML 4 user agents support the following cases:
– If the method is "get" and the action is an HTTP URI, the user agent takes the value of action, appends a `?' to it, then
appends the form data set, encoded using the "application/x-www-form-urlencoded" content type. The user agent then
traverses the link to this URI. In this scenario, form data are restricted to ASCII codes.
– If the method is "post" and the action is an HTTP URI, the user agent conducts an HTTP "post" transaction using the
value of the action attribute and a message created according to the content type specified by the enctype attribu1t5e.4
154
Form Content type
• application/x-www-form-urlencoded
– This is the default content type. Forms submitted with this content type must be encoded as
follows:
• Control names and values are escaped.
• Space characters are replaced by `+', and reserved characters are escaped: non-alphanumeric characters are
replaced by `%HH', and two hexadecimal digits (HH) represent the ASCII code of the character. Line
breaks are represented as "CR LF" pairs (i.e., `%0D%0A').
– The control names/values are listed in the order they appear in the document. The name is
separated from the value by `=' and name/value pairs are separated from each other by `&'.
• multipart/form-data
– It should be used for submitting forms that contain files, non-ASCII data, and binary data.
– A "multipart/form-data" message contains a series of parts, each representing a successful
control.
– Each part is expected to contain:
• a "Content-Disposition" header whose value is "form-data".
• a name attribute specifying the control name (encoded in non-ASCII character sets) of the corresponding
control.
155
155
Website structure /web concept
• It is the framework of the site in which the information or content is
presented.
• The structure of the site is composed of the different sections of the website
and navigation within those sections. It is a framework that shapes the site and
defines navigation scheme.
• A website is composed of three main areas: the homepage, the main sections
and the subsections
Home
page

Main Main Main


Section section2 section3

Sub
section
156
156
Cont..d
<table border="0" width="100%" cellpadding="10">
<tr>
<td width="50%" valign="top">
This is the Time to save Our Earth to Our Future Generation. So
everybody shoud be a Volunteer.
</td>
<td width="50%" valign="top">
For smooth relationship between to us & nature We should do some
activities to Preserve our Earth.
</td>
</tr> </table>

This is the Time to save Our Earth to For smooth relationship between to us &
Our Future Generation.So nature We should do some
everybody shoud be a Volunteer. activities to Preserve our Earth.

157
149
Cont..d

150
159
Website structure
• It is like the skeleton or nervous system in the human body. Every joint or
synapse (representing a page) is connected together into a network of links.

A general rule of thumb is that it should take no more than threeclicks for a
visitor to find what they are looking for.
151
160
Website structure
• Home page of a website
– It should tell visitors what your site is about. The homepage should
answer the questions Who, What, and Why about the sites purpose.
– It should also provide an sitemap or table of contents and guide visitors to
the information they need.
– It should not contain a lot of text

152
160
Website structure
• Main sections
– they will form the backbone of the navigation system a collection of
links that provide access to the main content.
– These pages should provide one click access to the subsections.
– Each main section should cover a specific subject or data base which is
focused on a single topic
• Subsections
– These represent the main section of the website
– Each should contains all of the important data related to the main
section

153
160
Chapter Three
Cascading Style Sheets (CSS)

By Daniel Getaye
BSc. In Information System
Overview CSS
• are a way to control the look and feel of your HTML documents in
an organized and efficient manner.
• The principle of Cascading Style Sheets (CSS) has roots in
Standardized Generalized Markup Language (SGML) from the 1980s.
• Its goals are to create a consistent look across many web-pages and
to separate structure from presentation so you can provide
different style sheets for printing, browsing, or other scenarios
• With CSS you will be able to:
– Add new looks to your old HTML
– Completely restyle a web site with only a few changes to your CSS code
– Use the "style" you create on any webpage you wish!
164
155
Overview CSS
• Cascading style sheets provide a means to apply a presentation to
an HTML structure by defining how HTML elements are displayed.
• By using CSS, you can set background and fore-ground colors,
margins, borders, fonts, positions, and much more. You have
creative control of the HTML elements, so you can decide what the
elements look like and where they display on the screen.
• A style is a rule that describes how to format a specific part of an
HTML document.
• A style sheet is a set of style rules.
165
156
Overview CSS
• Cascading style sheets provide a means to apply a presentation to
an HTML structure by defining how HTML elements are displayed.
• By using CSS, you can set background and fore-ground colors,
margins, borders, fonts, positions, and much more. You have
creative control of the HTML elements, so you can decide what the
elements look like and where they display on the screen.
• A style is a rule that describes how to format a specific part of an
HTML document.
• A style sheet is a set of style rules.
157
170
Cont..d
• You can create
– a style and apply it to many elements based on a selector.
– A style and use a selector to locate and select elements based on tag
name, class name, ID, and more.
– a style that works with images, and you can create a style that works
only with hyperlinks.
– a named style that you can apply to any element.
• “ the reusability is powerful”

158
170
Defining CSS
• CSS code is not written the same way as HTML code is. This makes sense
because CSS is not HTML, but rather a way of manipulating existing HTML.
• A style rule, or style, is composed of two parts:
– the selector, which locates the elements in the HTML document that will be
styled, and
– the declaration block, which contains the formatting instructions (declarations).
• A declaration comprises
– a CSS property,
– followed by a colon,
– followed by a value.
• Multiple declarations are always separated with a semicolon.

159
170
Cont..d
• You can create
– a style and apply it to many elements based on a selector.
– A style and use a selector to locate and select elements based on tag
name, class name, ID, and more.
– a style that works with images, and you can create a style that works
only with hyperlinks.
– a named style that you can apply to any element.
• “ the reusability is powerful”

160
170
Cont..d
⦁ General C S S Format:
“Selector" { declaration;}
" selector" { "CSS Property" : "Value" ; }

body { background-color: white; color: gray; }


⦁ HTML element we wanted to manipulate:
body{ :;}
⦁ Then we chose the CSS attribute color.
body {background-color ;}
⦁ Next we choose the font color to be white. –
body {background-color :white;}
161
170
Cont..d
CSS selectors
• are the heart and soul of CSS.
• They define which HTML elements you are going to be manipulating with
CSS code and
• The selector name creates a direct relationship with the HTML tag you
want to edit.
Example:
• If you wanted to change the way a paragraph tag behaved, the CSS code
would look like:
p { PROPERTY: VALUE }
• The above example is a template that you can use whenever you are
manipulating the paragraph HTML element

16
2
171
Creating CSS
⦁ Cascading Style Sheets come in three flavors:
⦁ inline.
⦁ ,internal,
⦁ and
⦁ external,
Creating an inline style
⦁ All elements have a global attribute called style that can be used to provide an
inline style.
⦁ An inline style is defined on the element to which you wish to add styling,
⦁ don’t need a selector; just need to specify the declaration block.
⦁ The following is an example of an inline style on the <body> element that sets the
background color to white and the font color to gray.
⦁ <body style='background-color:white;color:gray;'>
⦁ </body>
16
3
172
Inline CSS
• In the example, you don’t need an external style sheet because
you defined the style on the actual <body> element.
• You should try to avoid this technique; it violates the primary
goal of separation between structure and presentation
• doesn’t create any reusability because you will need to copy this
style to each HTML document you add to your application.
• An advantage of using an inline style is
– it always overrides styles that are defined else-where because the inline
styles are specific to the element on which the inline style is defined.
– This specificity can solve isolated problems when a style is applied globally in
an external style sheet, but one element needs to be styled differently.
164
173
Cont..d
<h2 style="color:red;margin-left:40px;">
Inline CSS is applied on this heading.
</h2>
<p>This paragraph is not affected.</p>

Disadvantages of Inline CSS


•You cannot use quotations within inline CSS. If you use quotations the browser
will interpret this as an end of your style value.
•These styles cannot be reused anywhere else.
•These styles are tough to be edited because they are not stored at a single
place.
•It is not possible to style pseudo-codes and pseudo-classes with inline CSS.
•Inline CSS does not provide browser cache advantages. 174
174
Embded (internal style)
• Instead of creating inline styles by using the global style
attribute, you can uses the <style> element to create an
embedded (internal) style sheet within your HTML document.
• use CSS selectors to assign the style definitions to elements on
the page.
• embedded style is located within the <head> element
• Place the CSS Code between <style> and </style>

175
175
Internal CSS Example
<html>
<head> • it does not provide file separation.
<style> • It provides reuse within the files, but it
body { background-color: blue; } does not promote reuse across HTML
p { color: white; } documents.
</style>
</head> • use this approach when you want to
<body> have a single, stand-alone HTML
<h2>Internal CSS</h2> document that contains everything
<p>This page uses internal CSS. Using the style needed to render.
tag we are able to modify
the appearance of HTML elements.</p>
</body>
</html> 176
176
External (Cascading style Sheet)
Why use external CSS?
• Using an external style sheet is considered the best way to
implement your styles.
• It keeps your website design and content separate.
• It's much easier to reuse CSS code if you have it in a separate file.
• Instead of typing the same CSS code on every web page, simply
have many pages refer to a single CSS file with the "link" tag.
• drastic changes can be achieved to web pages with just a few
changes in a single CSS file.
• its possible to link many external style sheets to an HTML
document.
177
177
Creating an external style sheet
• Instead of creating the same embedded styles in every HTML
document, the best approach is to create an external style sheet
file that can be linked to all your pages.
• External CSS is a file that contains only CSS code and is saved
with a ".css" file extension.
• This CSS file is then referenced in your HTML using the <link>
element instead of <style>.
• Consider the example bellow
– Test.css
– Test.html
178
178
External (CSS example)
Test.css
body{ background-color: gray;} In example test.html,
p { color: blue; } • the <link> element contains the rel
h3{ color: white; }
attribute, which specifies the rela-
Test.html tionship between the current HTML
<html> document and the external file as a
<head> style sheet.
<link rel="stylesheet" type="text/css"
href="test.css" /> • The type attribute specifies the
</head> MIME type of the external file as a
<body>
<h3> A White Header </h3> text-based cascading style sheet.
<p> This paragraph has a blue font. • The href attribute specifies the
The background color of this page is
gray because we changed it with CSS! </p>
relative location of the external CSS
</body> file, which is the test.css file
</html>
179
179
Using media to specify the target device
• The <link> element also has a media attribute that can specify
the target device.
• By using the media attribute, you can create a CSS file for each
device type and link all the CSS files into your HTML
documents.
• When the HTML document is rendered, the browser
determines the media type and uses the appropriate CSS file.
• The browser can select only one media type for the rendering
of an HTML document
180
180
CSS and Media…
• The following is a list of the media types that are avail-able for use.
– all Renders to all devices
– braille Renders to braille tactile feedback devices
– embossed Renders to paged braille printers
– handheld Renders to handheld devices that typically have small, low-resolution
screens and limited bandwidth
– print Renders paged material and documents viewed on screen in print preview
mode
screen Renders to color computer screens
speech Renders to speech synthesizers
– tty Renders to media, using a fixed-pitch character grid such as teletypes,
terminals, and portable devices with limited display capabilities
tv Renders to television-type devices that typically have low-resolution color
screens with limited ability to scroll and have sound

181
181
Media…
• The following is an example of an HTML document that
contains <link> elements for screen styles and print styles.

<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel='stylesheet' type='text/css' href='Content/screen.css' media='screen' />
<link rel='stylesheet' type='text/css' href='Content/printer.css' media='print' />
</head>
<body>
</body>
</html> 182
182
Specifying the character encoding of the style sheet
⦁ @charset rule use to specify the character encoding of the style
sheet text
⦁ To be compatible with all browsers, be sure to place this on the first
line of your CSS file.
@charset 'UTF-8';
body { background-color: white; color: gray; }
⦁ if your HTML document has a <meta> element that describes the
character set of the HTML document, that setting overrides the
@charset setting in the CSS file.
<head>
<meta http-equiv='Content-Type' content='text/html;charset=UTF-8' >
<link rel='stylesheet' type='text/css' href='Content/default.css' />
183
183</head>
Imported style sheets from other style sheets

• when a style sheet grows, its possible to break it into smaller,


more manageable files.
• The @import rule enables you to import a CSS file to the current
style sheet.
• No limit on the number of @import rules
• the @import rules must be at the top of the style sheet,
• before any other content except the @charset rule.
• Note:
• If comment are above the @import rules, they will not work
properly.
175
185
@Import CSS
@import url('/Content/header.css');
@import url('/Content/menu.css');
@import url('/Content/sidebar.css');
@import url('/Content/mainContent.css');
@import url('/Content/footer.css');
body {
background-color: white;
color: gray;
}

• contents in the CSS file must follow the @import


rules

176
185
Defining selectors
• CSS selectors are used to select the content you want to style.
Selectors are the part of CSS rule set. CSS selectors select HTML
elements according to its id, class, type, attribute etc.
• There are several different types of selectors in CSS.
1. CSS Element Selector
2. CSS Id Selector
3. CSS Class Selector
4. CSS Universal Selector
5. CSS Group Selector
186
177
CSS Element selectors
The element selector selects the HTML element by name.
<!DOCTYPE html>
<html>
<head>
<style>
p{
text-align: center;
color: blue;
}
</style>
</head>
<body>
<p>This style will be applied on every paragraph.</p>
<p id="para1">Me too!</p>
<p>And me!</p>
</body>
</html>

187
178
Defining selectors
• Three Ways to define a selector
– element selectors,
– id selectors, and
• In the previous examples, the tag name (body) is
– class selectors the selector, but there is only one <body>
element in an HTML document.
Creating an element type selector • But what if the selector is Button?
• In this example, if there are 50 buttons, all
An element type selector is based the
buttons will be set to have the defined style.
on the name of the tag • What if we want to set the style in
single button or only set of buttons?
background-color: white;
color: gray;
}

188
188
Creating an id selector
• An id selector is based on the id of the element.
• To set the style on a single button, you can assign an id to the button and
then specify the id as the selector, prefixed with the hash (#) symbol.
• The following example sets the style on an element whose id is btnSave.
• In this example, it doesn’t matter which type of
#btnSave { element is being accessed; all that matters is that
background-color: white; the id is btnSave.
color: gray;
• across webpages, this sets the style of any element
}
whose id is btnSave.
• Because the id must be unique across the HTML
document, using this
approach to set a style limits the
reusability on a page 189
189
Creating a class selector
• A class selector is a style with a class name of your
choice, prefixed with the period (.) symbol.
• This is also called a named style.
• The class name can be assigned to any element
through the class attribute.
• In the following example, a style is created with a
class name of myStyle.
This style won’t apply to any
elements until you specify the class
name by using the class attribute
190
181
Class selector …
<!DOCTYPE html>
<html>
<head> <title></title>
<link rel='stylesheet' type='text/css' href='Content/default.css' />
</head>
<body>
<input id='txtName' name='txtName' type='text' class='myStyle' />
<button id='btnOk' class='myStyle'>Ok</button>
<button id='btnSave'>Save</button>
<button id='btnCancel' class='myStyle'>Cancel</button>
</body>
</html>

• In this example, the class attribute specifies the myStyle style on


the text box and two of the buttons.
• Named styles promote reuse because they can be used on any
element as needed. 191
182
Class selector…
p{ color: red; font-size: 20px; } <html>
p.test1{ color: blue; } <head><style>……..</ style ></head>
p.test2{ font-size: 12px; } <body>
<p>This is a normal paragraph.</p>
<p class="test1">This is a paragraph that uses the p.test1
CSS code!</p>
Output <p class="test2">This is a paragraph that uses the p.test2
CSS code!</p>
……

• CSS code in classes will override the general CSS code for
that element.
• In the above example p.test1 overrides the style defined for
the p p{ color: red; font-size: 20px; }
192
183
Using the universal selector

• If you want to apply a style to every element, you can use


the asterisk (*) symbol.
• The following example applies the style to every element in
the HTML document.
*{
background-color: white;
color: gray;
}

• You should avoid using the universal selector because of the


performance cost.
184
196
Grouping selectors
• You can group selectors when you will be applying
the same style by separating each selector with a
comma.
Button, p {
background-color: white;
color: gray;
}

185
196
Using pseudo-class and pseudo-element selectors

• Styles are generally attached to an element based on locating the


element in the document object model (DOM) tree.
• Although this usually works fine, sometimes you want to apply a
style to something more granular than an element.
– How do you assign a style to the first line of a paragraph?
– How do you assign a style to a hyperlink that has been visited?
• To access information that is either outside the DOM tree or
difficult to access in the DOM tree, you can use pseudo classes
and pseudo elements.
186
196
Pseudo classes…
• Pseudo classes classify elements based on something other than
name, attributes, or content and, usually, something that cannot
be deduced from the DOM tree
• You can use the pseudo classes anywhere in your selector chain
to help you locate elements when the identified state is true.
• You can also use pseudo classes at the end of the selector chain
to set the style of the element when the iden-tified state is true
• Consider the following example, about a link and its four states

187
196
Pseudo class…
• The states must be defined in the correct order
1. link - this is a link that has not been used, nor is a mouse pointer
hovering over it
2. visited - this is a link that has been used before, but has no mouse
on it
3. hover - this is a link currently has a mouse pointer hovering over
it/on it
4. active - this is a link that is in the process of being clicked
• Using CSS you can make a different look for each one of these
states using pseudo class
• Code format: a:(STATE'S NAME) { attribute: value; }
188
196
Pseudo classes…
a:link {
color: white;
background-color: black; Considering the bellow html the
text-decoration: none; effect is illustrated in the figure
border: 2px solid white;
}
bellow
a:visited { <a href="">This is a special CSS
color: white; Link</a>
background-color:
black; text-decoration: none;
border: 2px solid white;
}
a:hover {
color: black;
background-color: white;
text-decoration: none;
border: 2px solid black;
} 189
198
CSS Font Properties
• The CSS font properties control all aspects of your
text graphical representation.
• From the thickness of your font (font-weight) to font
type (font-family) of your choice.
• Here are all the font properties at your disposal:
– font
– font-family
– font-size
– font-style
– font-weight
– font-variant
190
199
CSS Text Properties
• The CSS text properties control the spacing,
alignment, decoration, and other miscellaneous
aspects of the text.
• Here is a list of all the CSS text properties. letter-
spacing
– word-spacing
– text-decoration
– vertical-align
– text-transform
– text-align
– text-indent
– line-height
200
200
CSS Background Properties
• The CSS background properties control things like if
the background is a single color or maybe an image.
• If it's an image you can set the position of the image
and tell it whether or not you want the image to
repeat left-to-right and/or top-to-bottom.
– Background
– Background Color
– Background Image
– Background Repeat
– Background Attachment
– Background Position
201
201
Using subsequent adjacent sibling selectors
• An adjacent selector can be used to select an
element if it is preceded by a specific element.
• The plus (+) sign denotes an adjacent selector.
• In the following example, div + h1 set the heading
to a background color of yellow if the heading is
preceded by a <div> element as the previous
sibling.

div + h1 {
background-color: yellow;
}
202
202
CSS COMMENTS

Comments are used to explain your code, and may help you when you
edit the source code at a later date. Comments are ignored by browsers.
A CSS comment begins with "/*", and ends with "*/", like this:
/*This is a comment*/
p
{
text-align:center;
/*This is another comment*/
color:black;
font-family:arial;
}
194
203
Working with CONTENTS TO CSS

CSS COMMENTS
CSS COLORS
CSS TEXT
CSS ID AND CLASS
POSITIONING
OVERLAPPING ELEMENTS
CSS ALIGN
CROSS BROWSERS COMPATIBLE ISSUES
195
206
Working with Colors

Colors are displayed combining RED, GREEN, and BLUE light.


COLOR VALUES
CSS colors are defined using a hexadecimal (hex) notation for
the combination of Red, Green, and Blue color values (RGB). The lowest
value that can be given to one of the light sources is 0 (hex 00). The
highest value is 255 (hex FF).
Hex values are written as 3 double digit numbers, starting with a # sign.

196
206
Working CSS TEXT
The color property is used to set the color of the text. The color
can be specified by:
* name - a color name, like "red"
* RGB - an RGB value, like "rgb(255,0,0)"
* Hex - a hex value, like "#ff0000"
The default color for a page is defined in the body selector.
Example
body {color:blue;}
h1 {color:#00ff00;}
h2 {color:rgb(255,0,0);}
197
206
Working CSS TEXT alignment
The color property is used to set the color of the text. The color
can be specified by:
* name - a color name, like "red"
* RGB - an RGB value, like "rgb(255,0,0)"
* Hex - a hex value, like "#ff0000"
The default color for a page is defined in the body selector.
Example
body {color:blue;}
h1 {color:#00ff00;}
h2 {color:rgb(255,0,0);} 198
207
Text Alignment

The text-align property is used to set the


horizontal alignment of a text. Text can be centered, or
aligned to the left or right, or justified.
When text-align is set to "justify", each line is
stretched so that every line has equal width, and the
left and right margins are straight
Example
h1 {text-align:center;}
p.date {text-align:right;}
p.main {text-align:justify;}
Text Decoration

The text-decoration property is used to set or


remove decorations from text.

The text-decoration property is mostly used to


remove underlines from links for design purposes:

Example
a {text-decoration:none;}
Text Transformation

The text-transform property is used to specify


uppercase and lowercase letters in a text.
It can be used to turn everything into uppercase or
lowercase letters, or capitalize the first letter of each
word.
Example
p.uppercase {text-transform:uppercase;}
p.lowercase {text-transform:lowercase;}
p.capitalize {text-transform:capitalize;}
Text Indentation

The text-indentation property is used to specify the


indentation of the first line of a text.
Example
p {text-indent:50px;}
CSS Example
body
{
background-color:#d0e4fe;
}
h1
{
color:orange;
text-align:center;
}
p
{
font-family:"Times New Roman";
font-size:20px;
}
CSS ID AND CLASS
The id Selector
The id selector is used to specify a style for a single, unique element.
The id selector uses the id attribute of the HTML
element, and is defined with a "#".
The style rule below will be applied to the element with
id="para1":
Example
#para1
{
text-align:center;
color:red;
}
The class Selector

The class selector is used to specify a style for a


group of elements. Unlike the id selector, the class
selector is most often used on several elements.
This allows you to set a particular style for any
HTML elements with the same class.
The class selector uses the HTML class
attribute, and is defined with a "."
In the example below, all HTML elements with
class="center" will be center-aligned:
Example
.center {text-align:center;}
POSITIONING
The CSS positioning properties allow you to
position an element. It can also place an element
behind another, and specify what should happen when
an element's content is too big.
Elements can be positioned using the top, bottom,
left, and right properties. However, these properties
will not work unless the position property is set first.
They also work differently depending on the
positioning method.
There are four different positioning methods.
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.
It will not move even if the window is scrolled:
Example
p.pos_fixed
{
position:fixed;
top:30px;
right:5px;
}
Relative Positioning
A relative positioned element is positioned relative
to its normal position.
Example
h2.pos_left
{
position:relative;
left:-20px;
}
h2.pos_right
{
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>:
Example
h2
{
position:absolute;
left:100px;
top:150px;
}
Overlapping Elements
When elements are positioned outside the normal flow, they can
overlap other elements.
The z-index property specifies the stack order of an element
(which element should be placed in front of, or behind, the others). An
element can have a positive or negative stack order:
Example
img
{
position:absolute;
left:0px;
top:0px;
z-index:-1 }
CSS Align

Aligning 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 of block elements:

* <h1>
* <p>
* <div>
Center Aligning
Block elements can be aligned by setting the left and right
margins to "auto".
Note: Using margin:auto will not work in Internet
Explorer, unless a !DOCTYPE is declared.
Setting the left and right margins to auto specifies that
they should split the available margin equally. The result is a
centered element:
Example
. center {
margin-left:auto;
margin-right:auto;
width:70%;
background-color:#b0e0e6; }
Left and Right Aligning
Using the position Property
Example

.right
{
position:absolute;
right:0px;
width:300px;
background-color:#b0e0e6;
}
CROSSBROWSER COMPATIBILITY ISSUES

When aligning elements like this, it is always a good idea to predefine


margin and padding for the <body> element. This is to avoid visual
differences in different browsers.
There is also another problem with IE when using the position
property. If a container element (in our case <div class="container">)
has a specified width, and the !DOCTYPE declaration is missing, IE
will add a 17px margin on the right side. This seems to be space
reserved for a scrollbar. Always set the !DOCTYPE declaration when
using the position property:
Example
body{
margin:0;
padding:0;}
.container{
position:relative;
width:100%;
}
.right
{
position:absolute;
right:0px;
width:300px;
background-color:#b0e0e6;
}
Chapter Four

Client-Side Programming – JavaScript


(Detail of JavaScript will be discussed here)

By Daniel Getaye
BSc. In Information System
JavaScript
 JavaScript is an object-based scripting language which is lightweight
and cross-platform.
 JavaScript is not a compiled language, but it is a translated language.
The JavaScript Translator (embedded in the browser) is responsible for
translating the JavaScript code for the web browser.
 JavaScript (js) is a light-weight object-oriented programming language
which is used by several websites for scripting the webpages.
 It is an interpreted, full-fledged programming language that enables
dynamic interactivity on websites when applied to an HTML
document
218
229
Application of JavaScript

 JavaScript is used to create interactive websites. It is mainly used for:


 Client-side validation,
 Dynamic drop-down menus,
 Displaying date and time,
 Displaying pop-up windows and dialog boxes (like an alert dialog box,
confirm dialog box and prompt dialog box),
 Displaying clocks etc.

219
229
JavaScript Hello world example

<html>
• To insert a JavaScript into an HTML page, we
<head><title>JavaScript
HelloWorld!</title></head> use the <script> tag (also use the type
<body> attribute to define the scripting language).
<script • So, the <script type="text/javascript"> and
language="JavaScript">
</script> tells where the JavaScript starts and
document.write('Javascript ends:
says "Hello World!"') • By entering the document.write command
</script> between the <script type="text/javascript">
</body> and </script> tags,
</html> • the browser will recognize it as a JavaScript
command and execute the code line. In this
case the browser will write Hello World! to
the page:
220
230
JavaScript Location
 JavaScript can be located in the head, body or external file
 Head section
 Ensures script is loaded before trigger event
 Body section
 Script executes when body loads
 External
 Allows scripts to run on several pages

221
231
JavaScript cont...d
 JavaScript statements in head write to the beginning of the body section but
don’t violate HTML code already there
 JavaScript statements in body write based on their location
 JavaScript interpreted first then HTML interpreted second
 Document.write writes to the HTML document not the web page
<html>
<head>
<script language=“JavaScript”> This is first
document.write (“<b> This is first </b>); Now where does this print on the web page????
</script> This might be last?
</head>
<body>
Now where does this print on the web page???? <br />
<script language=“JavaScript”>
document.write ( “This might be last?”)
</script>

</body> 233
222 </html>
JavaScript cont...d
Now, let JavaScript generate HTML for us…

<html>
<head><title>JavaScript HelloWorld!</title></head>
<body>
<script laguage="JavaScript">
This is first
document.write("<h2>Javascript-Generated outp ut:</h2>"
Now where does this print on the web page????
+ "<p>This paragraph generated by JavaScript</p> "This might be last?
+ "<p>It can even insert an image</p>"
+ "<img src='../HilCoE/WebTech/images/Logo.jpg' />")
</script>
</body>
</html>
223
235
JavaScript cont...d
Do you want to recap all basic concepts of JavaScript
please clicked here

Just same with other Languages


No basic difference on basic issues

224
235
Example of JavaScript

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
</body> 236
236
</html>
Example of JavaScript

<html>
<head>
<title>table of students</title>
<script>
document.write("Hello JavaScript by JavaScript <br> ");
var a=20,b=20
document.write(a+b);
if(a+b < 50)
document.write('less than 50 <br> ');
else
document.write('greater than 50 <br> ')
</script>
</head>
<body>
</body>
</html> 237
226
Example of JavaScript
<!DOCTYPE html>
<html>
<head>
<title>java Script</title>
</head>
<body>
<script>
var data=200;//gloabal variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling JavaScript function
b();
</script>
</body>
</html>
238
227
JavaScript operator

228
239
JavaScript Loop

 The JavaScript loops are used to iterate the piece of code using for, while,
do while or for-in loops. It makes the code compact. It is mostly used in
array.
There are four types of loops in JavaScript.
1.for loop
2.while loop
3.do-while loop
4.for-in loop

229
239
JavaScript for loop

 The JavaScript for loop iterates the elements for the fixed number of
times. It should be used if number of iteration is known. The syntax of for
loop is given below.
for (initialization; condition; increment)
{
code to be executed
} <script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script> 23
0
241
JavaScript While loop

 The JavaScript while loop iterates the elements for the infinite number of
times. It should be used if number of iteration is not known.
 The syntax of while loop is given below.
<script>
while (condition)
var i=11;
{
while (i<=15)
code to be executed
{
}
document.write(i + "<br/>");
i++;
}
</script>
231
242
JavaScript do While loop

The JavaScript do while loop iterates the elements for the infinite number of
times like while loop. But, code is executed at least once whether condition
is true or false. The syntax of do while loop is given below.
do{
code to be executed
}while (condition); <script>
 . var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
232
243
JavaScript Function

 JavaScript functions are used to perform operations. We can call


JavaScript function many times to reuse the code.
 There are mainly two advantages of JavaScript functions.
 Code reusability: We can call a function several times so it save coding.
 Less coding: It makes our program compact. We don’t need to write
many lines of code each time to perform a common task.
JavaScript Function Syntax
<script>
The syntax of declaring function is given below.
function functionName([arg1, arg2, ...argN]){ function msg(){
//code to be executed alert("hello! this is message");
} }
</script>
<input type="button" onclick="msg()" value="call function"/>
244
Alert message

<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>

234
246
Function with Return Value

We can call function that returns a value and use it in our program. Let’s see the
example of function that returns value.

<script>
function getInfo(){
return "hello you Guys! How r u?";
hello you Guys! How r u?
}
</script>
<script>
document.write(getInfo());

235
246
Function with Return Value

We can call function that returns a value and use it in our program. Let’s see the
example of function that returns value.

<script>
var pow=new Function("num1","num2","return Math.pow(num1,num2)");
document.writeln(pow(2,3));
</script>

236
246
JavaScript data type
 JavaScript provides different data types to hold different types of values.
 There are two types of data types in JavaScript.
 Primitive data type
 Non-primitive (reference) data type
 JavaScript is a dynamic type language, means you don't need to specify
type of the variable because it is dynamically used by JavaScript engine.
 You need to use var here to specify the data type. It can hold any type
of values such as numbers, strings etc. For example:
 var a=40;//holding number
 var b="Rahul";//holding string

237
246
JavaScript primitivedata type
There are five types of primitive data types in JavaScript. They are as
follows:

238
249
JavaScript non-primitivedata type
The non-primitive data types are as follows:

239
250
DocumentObject Model
 The document object represents the whole html document.
 When html document is loaded in the browser, it becomes a document object.
 It is the root element that represents the html document. It has properties and
methods.
 By the help of document object, we can add dynamic content to our web page.

240
250
PropertiesDocumentObject
• Anchor object
• Document object
• Event object
• Form and Form Input object
• Frame, Frameset, and IFrame
objects
• Image object
• Location object
• Navigator object
• Option and Select objects
• Screen object
• Table, TableHeader, TableRow,
TableData objects 252
252 • Window object
Methodsof document object
We can access and change the contents of document by its methods.
The important methods of document object are as follows:

242
255
Examples
<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>

<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>
243
255
JavaScript - document.getElementById() method
 The document.getElementById() method returns the element of specified id.
 In the previous slide,we have used document.form1.name.value to get the value of
the input value.
 Instead of this, we can use document.getElementById() method to get value of the
input text. But we need to define id for the input field.

244
255
JavaScript - document.getElementByName() method
 The document.getElementsByName() method returns all the element of specified
name.
 The syntax of the getElementsByName() method is given below:
 document.getElementsByName("name")
<script type="text/javascript">
function totalelements()
{
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">

<input type="button" onclick="totalelements()" value="Total Genders">


</for2m56> 256
JavaScript - document.getElementByTagName() method

The document.getElementsByTagName() method returns all the element of specified tag


name.
 The syntax of the getElementsByTagName() method is given below:
document.getElementsByTagName("name")
<script type="text/javascript">
function countpara(){
var totalpara=document.getElementsByTagName("p");
alert("total p tags are: "+totalpara.length);

}
</script>
<p>This is a pragraph</p>
<p>Here we are going to count total number of paragraphs by
getElementByTagName() method.</p>
<p>Let's see the simple example</p> 257
<but2t5o7nonclick="countpara()">count paragraph</button>
Javascript - innerHTML
<script type="text/javascript" >
function showcommentform() {
var data="Name:<input type='text'
name='name'><br>Comment:<br><textarea rows='5'
cols='80'></textarea> <br><input type='submit' value='Post Comment'>";
document.getElementById('mylocation').innerHTML=data;
}
</script>
<form name="myForm">
<input type="button" value="comment" onclick="showcommentform()">
<div id="mylocation"></div>
</form>

258
258
Show/Hide Comment Form Example using innerHTML
<!DOCTYPE html>
<html> flag=true;
<head> }
<title>First JS</title> }
<script> </script>
var flag=true; </head>
function commentform(){ <body>
var cform="<form action='Comment'>Enter Name:<br> <button onclick="commentform()">Comment</button>
<input type='text' name='name'/><br/> <div id="mylocation"></div>
Enter Email:<br><input type='email' name='email'/> </body>
<br>Enter Comment:<br/> </html>
<textarea rows='5' cols='70'></textarea><br>
<input type='submit' value='Post Comment'/></form>";
if(flag){
document.getElementById("mylocation").innerHTML=cfo
rm;
flag=false;
}else2{59 259
document.getElementById("mylocation").innerHTML="";
JavaScript Event
 The change in the state of an object is known as an Event.
 In html, there are various events which represents that some activity is
performed by the user or by the browser.
 When javascript code is included in HTML, js react over these events and allow
the execution. This process of reacting over the events is called Event
Handling.
 Thus, js handles the HTML events via Event Handlers.
For example, when a user clicks over the browser, add js code, which will execute
the task to be performed on the event.
Some of the HTML events and their event handlers are

249
260
Mouse and keyboard events:

250
260
Mouse and keyboard events:

251
260
Examples click Events
<html>
<head> Javascript Events </head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function clickevent()
{
document.write("This is JavaTpoint");
}
//-->
</script>
<form>
<input type="button" onclick="clickevent()" value="Who's this?"/
>
</form>
</body> 263
263
</html>
Examples MouseOver Events
<html>
<head> Javascript Events </head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function mouseoverevent()
{
alert("This is JavaTpoint");
}
//-->
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me
</p>
</body>
</html> 264
264
Examples Focus Events
<html>
<head> Javascript Events </head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
<!--
function focusevent()
{

document.getElementById("input1").style.background="
aqua";
}
//-->
</script> </body> 265
265
</html>
Examples Keydown Events
<html>
<head> Javascript Events </head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1"
onkeydown="keydownevent()"/>
<script>
<!--
function keydownevent()
{
document.getElementById("input1");
alert("Pressed a key");
}
//-->
</script> </body> 266
266
</html>
Examples Load Events
<html>
<head> Javascript Events </head>
</br>
<body onload="window.alert('Page successfully loaded');">
<script>
<!--
document.write("The page is loaded successfully");
//-->
</script>
</body>
</html>

267
267
JavaScript addEventListener()
 The addEventListener() method is used to attach an event handler to a particular
element. It does not override the existing event handlers.
 Events are said to be an essential part of the JavaScript. A web page responds
according to the event that occurred. Events can be user-generated or generated by
API's.
 An event listener is a JavaScript's procedure that waits for the occurrence of an
event.
 The addEventListener() method is an inbuilt function of JavaScript.
 We can add multiple event handlers to a particular element without overwriting the
existing event handlers.

Syntax
1.element.addEventListener(event, function, useCapture);
2.element.addEventListener(event, function, useCapture);
268
Mouse events:

258
269
Mouse events:

259
269
Mouse events:

260
269
JavaScript Form Validation
 It is important to validate the form submitted by the user because it can have
inappropriate values.
 So, validation is must to authenticate user.
 JavaScript provides facility to validate the form on the client-side so data
processing will be faster than server-side validation.
 Most of the web developers prefer JavaScript form validation.
 For instance,through JavaScript, we can validate name, password, email, date,
mobile numbers and more fields.

261
269
JavaScript Form Validation
<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;

if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="abc.jsp" onsubmit="ret
urn validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</f2o7r3m>
273
JavaScript Validation image alert
interactive JavaScript form validation example that displays correct and
inco<rsrcericptt>image if input is correct or incorrect. }else{
<script> document.getElementById("passwordloc").innerHTML=" <img src='
function validate(){ checked.gif'/>";
var name=document.f1.name.value; }
var password=document.f1.password.value; return status;
var status=false; }
</script>
if(name.length<1){
document.getElementById("nameloc").innerHTML= <form name="f1" action="#" onsubmit="return validate()">
" <img src='unchecked.gif'/> Please enter your name"; <table>
status=false; <tr><td>Enter Name:</td><td><input type="text" name="name"/>
}else{
document.getElementById("nameloc").innerHTML=“ <span id="nameloc"></span></td></tr>
<img src='checked.gif'/>"; <tr><td>Enter Password:</td><td><input type="password" name=
status=true; "password"/>
} <span id="passwordloc"></span></td></tr>
if(password.length<6){ <tr><td colspan="2"><input type="submit" value="register"/></td>
document.getElementById("passwordloc").innerHTML= </tr>
" <img src='unchecked.gif'/> Password must be at least 6 char </table>
long"; </form> 274
st2a7t4us=false;
JavaScript Retype Password Validation
<script type="text/javascript">
function matchpass(){
var firstpassword=document.f1.password.value;
var secondpassword=document.f1.password2.value;

if(firstpassword==secondpassword){
return true;
}
else{
alert("password must be same!");
return false;
}
}
</script>
<form name="f1" action="register.jsp" onsubmit="return
matchpass()">
Password:<input type="password" name="password" /><br/>
Re-enter Password:<input type="password"
name="password2"/><br/>
<input type="submit"> 275
</fo27r5m>
JavaScript Number Validation
<style type="text/css">
p{color:red;}
</style>
<script>
function validate(){
var num=document.myform.num.value;
if (isNaN(num)){
document.getElementById("numloc").innerHTML="<p> Enter
Numeric value only </p>";
return false;
}else{
return true;
}
}
</script>
<form name="myform" onsubmit="return validate()" >
Number: <input type="text" name="num"><span
id="numloc"></span><br/>
<input type="submit" value="submit">
</form> 276
276
JavaScript Email Validation
<script>
function validateemail() There are many criteria that need to be follow to validate the email
{ id such as:
var x=document.myform.email.value; •email id must contain the @ and . character
var atposition=x.indexOf("@"); •There must be at least one character before and after the @.
var dotposition=x.lastIndexOf("."); •There must be at least two characters after . (dot).
if (atposition<1 || dotposition<atposition+2 ||
dotposition+2>=x.length){
alert("Please enter a valid e-mail address \n
atpostion:"+atposition+"\n dotposition:"+dotposition);
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="#"
onsubmit="return validateemail();">
Email: <input type="text" name="email"><br/>

<input type="submit" value="register"> 27


</fo27r7m> 7
Javascript - innerHTML
 The innerHTML property can be used to write the dynamic html on the html document.
 It is used mostly in the web pages to generate the dynamic html such as registration form,
comment form, links etc.
 In in the following example, we are going to create the html form when user clicks on the
button.
 In this example, we are dynamically writing the html form inside the div name having the
id mylocation. We are identifying this position by calling the document.getElementById()
method.

278
267
Form Validation
</head>
</style> <body onload='document.form1.text1.focus()'>
<head> <script type="text/javascript"> <div class="mail">
<meta charset="utf-8"> <p>Enter Userid [between 6 to 8 characters] and
<title>JavaScript form validation - checking non Submit</p>
empty</title> function stringlength(inputtxt, minlength, maxlength) <form name="form1" action="#">
<link rel='stylesheet' href='form-style.css' { <ul>
type='text/css' /> var field = inputtxt.value; <li>Username:<input type='text' name='text1'/></li>
var mnlen = minlength; <li>&nbsp;</li>
<style type="text/css"> var mxlen = maxlength; <li class="submit"it"><input type="submit"
li {list-style-type: none; name="submit" value="Submit"
font-size: 16pt; if(field.length<mnlen || field.length> mxlen) onclick="stringlength(document.form1.text1,6,8)"/></l
} { i>
.mail { alert("Please input the userid between " +mnlen+ " <li>&nbsp;</li>
margin: auto; and " +mxlen+ " characters"); </form>
padding-top: 10px; return false; </ul>
padding-bottom: 10px; } </div>
width: 400px; else <script src="string-lenght.js"></script>
background : #D8F1F8; { </body>
border: 1px soild silver; alert('Your userid have accepted.'); </html>
color: #000 return true;
} }
.mail h2 { }

279
margin-left: 38px;
} </script>
268
JavaScript and HTML Forms
<HTML> //--></SCRIPT>
<HEAD> </HEAD>
<SCRIPT LANGUAGE=JavaScript><!--
function plus(){ <BODY BGCOLOR="#FFFFCC">
var n1; <P><FORM name=addmult>
var n2; <fieldset style="width: 305px; height: 110px"><legend>Simple
n1=document.addmult.num1.value; calculator </legend>
n2=document.addmult.num2.value;
<P style="width: 277px; height: 81px;">Enter a number in each field:
n1=parseFloat(n1); <INPUT TYPE=text NAME=num1 VALUE="" SIZE=5>
n2=parseFloat(n2); <INPUT TYPE=text NAME=num2 VALUE="" SIZE=5><BR>
<INPUT TYPE=button VALUE="+" onclick="plus()">
document.addmult.result.value=n1+n2;
} <INPUT TYPE=button VALUE="*" onclick="times()"><BR>
function times(){ <INPUT TYPE=reset VALUE="Reset Form"><BR>
var n1; Result: <input type = text name = result>
var n2;
n1=document.addmult.num1.value; </fieldset>
n2=document.addmult.num2.value; </FORM></HTML>

n1=parseFloat(n1);
n2=parseFloat(n2);

document.addmult.result.value=n1*n2;
}

280
269
JavaScript and HTML Forms
<TR>
<HTML> <TD>Address:</TD>
<HEAD> <TD>
<SCRIPT LANGUAGE=JavaScript><!-- <P><INPUT TYPE=text NAME=address VALUE="" SIZE=32>
function verify(){ </TD>
with(document.infoform){ </TR>
if((fullname.value=="")||(address.value=="")||(email.value=="")){ <TR>
alert("You have left one or more fields blank. Please supply the <TD>E-maill</TD>
necessary information, and re-submit the <TD><INPUT TYPE=text NAME=email VALUE="" SIZE=32></TD>
form."); </TR>
} <TR>
else { <TD><INPUT TYPE=button VALUE="Submit"
display.value="The following information has been added to our onclick="verify()"></TD>
<TD><INPUT TYPE=reset VALUE="Clear Your Information“></TD>
guestbook:\r"+fullname.value+"\r"+ address.value +"\r"
</TR>
+email.value;
<TR><TD><TEXTAREA NAME=display ROWS=5 COLS=41
} WRAP=virtual> </TEXTAREA> </TD>
} </TR>
} </TABLE>
//--></SCRIPT> </FORM>
</HEAD> </BODY>
<BODY BGCOLOR="#FFFFCC"> </HTML>
<P><FORM name=infoform>
<P><TABLE BORDER=0>
<TR>
<TD WIDTH=83>Name:</TD>
281
281 <TD><INPUT TYPE=text NAME=fullname VALUE="" SIZE=32></TD>
</TR>
Chapter Five

Server-Side Scripting–PHP
(Detail of PHP will be discussed here)

By Daniel Getaye
BSc. In Information System
PHP
 PHP stands for Hypertext Preprocessor.
 PHP is a very popular and widely-used open source server-side
scripting language to write dynamically generated web pages.
 PHP was originally created by Rasmus Lerdorf in 1994.
 It was initially known as Personal Home Page.
 PHP scripts are executed on the server and the result is sent to the
web browser as plain HTML.
 PHP can be integrated with the number of popular databases,
including MySQL, PostgreSQL, Oracle, Microsoft SQL Server, Sybase,
and so on.
272
286
PHP
 The current major version of PHP is 7.
 All of the code in this tutorial has been tested and validated against

the most recent release of PHP 7.


 PHP is very powerful language yet easy to learn and use. So
bookmark this website and continued on.

273
286
What You Can Do with PHP
There are lot more things you can do with PHP.
You can generate pages and files dynamically.
You can create, open, read, write and close files on the server.
You can collect data from a web form such as user information, email,
phone no, etc.
You can send emails to the users of your website.
You can send and receive cookies to track the visitor of your website.
You can store, delete, and modify information in your database.
You can restrict unauthorized access to your website.
You can encrypt data for safe transmission over internet.
274
286
Advantages of PHP over Other Languages
 There are several advantages why one should choose PHP.
 Easy to learn: PHP is easy to learn and use. For beginner programmers who
just started out in web development, PHP is often considered as the
preferable choice of language to learn.
 Open source: PHP is an open-source project. It is developed and maintained
by a worldwide community of developers who make its source code freely
available to download and use.
 Portability: PHP runs on various platforms such as Microsoft Windows,
Linux, Mac OS, etc. and it is compatible with almost all servers used today
such Apache, IIS, etc.

275
286
Advantages of PHP over Other Languages cont…d
 Fast Performance: Scripts written in PHP usually execute or runs faster than
those written in other scripting languages like ASP, Ruby, Python, Java, etc.
 Vast Community: Since PHP is supported by the worldwide community,
finding help or documentation related to PHP online is extremely easy.

276
286
Setting Up a Local Web Server
 PHP script execute on a web server running PHP.
 So before you start writing any PHP program you need the following program
installed on your computer.
 The Apache Web server.
 The PHP engine.
 The MySQL database server.
 You can either install them individually or choose a pre-configured package for
your operating system like Linux and Windows.
 Popular pre-configured package are XAMPP and WampServer.
 WampServer is a Windows web development environment.
 It allows you to create web applications with Apache2, PHP and a MySQL
database.
277
286
Setting Up a Local Web Server
 It will also provide the MySQL administrative tool PhpMyAdmin to easily manage
your databases using a web browser.
 WAMP Windows ,Apache ,Mysql And Php
 XAMPP (X Any Operating System), Apache, Mysql ,Php And Perl,
 After you installed this server then click on the WampServer icon somewhere on
your Windows task bar and select the "www directory". Alternatively, you can
access the "www" directory through navigating the C:\wamp\www.
 If you are using Xampp server, you can access the “htdocs" directory through
navigating the C:\xampp\htdocs.
 Create a subdirectory in "www" or “htdocs" directory let's say "project".

278
286
Setting Up a Local Web Server

279
286
Creating Your First PHP Script
 Now open up your favorite code editor and create a new PHP file then type
the following code:
<?php // is starting tag // is single line comments
echo "Hello, world!"; // is just to display greeting message
?> //is closing tag
 Go to XAMPP or WAMP server and start your server by click on start apache
and start phpmyadmin(mysql).
 Now save this file as "hello.php" in your project folder (located
at C:\wamp\www\project) for WAMP or C:\Xampp\htdocs\project) for XAMPP
 Then view the result in your browser through visiting this URL:
http://localhost/project/hello.php or 127.0.0.1/project/hello.php.

280
286
Creating Your First PHP Script
 PHP can be embedded within a normal HTML web page. That means inside
your HTML document you can write the PHP statements, as demonstrated in
the follwoing example:

<!DOCTYPE HTML>
<html> <head>
<title>PHP Application</title>
</head>
<body>
<?php // Display greeting message
echo 'Hello World!'; ?>
</body>
</html> 292
292
Standard PHP Syntax
 A PHP script starts with the <?php and ends with the ?> tag.
 The PHP delimiter <?php and ?> in the following example simply tells the PHP
engine to treat the enclosed code block as PHP code, rather than simple HTML.
<?php // Some code to be executed
echo "Hello, world!";
?>
 Every PHP statement end with a semicolon (;)
 This tells the PHP engine that the end of the current statement has been
reached.

293
293
Embedding PHP within HTML
 PHP files are plain text files with .php extension.
 Inside a PHP file you can write HTML like you do in regular HTML pages as well as embed
PHP codes for server side execution.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>A Simple PHP File</title>
</head>
<body>
<h1><?php echo "Hello, world!"; ?></h1>
</body>
</html>
 If you view the source code of the resulting web page in your browser, the only difference
you will see is the PHP code <?php echo "Hello, world!"; ?> has been replaced with the 294
294
output "Hello, world!".
PHP Comments
 PHP support single-line as well as multi-line comments.
 To write a single-line comment either start the line with either two slashes (//) or a hash
symbol (#).
 However to write multi-line comments, start the comment with a slash followed by an
asterisk (/*) and end the comment with an asterisk followed by a slash (*/), like this:
 For example:

<?php // This is a single line comment


# This is also a single line comment
/* This is a multiple line comment block
that spans across more than one line */
echo "Hello, world!"; ?>

284
296
Case Sensitivity in PHP
• Variable names in PHP are case-sensitive. As a result the
variables $color, $Color and $COLOR are treated as three different variables.
<?php // This is a single line comment
// Assign value to variable
$color = "blue"; // Try to print variable value
echo "The color of the sky is " . $color . "<br>";
echo "The color of the sky is " . $Color . "<br>";
echo "The color of the sky is " . $COLOR . "<br>";
?>
 If you try to run the above example code it will only display the value of the
variable $color and produce the "Undefined variable" warning for the
variable $Color and $COLOR.

285
296
Case Sensitivity in PHP
However the keywords, function and classes names are case-insensitive.
As a result calling the gettype() or GETTYPE() produce the same result.
For example
<?php // Assign value to variable
$color = "blue";
// Get the type of a variable echo gettype($color) . "<br>";
echo GETTYPE($color) . "<br>"; ?>
 If you try to run the above example code both the functions gettype() and GETTYPE() gives
the same output, which is: string.

286
296
What is Variable in PHP
 Variables are used to store data, like string of text, numbers, etc.
 Variable values can change over the course of a script.
 Here're some important things to know about variables:
 In PHP, a variable does not need to be declared before adding a value to it.
 PHP automatically converts the variable to the correct data type, depending on its
value.
 After declaring a variable it can be reused throughout the code.
 The assignment operator (=) used to assign value to a variable.
 In PHP variable can be declared as: $var_name = value;
 <?php // Declaring variables
 $txt = "Hello World!";
 $number = 10; // Displaying variables value
 echo $txt; // Output: Hello World!
 echo $number; // Output: 10 ?> 298
298
PHP Naming Convention(identifier rules)
 These are the following rules for naming a PHP variable:
 All variables in PHP start with a $ sign, followed by the name of the variable.
 A variable name must start with a letter or the underscore character _.
 A variable name cannot start with a number.
 A variable name in PHP can only contain alpha-numeric characters
and underscores (A-z, 0-9, and _).
 A variable name cannot contain spaces.

288
300
The PHP echo Statement
 The echo statement can output one or more strings.
 In general terms, the echo statement can display anything that can be
displayed to the browser, such as string, numbers, variables values, the results
of expressions etc.
 Since echo is a language construct not actually a function (like if statement) ,
you can use it without parentheses e.g. echo or echo().
 However, if you want to pass more than one parameter to echo, the
parameters must not be enclosed within parentheses.

289
300
Display Strings of Text
The following example will show you how to display a string of text with the echo
statement:
<?php // Displaying string of text echo "Hello World!"; ?>
The following example will show you how to display HTML code using the echo
statement:
<?php // Displaying HTML code
echo "<h4>This is a simple heading.</h4>";
echo "<h4 style='color: red;'>This is heading with style.</h4>"; ?>

290
300
Display a variable
 The following example will show you how to display variable using the echo
statement:

<?php // Defining variables


$txt = "Hello World!";
$num = 123456789;
$colors = array("Red", "Green", "Blue");
// Displaying variables
echo $txt; echo "<br>"; echo $num;
echo "<br>";
echo $colors[0]; ?>

291
300
The PHP print Statement
 You can also use the print statement (an alternative to echo) to display output
to the browser.
 Like echo the print is also a language construct not a real function.
 So you can also use it without parentheses like: print or print().
 Both echo and print statement works exactly the same way except that
the print statement can only output one string, and always returns 1.
 That's why the echo statement considered marginally faster than
the print statement since it doesn't return any value.
Display Strings of Text
The following example will show you how to display a string of text with the print
statement:
<?php // Displaying string of text
print "Hello World!"; ?> 292
303
Display HTML Code
 The following example will show you how to display HTML code using the print
statement:
<?php // Displaying HTML code
print "<h4>This is a simple heading.</h4>";
print "<h4 style='color: red;'>
This is heading with style.</h4>";
?>

293
306
Display Variables
 The following example will show you how to display variable
using the print statement:
<?php // Defining variables
$txt = "Hello World!";
$num = 123456789;
$colors = array("Red", "Green", "Blue");
// Displaying variables
print $txt; print "<br>";
print $num; print "<br>";
print $colors[0]; ?>

294
306
Data Types in PHP
 The values assigned to a PHP variable may be of different data types including simple string
and numeric types to more complex data types like arrays and objects.
 PHP supports total eight primitive data types: Integer, Floating point number or Float, String,
Booleans, Array, Object, resource and NULL.
 integer number string values floating number

295
306
Data Types in PHP

PHP Arrays
 An array is a variable that can hold more than one
value at a time. It is useful to aggregate a series of
related items together, for example a set of country
or city names.
 An array is formally defined as an indexed collection
of data values. Each index (also known as the key) of
an array is unique and references a corresponding 307
307
value.
Data Types in PHP
PHP Objects
 An object is a data type that not only allows storing data but also information on, how to process that data.
 An object is a specific instance of a class which serve as templates for objects.
 Objects are created based on this template via the new keyword.

297
309
Data Types in PHP
PHP Resources
 A resource is a special variable, holding a reference to an external resource.
 Resource variables typically hold special handlers to opened files and database connections.
<?php // Open a file for reading
$handle = fopen("note.txt", "r"); var_dump($handle);
echo "<br>"; // Connect to MySQL database server with default
setting
$link = mysqli_connect("localhost", "root", "");
var_dump($link); ?>

298
309
Statements in PHP
 There are several statements in PHP that you can use to make decisions:
 Decision making statements(if else conditional statements)
 Selection statements (Switch)
 Repetition statements (loops)

299
309
Decision making Statements in PHP
 There are several statements in PHP that you can use to make decisions:
 The if statement
 The if...else statement
 The if...elseif....else statement
 The switch...case statement

300
309
Statements in PHP
 There are several statements in PHP that you can use to make decisions:
 The if statement The if...else statement

301
309
Statements in PHP
The if...elseif....else statement ternary operator written as more compact way:

302
309
Statements in PHP
Switch statement
 The switch-case statement is an alternative to the if-elseif-else statement, which does
almost the same thing.
 The switch-case statement tests a variable against a series of values until it finds a match,
and then executes the block of code corresponding to that match.

303
309
Loop Statements in PHP
Different Types of Loops in PHP
 Loops are used to execute the same block of code again and again, as long as a
certain condition is met. The basic idea behind a loop is to automate the
repetitive tasks within a program to save the time and effort. PHP supports
four different types of loops.
 while — loops through a block of code as long as the condition specified
evaluates to true.
 do…while — the block of code executed once and then condition is evaluated.
If the condition is true the statement is repeated as long as the specified
condition is true.
 for — loops through a block of code until the counter reaches a specified
number.
 foreach — loops through a block of code for each element in an array. 315
315
Loop Statements in PHP
while do…while

 The while loop differs from the do-while loop in one important way — with a while loop, the condition to be
evaluated is tested at the beginning of each loop iteration, so if the conditional expression evaluates to false,
the loop will never be executed.
 With a do-while loop, on the other hand, the loop will always be executed once, even if the conditional
expression is false, because the condition is evaluated at the end of the loop iteration rather than the
beginning.
305
330
Loop Statements in PHP

 for — loops through a block of code until the counter reaches a specified
number.

 foreach — loops through a block of code for each element in an array.

306
330
Loop Statements in PHP
 foreach — loops through a block of code for each element in an array.

307
330
Statements in PHP
 PHP 7 introduces a new null coalescing operator (??) which you can use as a shorthand
where you need to use a ternary operator in conjunction with isset() function.
 To uderstand this in a better way consider the following line of code. It fetches the value
of $_GET['name'], if it does not exist or NULL, it returns 'anonymous

308
330
PHP arrays
 Arrays are complex variables that allow us to store more than one value or a group of values
under a single variable name.
 Let's suppose you want to store colors in your PHP script.
 Storing the colors one by one in a variable could look something like this:

309
330
PHP arrays
Types of Arrays in PHP
There are three types of arrays that you can create. These are:
1) Indexed array — An array with a numeric key.
An indexed or numeric array stores each array element with a numeric index. The following
examples shows two ways of creating an indexed array, the easiest way is:

310
330
PHP arrays
Types of Arrays in PHP
2) Associative Arrays:
 In an associative array, the keys assigned to values can be arbitrary and user defined strings.
 In the following example the array uses keys instead of index numbers:

311
330
PHP arrays
Types of Arrays in PHP
3) Multidimensional Arrays
The multidimensional array is an array in which each element can also be an array and each
element in the sub-array can be an array or further contain array within itself and so on. An
example of a multidimensional array will look something like this:

312
330
PHP Fucnctions
Types of functions in PHP
1) PHP Built-in Functions
 A function is a self-contained block of code that performs a specific task.
 PHP has a huge collection of internal or built-in functions that you can call directly within
your PHP scripts to perform a specific task, like gettype(), print_r(), var_dump, etc.
2) PHP User-Defined Functions
In addition to the built-in functions, PHP also allows you to define your own functions. It is a
way to create reusable code packages that perform specific tasks and can be kept and
maintained separately form main program. Here are some advantages of using functions
 Functions reduces the repetition of code within a program
 Functions makes the code much easier to maintain
 Functions makes it easier to eliminate the errors
 Functions can be reused in other application

313
330
PHP Fucnctions
Types of functions in PHP
2) PHP User-Defined Functions

314
330
PHP Fucnctions
Types of functions in PHP
2) PHP User-Defined Functions
Functions with Optional Parameters and Default Values
You can also create functions with optional parameters — just insert the parameter name, followed by an equals (=) sign,
followed by a default value, like this.

315
330
PHP Math Functions

316
330
Methods of Sending Information to Server
 web browser communicates with the server typically using one of the
two HTTP (Hypertext Transfer Protocol) methods — GET and POST.
 Both methods pass the information differently and have different
advantages and disadvantages, as described below.
The GET Method
In GET method the data is sent as URL parameters that are usually strings
of name and value pairs separated by ampersands (&).
In general, a URL with GET data will look like this:

317
330
Advantages and Disadvantages of Using the GET Method

 Since the data sent by the GET method are displayed in the URL, it is possible
to bookmark the page with specific query string values.
 The GET method is not suitable for passing sensitive information such as the
username and password, because these are fully visible in the URL query string
as well as potentially stored in the client browser's memory as a visited page.
 Because the GET method assigns data to a server environment variable, the
length of the URL is limited.
 So, there is a limitation for the total data to be sent.
 PHP provides the superglobal variable $_GET to access all the information sent
either through the URL or submitted through an HTML form using
the method="get".
318
330
Cont...d with Example

319
330
Advantages and Disadvantages of Using the POST Method
 In POST method the data is sent to the server as a package in a separate
communication with the processing script. Data sent through POST method
will not visible in the URL. Some of the advantages are
 It is more secure than GET because user-entered information is never visible in
the URL query string or in the server logs.
 There is a much larger limit on the amount of data that can be passed and one
can send text data as well as binary data (uploading a file) using POST.
 Since the data sent by the POST method is not visible in the URL, so it is not
possible to bookmark the page with specific query.
 Like $_GET, PHP provide another superglobal variable $_POST to access all the
information sent via post method or submitted through an HTML form using
the method="post".
320
330
Cont...d with Example

321
330
The $_REQUEST Variable
 PHP provides another superglobal variable $_REQUEST that contains the values
of both the $_GET and $_POST variables as well as the values of
the $_COOKIE superglobal variable.

322
330
PHP Include and Require Files
 You can save a lot of time and work through including files — Just store a block
of code in a separate file and include it wherever you want using
the include() and require() statements instead of typing the entire block of code
multiple times.
 A typical example is including the header, footer and menu file within all the
pages of a website.

323
330
The include_once and require_once Statements
If you accidentally include the same file (typically functions or classes files)
more than one time within your code using the include or require statements, it
may cause conflicts.
 To prevent this situation, PHP
provides include_once and require_once statements.
 These statements behave in the same way as include and require statements
with one exception.
 The include_once and require_once statements will only include the file once
even if asked to include it a second time i.e.
 if the specified file has already been included in a previous statement, the file
is not included again.
 To better understand how it works, let's check out an example. Suppose we've
a335'my_functions.php' file with the following code: 324
The include_once and require_once Statements

325
336
The PHP Date() Function
 The PHP date() function convert a timestamp to a more readable date and
time.
 The format parameter in the date() function is required which specifies the
format of returned date and time.
 However the timestamp is an optional parameter, if not included then current
date and time will be used. The following statement displays today's date:

<?php
$today = date("d/m/Y");
echo $today;
?>
326
336
The PHP Date() Function
<?php
echo date("d/m/Y") . "<br>";
echo date("d-m-Y") . "<br>";
echo date("d.m.Y"); ?>

<?php echo date("h:i:s") . "<br>";


echo date("F d, Y h:i:s A") . "<br>";
echo date("h:i a"); ?>

327
336
PHP Sessions
 Although you can store data using cookies but it has some security issues.
 Since cookies are stored on user's computer it is possible for an attacker to
easily modify a cookie content to insert potentially harmful data in your
application that might break your application.
 Also every time the browser requests a URL to the server, all the
cookie data for a website is automatically sent to the server within
the request.
 It means if you have stored 5 cookies on user's system, each having
4KB in size, the browser needs to upload 20KB of data each time the
user views a page, which can affect your site's performance.
328
336
PHP Sessions
 We can solve both of these issues by using the PHP session.
 A PHP session stores data on the server rather than user's computer. In a
session based environment, every user is identified through a unique number
called session identifier or SID.
 This unique session ID is used to link each user with their own information on
the server like emails, posts, etc.

329
336
Starting a PHP Session
 Before you can store any information in session variables, you must first start up the
session.
 To begin a new session, simply call the PHP session_start() function.
 It will create a new session and generate a unique session ID for the user.
 The PHP code in the example below simply starts a new session.
<?php // Starting session session_start(); ?>
 The session_start() function first checks to see if a session already exists by
looking for the presence of a session ID.
 If it finds one, i.e. if the session is already started, it sets up the session variables and
if doesn't, it starts a new session by creating a new session ID.

330
Storing and Accessing Session Data
 You can store all your session data as key-value pairs in the $_SESSION[] super
global array.
 The stored data can be accessed during lifetime of a session. Consider the
following script, which creates a new session and registers two session
variables
<?php // Starting session session_start(); // Storing session data
$_SESSION["firstname"] = "Peter";
$_SESSION["lastname"] = "Parker"; ?>
 To access the session data we set on our previous example from any other
page on the same web domain — simply recreate the session by
calling session_start() and
 then pass the corresponding key to the $_SESSION associative array.
331
Storing and Accessing Session Data

<?php // Starting session session_start(); //


Accessing session data echo 'Hi, ' .
$_SESSION["firstname"] . ' ' .
$_SESSION["lastname"]; ?>

332
PHP Form Handling
 To collect user inputs submitted through a form using the PHP superglobal
variables $_GET, $_POST and $_REQUEST.
 To create a simple HMTL contact form that allows users to enter their comment
and feedback then displays it to the browser using PHP.
 Open up your favourite code editor and create a new PHP file.
 Now type the following code and save this file as "contact-form.php" in the
root directory of your project.

333
PHP Form Handling
<!DOCTYPE html> <html lang="en">
<head> <meta charset="UTF-8">
<title>Contact Form</title> </head>
<body> <h2>Contact Us</h2>
<p>Please fill in this form and send us.</p>
<form action="process-form.php" method="post">
<p> <label for="inputName">Name:<sup>*</sup></label>
<input type="text" name="name" id="inputName"> </p>
<p> <label for="inputEmail">Email:<sup>*</sup></label>
<input type="text" name="email" id="inputEmail"> </p>
<p> <label for="inputSubject">Subject:</label>
<input type="text" name="subject" id="inputSubject"> </p>
<p> <label for="inputComment">Message:<sup>*</sup></label>
<textarea name="message" id="inputComment" rows="5" cols="30"></textarea>
</p> <input type="submit" value="Submit">
<input type="reset" value="Reset"> </form> </body> </html>
334
Capturing Form Data with PHP
 To access the value of a particular form field, you can use the following superglobal
variables.
 These variables are available in all scopes throughout a script.
 When a user submit the above contact form through clicking the submit button, the
form data is sent to the "process-form.php" file on the server for processing.
 It simply captures the information submitted by the user and displays it to browser.

335
PHP Form Handling(processing the form values)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Form</title>
</head>
<body>
<h1>Thank You</h1>
<p>Here is the information you have submitted:</p>
<ol>
<li><em>Name:</em> <?php echo $_POST["name"]?></li>
<li><em>Email:</em> <?php echo $_POST["email"]?></li>
<li><em>Subject:</em> <?php echo $_POST["subject"]?></li>
<li><em>Message:</em> <?php echo $_POST["message"]?>
</li>
</ol>
</body> Since the form data is sent through the post method, you can retrieve the value of a particular form fiel
</html> passing its name to the $_POST superglobal array, and displays each field value using echo() 347
statemen
Explanation of code

 Notice that there are two attributes within the opening <form> tag:
 The action attribute references a PHP file "process-form.php" that receives the
data entered into the form when user submit it by pressing the submit button.
 The method attribute tells the browser to send the form data through POST
method.
 Rest of the elements inside the form are basic form controls to receive user
inputs. To learn more about HTML form elements .

337
PHP Form Validation
Sanitizing and Validating Form Data
 To implement some basic security feature like sanitization and validation of the
user's input so that user can not insert potentially harmful data that
compromise the website security or might break the application.
 The following is our all-in-one PHP script which does the following things:
•It will ask the users to enter his comments about the website.
•The same script displays the contact form and process the submitted form data.

338
PHP Form Validation cont…d
 The script sanitizes and validates the user inputs. If any required field (marked
with *) is missing or validation failed due to incorrect inputs the script
redisplays the form with an error message for corresponding form field.
 The script remembers which fields the user has already filled in, and prefills
those fields when the form redisplayed due to validation error.
 If the data submitted by the user are acceptable and everything goes well it
will send an email to the website administrator and display a success message
to the user.
 See every thing in practical session validate.php

339
Explanation of code
 The filterName() function (line no-03) validate input value as person's name. A valid
name can only contain alphabetical characters (a-z, A-Z).
 The filterEmail() function (line no-14) validate input value as email address.
 The filterString() function (line no-25) only sanitize the input value by stripping HTML
tags and special characters. It doesn't validate the input value against anything.
 The attribute action=“validation.php" (line no-111) inside the <form> tag specifies
that the same validation.php file display the form as well as process the form data.
 The PHP code inside the value attribute of <input> and <textarea> e.g. <?php echo
$name; ?> display prefilled value when form is redisplayed upon validation error.
 The PHP code inside the .error class e.g. <span class="error"><?php echo $nameErr;
?></span> display error for corresponding field.

340
PHP Filters
Validating and Sanitizing Data with Filters
 Sanitizing and validating user input is one of the most common tasks in a web
application.
 To make this task easier PHP provides native filter extension that you can use to
sanitize or validate data such as e-mail addresses, URLs, IP addresses, etc.
 To validate data using filter extension you need to use the
PHP's filter_var() function.
 The basic syntax of this function can be given with:

341
PHP Filters
Sanitize a String Validate Integer Values

342
PHP Filters
validate Ip Validate Integer Values

343
PHP Filters
Sanitize and Validate Email Addresses

344
PHP Filters
Sanitize and Validate URLs
 The following example will show you how to sanitize and validate a url.

345
PHP Filters
Sanitize and Validate URLs

346
PHP Filters
Validate Integers Within a Range
 The following example will validate whether the supplied value is an integer or
not, as well as whether it lies within the range of 0 to 100 or not.

347
PHP Regular Expressions
 Regular Expressions, commonly known as "regex" or "RegExp", are a specially
formatted text strings used to find patterns in text.
 Regular expressions are one of the most powerful tools available today for
effective and efficient text processing and manipulations.
 For example, it can be used to verify whether the format of data i.e. name,
email, phone number, etc. entered by the user was correct or not, find or
replace matching string within text content, and so on.
 PHP (version 5.3 and above) supports Perl style regular expressions via
its preg_ family of functions.
 Because Perl (Practical Extraction and Report Language) was the first
mainstream programming language that provided integrated support for
regular expressions and it is well known for its strong support of regular
expressions and its extraordinary text processing and manipulation 359
PHP Regular Expressions

360
PHP Regular Expressions
Character Classes
 Square brackets surrounding a pattern of characters are called a character
class e.g. [abc].
 A character class always matches a single character out of a list of specified
characters that means the expression [abc] matches only a, b or c character.
 Negated character classes can also be defined that match any character except
those contained within the brackets. A negated character class is defined by
placing a caret (^) symbol immediately after the opening bracket, like
this [^abc].
 You can also define a range of characters by using the hyphen (-) character
inside a character class, like [0-9]. Let's look at some examples of character
classes:
361
PHP Regular Expressions

351
PHP Regular Expressions

352
PHP Regular Expressions

353
PHP MySQL injection
 SQL injection is a technique (like other web attack mechanisms)
to attack data driven applications.
 This attack can bypass a firewall and can affect a fully patched
system.
 The attacker takes the advantage of poorly filtered or not correctly
escaped characters embedded in SQL statements into parsing
variable data from user input.
 The attacker injects arbitrary data, most often a database query,
into a string that’s eventually executed by the database through a
web application (e.g. a login form).

354
PHP MySQL injection

355
PHP MySQL injection
 Through SQL Injection attacker can obtain unauthorized access to a
database and can create, read, update, alter, or delete data stored in the
back-end database.
 Currently, almost all SQL databases such as Oracle, MySQL, PostgreSQL,
MSSQL Server, MS Access are potentially vulnerable to SQL injection
attacks.
 In its most common form, a SQL injection attack gives access to
sensitive information such as social security numbers, credit card
number or other financial data.

356
PHP MySQL Introduction
 MySQL is the most popular database system used with the PHP language.
 MySQL is one of the most popular relational database system being used on the
Web today.
 It is freely available and easy to install, however if you have installed Wamp or
Xampp server it already there on your machine.
 MySQL database server offers several advantages:
 MySQL is easy to use, yet extremely powerful, fast, secure, and scalable.
 MySQL runs on a wide range of operating systems, including UNIX or Linux,
Microsoft Windows, Apple Mac OS X, and others.
 MySQL supports standard SQL (Structured Query Language)..

357
PHP MySQL Introduction
 MySQL is ideal database solution for both small and large applications.
 MySQL is developed, and distributed by Oracle Corporation.
 MySQL includes data security layers that protect sensitive data from intruders.
 MySQL database stores data into tables like other relational database.
 A table is a collection of related data, and it is divided into rows and columns.
 Each row in a table represents a data record that are inherently connected to
each other such as information related to a particular person, whereas each
column represents a specific field such as id, first_name, last_name, email, etc.
 The structure of a simple MySQL table that contains person's general
information may look something like this:

358
PHP MySQL Introduction

359
PHP MySQL Introduction
Talking to MySQL Databases with SQL
 SQL, the Structured Query Language, is a simple, standardized language for
communicating with relational databases like MySQL.
 With SQL you can perform any database-related task, such as creating databases
and tables, saving data in database tables, query a database for specific records,
deleting and updating data in databases.
 Look at the following standard SQL query that returns the email address of a
person whose first name is equal to 'Peter' in the persons table:
 SELECT email FROM persons WHERE first_name="Peter“
 If you execute the SQL query above it will return the following record:
Output is look like
peterparker@mail.com 371
PHP Connect to MySQL Server
Ways of Connecting to MySQL through PHP
 In order to store or access the data inside a MySQL database, you first need to
connect to the MySQL database server.
 PHP offers two different ways to connect to MySQL server: MySQLi (Improved
MySQL) and PDO (PHP Data Objects) extensions.
 While the PDO extension is more portable and supports more than twelve
different databases, MySQLi extension as the name suggests supports MySQL
database only.
 MySQLi extension however provides an easier way to connect to, and execute
queries on, a MySQL database server.
 Both PDO and MySQLi offer an object-oriented API, but MySQLi also offers a
procedural API which is relatively easy for beginners to understand. 372
PHP Connect to MySQL Server
Ways of Connecting to MySQL through PHP
 In order to store or access the data inside a MySQL database, you first need to
connect to the MySQL database server.
 PHP offers two different ways to connect to MySQL server: MySQLi (Improved
MySQL) and PDO (PHP Data Objects) extensions.
 While the PDO extension is more portable and supports more than twelve
different databases, MySQLi extension as the name suggests supports MySQL
database only.
 MySQLi extension however provides an easier way to connect to, and execute
queries on, a MySQL database server.
 Both PDO and MySQLi offer an object-oriented API, but MySQLi also offers a
procedural API which is relatively easy for beginners to understand.
362
PHP Connect to MySQL Server
Connecting to MySQL Database Server
 In PHP you can easily do this using the mysqli_connect() function. All
communication between PHP and the MySQL database server takes place
through this connection.
 Here're the basic syntaxes for connecting to MySQL using MySQLi and PDO
extensions:

36
3
PHP Connect procedural
<?php/* Attempt MySQL server
connection. Assuming you are running
MySQL
server with default setting (user
'root' with no password) */
$link = mysqli_connect("localhost",
"root", "");
// Check connection
if($link === false){
die("ERROR: Could not connect. "
. mysqli_connect_error());
}
// Print host information
echo "Connect Successfully.
Host info: " .
mysqli_get_host_info($link); 375
?>
PHP Connect Object oriented
<?php
/* Attempt MySQL server connection. Assuming you are running
MySQL
server with default setting (user 'root' with no password) */
$mysqli = new mysqli("localhost", "root", "", "test");
// Check connection
if($mysqli === false){
die("ERROR: Could not connect. " . $mysqli>connect_error);
}
// Print host information
echo "Connect Successfully. Host info: " . $mysqli->host_info;
// Close connection
$mysqli->close();
?>

376
PHP Connect PDO
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
try{
$pdo = new PDO("mysql:host=localhost;dbname=demo", "root", "");
// Set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Print host information
echo "Connect Successfully. Host info: " .
$pdo->getAttribute(constant("PDO::ATTR_CONNECTION_STATUS"));
} catch(PDOException $e){
die("ERROR: Could not connect. " . $e->getMessage());
}
// Close connection
unset($pdo);
?> 377
PHP MySQL Create Database
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", ""); // Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}// Attempt create database query execution
$sql = "CREATE DATABASE sampe1";
if(mysqli_query($link, $sql)){
echo "Database created successfully";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
} // Close connection
mysqli_close($link);
?> 378
PHP MySQL Create Tables
<?php if(mysqli_query($link, $sql)){
$link = mysqli_connect("localhost", echo "Table created
"root", "", "sampe1"); successfully.";
// Check connection } else{
if($link === false){ echo "ERROR: Could not able to
die("ERROR: Could not connect. " .execute $sql. " . mysqli_error($link)
mysqli_connect_error()); }
}
// Attempt create table query // Close connection
execution mysqli_close($link);
$sql = "CREATE TABLE persons( ?>
id INT NOT NULL PRIMARY KEY
AUTO_INCREMENT,
first_name VARCHAR(30) NOT NULL,
last_name VARCHAR(30) NOT NULL,
379
email VARCHAR(70) NOT NULL UNIQUE
PHP MySQL insert data to Tables
<?php (first_name, last_name, email) VALUES
/* Attempt MySQL server connection. ('Peter', 'Parker',
Assuming you are running MySQL 'peterparker@mail.com')";
server with default setting (user if(mysqli_query($link, $sql)){
'root' with no password) */ echo "Records inserted
$link = mysqli_connect("localhost", successfully.";
"root", "", "sampe1"); } else{
echo "ERROR: Could not able to
// Check connection execute $sql. " .
if($link === false){ mysqli_error($link);
die("ERROR: Could not connect. " }
. mysqli_connect_error());
} // Close connection
mysqli_close($link);
// Attempt insert query execution ?>
380
$sql = "INSERT INTO persons
PHP MySQL insert multiple data to Tables
<?php 'clarkkent@mail.com'),
/* Attempt MySQL server connection. ('John', 'Carter',
Assuming you are running MySQL 'johncarter@mail.com'),
server with default setting (user 'root' ('Harry', 'Potter',
with no password) */ 'harrypotter@mail.com')";
$link = mysqli_connect("localhost", if(mysqli_query($link, $sql)){
"root", "", "sampe1"); echo "Records added successfully.";
// Check connection } else{
if($link === false){ echo "ERROR: Could not able to execute
die("ERROR: Could not connect. " . $sql. " . mysqli_error($link);
mysqli_connect_error()); }
}
// Attempt insert query execution // Close connection
$sql = "INSERT INTO persons (first_name, mysqli_close($link);
last_name, email) VALUES ?>
('John', 'Rambo',
'johnrambo@mail.com'),
('Clark', 'Kent', 381
Insert Data into a Database from an HTML Form
Step 1: Creating the HTML Form <label for="lastName">Last Name:</label>
Here's a simple HTML form that has three <input type="text" name="last_name"
text <input> fields and a submit button. id="lastName">
<!DOCTYPE html> </p>
<html lang="en"> <p>
<head> <label for="emailAddress">Email Address:</label>
<meta charset="UTF-8"> <input type="text" name="email"
<title>Add Record Form</title> id="emailAddress">
</head> </p>
<body> <input type="submit" value="Submit">
<form action="insert.php" method="post"> </form>
<p> </body>
<label for="firstName">First Name:</label> </html>
<input type="text" name="first_name"
id="firstName">
</p>
<p>
382
Insert Data into a Database from an HTML Form
Step 2: Retrieving and Inserting the Form Data // Escape user inputs for security
 add record HTML form, in the example above, the $first_name = mysqli_real_escape_string($link,
form data is sent to 'insert.php' file. $_REQUEST['first_name']);
 The 'insert.php' file connects to the MySQL database $last_name = mysqli_real_escape_string($link,
server, retrieves forms fields using the $_REQUEST['last_name']);
PHP $_REQUEST variables and finally execute the $email = mysqli_real_escape_string($link,
insert query to add the records. $_REQUEST['email']);
<?php // Attempt insert query execution
/* Attempt MySQL server connection. Assuming you are $sql = "INSERT INTO persons (first_name, last_name,
running MySQL email) VALUES ('$first_name', '$last_name', '$email')";
server with default setting (user 'root' with no password) if(mysqli_query($link, $sql)){
*/ echo "Records added successfully.";
$link = mysqli_connect("localhost", "root", "", "demo"); } else{
echo "ERROR: Could not able to execute $sql. " .
// Check connection mysqli_error($link);
if($link === false){ }// Close connection
die("ERROR: Could not connect. " . mysqli_close($link);
mysqli_connect_error()); ?> 383
}
How to Get the ID of Last Inserted Row
<?php last_name, email) VALUES ('Ron', 'Weasley',
/* Attempt MySQL server connection. 'ronweasley@mail.com')";
Assuming you are running MySQL if(mysqli_query($link, $sql)){
server with default setting (user 'root' with no // Obtain last inserted id
password) */ $last_id = mysqli_insert_id($link);
$link = mysqli_connect("localhost", "root", "", echo "Records inserted successfully. Last
"sampe1"); inserted ID is: " . $last_id;
} else{
// Check connection echo "ERROR: Could not able to execute
if($link === false){ $sql. " . mysqli_error($link);
die("ERROR: Could not connect. " . }
mysqli_connect_error());
} // Close connection
mysqli_close($link);
// Attempt insert query execution ?> 384
$sql = "INSERT INTO persons (first_name,
PHP MySQL SELECT Query
Selecting Data From Database Tables
SELECT column1_name, column2_name, columnN_name FROM table_name;

374
PHP MySQL WHERE Clause
Filtering the Records
 The WHERE clause is used to extract only those records that fulfill a specified condition.
 The basic syntax of the WHERE clause can be given with:
SELECT column_name(s) FROM table_name WHERE column_name operator value

375
PHP MySQL WHERE Clause
Filtering the Records echo "<tr>";
<?php echo "<td>" . $row['id'] . "</td>";
/* Attempt MySQL server connection. Assuming you are running echo "<td>" . $row['first_name'] . "</td>";
MySQL echo "<td>" . $row['last_name'] . "</td>";
server with default setting (user 'root' with no password) */ echo "<td>" . $row['email'] . "</td>";
$link = mysqli_connect("localhost", "root", "", "sampe1"); echo "</tr>";
// Check connection }
if($link === false){ echo "</table>"; // Close result set
die("ERROR: Could not connect. " . mysqli_connect_error()); mysqli_free_result($result);
}// Attempt select query execution } else{
$sql = "SELECT * FROM persons WHERE first_name='john'"; echo "No records matching your query were found.";
if($result = mysqli_query($link, $sql)){ }
if(mysqli_num_rows($result) > 0){ } else{
echo "<table border='1px'>"; echo "ERROR: Could not able to execute $sql. " .
echo "<tr>"; mysqli_error($link);
echo "<th>id</th>"; }// Close connection
echo "<th>first_name</th>"; mysqli_close($link);
echo "<th>last_name</th>"; ?>
echo "<th>email</th>";
echo "</tr>"; 387
while($row = mysqli_fetch_array($result)){
PHP MySQL LIMIT Clause
Limiting Result Sets
SELECT column_name(s) FROM table_name LIMIT row_offset, row_count;

388
PHP MySQL Limit Clause
<?php while($row = mysqli_fetch_array($result)){
/* Attempt MySQL server connection. Assuming you are running echo "<tr>";
MySQL echo "<td>" . $row['id'] . "</td>";
server with default setting (user 'root' with no password) */ echo "<td>" . $row['first_name'] . "</td>";
$link = mysqli_connect("localhost", "root", "", "sampe1"); echo "<td>" . $row['last_name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
// Check connection echo "</tr>";
if($link === false){ }
die("ERROR: Could not connect. " . mysqli_connect_error()); echo "</table>";
} // Close result set
// Attempt select query execution mysqli_free_result($result);
$sql = "SELECT * FROM persons LIMIT 2"; } else{
if($result = mysqli_query($link, $sql)){ echo "No records matching your query were found.";
if(mysqli_num_rows($result) > 0){ }
echo "<table border='1px'>"; } else{
echo "<tr>"; echo "ERROR: Could not able to execute $sql. " .
echo "<th>id</th>"; mysqli_error($link);
echo "<th>first_name</th>"; }// Close connection
echo "<th>last_name</th>"; mysqli_close($link);
echo "<th>email</th>"; ?> 389
echo "</tr>";
PHP MySQL ORDER BY Clause
Ordering the Result Set
 The ORDER BY clause can be used in conjugation with the SELECT statement to see
the data from a table ordered by a specific field.
 The ORDER BY clause lets you define the field name to sort against and the sort
direction either ascending or descending.
The basic syntax of this clause can be given with:
SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC

390
PHP MySQL order Clause
<?php echo "<td>" . $row['id'] . "</td>";
/* Attempt MySQL server connection. Assuming you are echo "<td>" . $row['first_name'] . "</td>";
running MySQL echo "<td>" . $row['last_name'] . "</td>";
server with default setting (user 'root' with no password) */ echo "<td>" . $row['email'] . "</td>";
$link = mysqli_connect("localhost", "root", "", "sampe1"); echo "</tr>";
// Check connection }
if($link === false){ echo "</table>";
die("ERROR: Could not connect. " . mysqli_connect_error()); // Close result set
}// Attempt select query execution with order by clause mysqli_free_result($result);
$sql = "SELECT * FROM persons ORDER BY first_name"; } else{
if($result = mysqli_query($link, $sql)){ echo "No records matching your query were found.";
if(mysqli_num_rows($result) > 0){ }
echo "<table border='solid 1px'>"; } else{
echo "<tr>"; echo "ERROR: Could not able to execute $sql. " .
echo "<th>id</th>"; mysqli_error($link);
echo "<th>first_name</th>"; }
echo "<th>last_name</th>"; // Close connection
echo "<th>email</th>"; mysqli_close($link);
echo "</tr>"; ?>
while($row = mysqli_fetch_array($result)){ 391
echo "<tr>";
PHP MySQL UPDATE Query
 The UPDATE statement is used to change or modify the existing records in a
database table.
 This statement is typically used in conjugation with the WHERE clause to apply
the changes to only those records that matches specific criteria.

$sql = "UPDATE persons SET email='Daniel Getaye' WHERE id=1";

381
PHP MySQL DELETE Query
 Just as you insert records into tables, you can delete records from a table using
the SQL DELETE statement.
 It is typically used in conjugation with the WHERE clause to delete only those
records that matches specific criteria or condition.
 The basic syntax of the DELETE statement can be given with:
DELETE FROM table_name WHERE column_name=some_value

382
PHP MySQL Login System
 User authentication is very common in modern web application.
 It is a security mechanism that is used to restrict unauthorized access to
member-only areas and tools on a site.
Building the Registration System
Step 1: Creating the Database Table
Execute the following SQL query to create the users table inside your MySQL
database.
CREATE TABLE users (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
); 394
PHP MySQL Login System
Step 2: Creating the Config File
After creating the table, we need create a PHP script in order to connect to the
MySQL database server. Let's create a file named "config.php" and put the
following code inside it.
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'sampe1');
/* Attempt to connect to MySQL database */
$link = mysqli_connect(DB_SERVER, DB_USERNAME,
DB_PASSWORD, DB_NAME);
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?> 395
PHP MySQL Login System
Step 3: Creating the Registration Form
 Let's create another PHP file "register.php" and put the following example
code in it.
 This example code will create a web form that allows user to register
themselves.
 This script will also generate errors if a user tries to submit the form without
entering any value, or if username entered by the user is already taken by
another user.

385
PHP MySQL Login System
Step 1: Creating the Login Form
 When user submit the form these inputs will be verified against the
credentials stored in the database, if the username and password match, the
user is authorized and granted access to the site, otherwise the login attempt
will be rejected.
 Let's create a file named "login.php" and place the following code inside it.

386
PHP MySQL Login System
Step 2: Creating the Welcome Page

Step 3: Creating the Logout Script

Adding the Password Reset Feature


You can find it the complete lab manual which we discussed in our lab session

387
PHP MySQL Login System
Step 2: Creating the Welcome Page

Step 3: Creating the Logout Script

Adding the Password Reset Feature


You can find it the complete lab manual which we discussed in our lab session

388
Any ambiguous

Questions

389

You might also like