[go: up one dir, main page]

0% found this document useful (0 votes)
7 views306 pages

Web Engineering

The document outlines the syllabus for a Web Engineering course at Sardar Patel University, covering topics such as HTML, JavaScript, PHP, AJAX, and e-commerce security. It details the structure and features of HTML, including its advantages and disadvantages, as well as the basic components of HTML documents. Additionally, it discusses the classification of HTML tags, attributes, and the layout of HTML documents.

Uploaded by

diwanhitesh68
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views306 pages

Web Engineering

The document outlines the syllabus for a Web Engineering course at Sardar Patel University, covering topics such as HTML, JavaScript, PHP, AJAX, and e-commerce security. It details the structure and features of HTML, including its advantages and disadvantages, as well as the basic components of HTML documents. Additionally, it discusses the classification of HTML tags, attributes, and the layout of HTML documents.

Uploaded by

diwanhitesh68
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 306

Web Engineering BE CSE SEM-VII

As Per New Course Prescribed By Sardar Patel


University

Web Engineering

BE CSE – IV
Sem - VII

By

Dr. Munesh S. Thakre

(Phd, M.Phil(IT), MCA, MCM, M.COM, B.Ed, P.G.D.C.C.A., P.G.D.C.A., D.C.A.)

Developed By. Dr. Munesh Thakre Page 1 of 306


Web Engineering BE CSE SEM-VII

CSE703 Web Engineering


Unit – I
Introduction: Web browsers and its functions, web optimizations; Static page design; designing static
web pages with HTML5.0-HTML basic, multimedia, Graphics, Form tags, CSS 2.0 concept and its
properties & CSS 3.0 properties i.e. borders, backgrounds, fonts, text effects, Buffering, Weblog,
Web Cache Poisoning.
Unit – II
JavaScript: Document Object Model (DOM), Obtaining user inputs, memory concepts, Operators,
Control Structures, Looping constructs, break, continue statements, Programmer defined functions,
Scoping rules, Recursion and iteration, Array declaration and allocation, passing arrays to function,
Objects: String, Date, Boolean, Window, document; using cookies, form validation in Java Script,
Handling Events Using JavaScript.
Unit – III
PHP: Installing and Configuring MySQL and PHP, Basic Security Guidelines, Variables, Data
Types, Operators and Expressions, Constants, Flow Control Functions; Switching Flow, Loops,
Code Blocks and Browser Output, Objects, Strings Processing, Form processing, Connecting to
database, cookies, Session, dynamic contents.
Unit – IV
Introduction to AJAX: Exploring different web technologies, Creating a simple AJAX application,
Interacting with the Web Server Using the XMLHttpRequest Object, Create an XMLHttpRequest
Object, Interact with the Web Server. Differentiating AJAX and Non-AJAX application.
Search engine optimization for individual web pages: header entries, tags, selection of URL, alt tags,
Search engine optimization for entire website: Hyperlinks and link structure, page rank of Google,
click rate, residence time of website.
Unit – V
E-Commerce & Security: E- Commerce: Business Models, Infrastructure, Creating an E-commerce
Web Site, Environment and Opportunities. Modes & Approaches, Marketing & Advertising
Concepts. Electronic Publishing issues, approaches, legalities and technologies, Secure Web
document, Digital Signatures and Firewalls, Cyber crime and laws, IT Act. Electronic Cash,
Electronic Payment Systems: RTGS, NEFT, Internet Banking, Credit/Debit Card. Security: Digital
Certificates & Signatures, SSL, SET, 3D Secure Protocol.

Developed By. Dr. Munesh Thakre Page 2 of 306


Web Engineering BE CSE SEM-VII

Unit – I
Introduction to HTML
HTML stands for Hyper Text Markup Language, which is the most widely used language on
Web to develop web pages. HTML was created by Berners-Lee in late 1991 but "HTML 2.0" was
the first standard HTML specification which was published in 1995. HTML 4.01 was a major
version of HTML and it was published in late 1999. Though HTML 4.01 version is widely used but
currently we are having HTML-5 version which is an extension to HTML 4.01, and this version
was published in 2012.
HTML is the standard markup language for creating Web pages.
 HTML stands for Hyper Text Markup Language
 HTML describes the structure of a Web page
 HTML consists of a series of elements
 HTML elements tell the browser how to display the content
 HTML elements are represented by tags
 HTML tags label pieces of content such as "heading", "paragraph", "table", and so on
 Browsers do not display the HTML tags, but use them to render the content of the page

Why to Learn HTML?


Originally, HTML was developed with the intent of defining the structure of documents like
headings, paragraphs, lists, and so forth to facilitate the sharing of scientific information between
researchers. Now, HTML is being widely used to format web pages with the help of different tags
available in HTML language.
HTML is a MUST for students and working professionals to become a great Software Engineer
especially when they are working in Web Development Domain. I will list down some of the key
advantages of learning HTML:
 Create Web site - You can create a website or customize an existing web template if you
know HTML well.
 Become a web designer - If you want to start a carrer as a professional web designer,
HTML and CSS designing is a must skill.
 Understand web - If you want to optimize your website, to boost its speed and performance,
it is good to know HTML to yield best results.

Developed By. Dr. Munesh Thakre Page 3 of 306


Web Engineering BE CSE SEM-VII

 Learn other languages - Once you understands the basic of HTML then other related
technologies like javascript, php, or angular are become easier to understand.
Features of HTML
1. HTML uses a set of tags that is used to create document and then it can be published on the
World Wide Web.
2. HTML is platform independent. It is supported by all types of operating system and browser.
3. HTML lets user jump from topic to topic or page by page rather than finding and reading
information linearly by means of hyperlink.
4. Documents prepared in HTML include reference graphics and formatting tags.
5. It helps in creating or building Table either symmetrical or Asymmetrical shape.
6. HTML supports the concept of Frames, Image and Animating effects.
7. It contains powerful Formatting facilities for Text, Images.
8. It is used to improve the appearance of web pages.
9. It supports various types of appearance of web pages.
10. HTML supports form which make it possible to create document that collect and process user
input.
11. It tells how to make a document interactive through special hypertext links etc.

Advantages of HTML
1. For creating HTML document, only text editor is needed. No special software is required. For
example, in Windows Notepad editor is sufficient for creating HTML document.
2. HTML contains powerful formatting facilities by means of various formatting tags.
3. Linking to various pages and thus one can navigate all the web pages.
4. It is used to learn and master high level programming language.

Disadvantages of HTML
1. HTML does not offer programming language features and capabilities.
2. Any simple calculation cannot be done in HTML.
3. HTML lacks structure.
4. It can not be used to display even date and time.
5. The interactive web pages can not be built in HTML.
6. The web pages developed in HTML cannot behave like an application.
7. The web pages developed in HTML do not have their own interface.

Developed By. Dr. Munesh Thakre Page 4 of 306


Web Engineering BE CSE SEM-VII

8. HTML lacks syntactic checking i.e. you can not validate HTML code and required special types
of software like scripting languages.

HTML Editors
HTML documents are basically plain text and known as ASCII text editor. There are various types of
editors for different platforms. Aprt from basic text editor some operating system supports
WYSIWYG (What You Seen Is What You Get) editors.
Steps to Create and View HTML Document
1. Open a Text Editor ex. Notepad.
2. Write the appropriate HTML code line by line.
3. Save the HTML code in the file having extension .HTML.
4. Open the Browser (ex. Internet Explorer).
5. Browse the file or type in the appropriate address of the HTML file in the address bar to view the
HTML page and press OK button.
6. Now web page will be displayed on the screen.

Basic Structure of HTML Program


An HTML document or web page is compised to two basic elements.
1. Contents: It may comprise of text and images to be displayed on web page.
2. Tags/Elements: It is an instruction that is followed by the Web Browser to display the
contents in a partuclar manner.
Every HTML document has the same general structure and it consists of few tags that define the
page as a whole. The primary part of the HTML document are denoted by <HTML>, <HEAD>,
<TITLE>, <BODY> tags. Each of these tag are known as document structure tags.
This two (a) The head (b) The body are enclosed in <HTML> and </HTML> tags. Complete
structure of HTML is given below:
<HTML>
<HEAD>
<TITLE>
Title of the doucment
</TITLE>
</HEAD>
<BODY>

Developed By. Dr. Munesh Thakre Page 5 of 306


Web Engineering BE CSE SEM-VII

Actual Document
</BODY>
</HTML>
Hello World using HTML.
Just to give you a little excitement about HTML, I'm going to give you a small conventional HTML
Hello World program.
<!DOCTYPE html>
<html>
<head>
<title>This is document title</title>
</head>
<body>
<h1>This is a heading</h1>
<p>Hello World!</p>
</body>
</html>
Example Explained
 The <!DOCTYPE html> declaration defines this document to be HTML5
 The <html> element is the root element of an HTML page
 The <head> element contains meta information about the document
 The <title> element specifies a title for the document
 The <body> element contains the visible page content
 The <h1> element defines a large heading
 The <p> element defines a paragraph

Applications of HTML
As mentioned before, HTML is one of the most widely used language over the web. I'm going to
list few of them here:
 Web pages development - HTML is used to create pages which are rendered over the web.
Almost every page of web is having html tags in it to render its details in browser.
 Internet Navigation - HTML provides tags which are used to navigate from one page to
another and is heavily used in internet navigation.
 Responsive UI - HTML pages now-a-days works well on all platform, mobile, tabs, desktop
or laptops owing to responsive design strategy.
 Offline support HTML pages once loaded can be made available offline on the machine
without any need of internet.

Developed By. Dr. Munesh Thakre Page 6 of 306


Web Engineering BE CSE SEM-VII

 Game development- HTML5 has native support for rich experience and is now useful in
gaming developent arena as well.

Classification of HTML Tags


HTML document or tags can be classified as:
1. Document Section Tags by using <HEAD> tags.
2. Body Section Tags
The Head
It is like an introduction to the page. It generally consists of title of the page. To define head add
<HEAD> tag at beginning and </HEAD> tag at the end. To define title we can enclosed the
document in between <TITLE> and </TITLE> tag.
The Body
In this user enters the text, images, sound and other animated tags that will appear on the web page.
To define body, place <BODY> tag at beginning and </BODY> at the end, after the head.

Tag and Tag Attribute of HTML


Tags
A tag is a single unit of markup. It is a set of symbols define in HTML, to have special meaning tags
are commands of instructions that are written directly into text editor. Tags start with open angle
brackets (<) followed by a keyword and end with close angle bracket (>). Tags are not displayed in
web browser but there effects are displayed on web page. Thus, web browser interprets Tags defined
within angle bracket (< >) as special text rather than considering it as simple text.
Syntax :
<TAG>
Example:
<B> Bold </B>
Types of Tags
The two types of tags present in HTML are:
1. Pair Tags
2. Singular Tags
1. Pair Tags
Pair tags consists of following:

Developed By. Dr. Munesh Thakre Page 7 of 306


Web Engineering BE CSE SEM-VII

a. Start Tags
b. End Tags
Start tags are used to begin an effect and end tags are used to end that effect. Name of end tag is
same as the start tag but the name of end tags preceded by a forward slash (/). Tags that include
pair ags are called container tags, as they hold or contain the text and other HTML elements
between the two tags.
Syntax:
<TAG> CONTENTS </TAG>
Example:
<B>Hello World</B>
<B> is bold tag. The text written between start <B> and end tag </B> will be displayed in bold.
2. Singular Tags
This kind of tag consists of only start tags and does not need to end with end tags and known as
standalone ta. This tags does not contain any contents and hence known as Empty Tags.
Example: <BR> which helps to break current line.

Tag Attribute
Attributes are the properties/elements/parameters of the tag. It is placed within tags. It modifies the
effect of a tag. A general syntax is:
<Tag Attribute1 = “value” Attribute2 = “value”, …. AttributeN = “value”>
An attribute value must be enclosed either within single or double quotes but if value itself contains
double quotes then one must enclose entire value within single quotes. Attributes within tag are
separated by single space.
Some important features of tags are:
 Some tags have no attributes. For example: <BR>
 One may specify multiple attributes with a single tag and they may appear in any order.
Eample:
<BODY BGCOLOR=“GREEN” BACKGROUND= “COMPUTER.GIF” TEXT= “RED”>
Attribute Values
All most all, the attributes used in tag have certain value. Note the following important points related
to attribute values.
1. Sometimes one must pick a value from a group of options say Align Attribute contains values
like Left, Center or Right.

Developed By. Dr. Munesh Thakre Page 8 of 306


Web Engineering BE CSE SEM-VII

2. Sime attribute does not have ay value for example; COMPACT attribute used in List or
NOSHADE in <HR> tag does not have any value.
3. Some attribute are stricter regarding the kind of value they accept for example SRC attribute of
<IMG> tag will accept only URLs.
4. Some attribute automatically take default value when value is not specified but attribute is
defined. For example, BORDER attribute in <TABLE> tag automatically take a default value 2
pixels.
5. Some attributes automatically pick up the value among many. For example FACE attribute of
<FONT> tag. One may specify more than one values to this attribute, browser will select
automatically matching font.

Document Layout Tag


It is also known as structure tags. An HTML document pages has following basic element:
1. <HTML> </HTML>
2. <HEAD> </HEAD>
3. <TITLE> </TITLE>
4. <BODY> </BODY>
1. HTML Tag
This tag indicates to the browser that the file is an HTML file. A basic HTML document consists
of opening <HTML> and closing </HTML> tags. All the content of the web page is contained
within these two tags.
Example:
<HTML>
HTML Tags and Contents
</HTML>
2. Putting header using HEAD Tag
A HTML document has a pair of opening <HEAD> and closing </HEAD> tag. Any information
typed here will appear in the viewing area of the web browser. The <HEAD> tag contains the
optional <TITLE> tag.
Example:
<HTML>
<HEAD>
<TITLE>

Developed By. Dr. Munesh Thakre Page 9 of 306


Web Engineering BE CSE SEM-VII

Demo of HTML
</TITLE>
</HEAD>
</HTML>
3. TITLE Tag
The content of this tag is displayed is the Title bar of any web browser window. It should be
unique and descriptive because it is used by search engines as a search criterion for any
information. In the absence of this tag, web browser displays the entire path of HTML file.
Example:
<HTML>
<HEAD>
<TITLE>
Demo of HTML
</TITLE>
</HEAD>
</HTML>
4. Main body of text using BODY Tag
This body tags is basically a block level tags that specify what the web browser should display in
the web browser window. Styles and formatting are applied to the content using tags, such as
heading tags, paragraph tags and font tags. Most of the tags are a part of the <BODY> tag. Some
examples of tag that are the part of the <BODY> tag are:
<H1> Heading Levels
<BR> Break Line
<HR> Horizontal Rule
<FORM> Insert Forms
<P> Paragraph
Various attributes of Body tag are:
1 BGCOLOR Changes the background color that is specified within tag. For
Example: <BODY BGCOLOR = “GREEN”>
2 BACKGROUND Change the background of web page with specific image. For
example: <BODY BACKGROUND = “COMPUTER.GIF”
3 TEXT It helps you display the contents of text with a specific color. For
example: <BODY TEXT = “READ”>

Developed By. Dr. Munesh Thakre Page 10 of 306


Web Engineering BE CSE SEM-VII

4 LINK Will set the color for the normal blue colored hyperlinks that you
see on web page by default. It will only change the color of the
unvisited hyperlink.
5 VLINK Will set the color of visited hyperlinks. By default Purple Color.
6 ALINK Will set the activated link color. This is the color that you see
when the mouse is pressed on a link but not released. By default
Red color.
7 STYLE Recent browser software uses this attribute to specify background
image. URL reference is enclosed within in the URL() keyword.

Classification of HTML Tags that appear in Body Section of HTML


HTML, Body tags can be classified as:
1. Logical Tags
2. Layout Tags
3. Text Formatting Tags
4. List Tags
5. Multimedia Tags
6. Miscellaneous Tags

1. Logical Tags(Comments)(Hiding text)


Anything that is enclosed within a pair of <!-- ………… --> is considered as a comment and
known as logical tags. These comments are included for some documentation or explaination.
This is greatly helpful to other users to understand the purpose of HTML programs or tags. There
is no restriction on number of comments that can be included in HTML file. These comments are
ignored by browser on loading HTML page i.e. it is not visible when document is loaded by web
browser.
Comment tag is an empty tag. Comment tag consists of:
a. Opening angle bracket ( < ), followed by
b. The exclamation ( ! ) symbol followed by
c. Double Dash ( -- ) followed by
d. Horizontal space, followed by
e. Any comment in the form of text. This text may of any length and in any case letter, followed
by

Developed By. Dr. Munesh Thakre Page 11 of 306


Web Engineering BE CSE SEM-VII

f. Horizontal space, followed by


g. Double Dash ( -- ) and finally
h. Closing angle bracket ( > ).
Example:
Write a program for the illustration of 'Comment Tag' in HTML.
<HTML>
<HEAD>
<TITLE>
DEMONSTRATION OF ATTRIBUTES
</TITLE>
</HEAD>
<BODY TEXT="NAVY" LINK="BLUE" ALINK="RED" VLINK="BLUE" BGCOLOR= "GREEN">
<P>THIS IS THE DEMO TEXT </P>
<BR>
<BR>
<A HREF="E:\BCAFINAL\HTM\PRG1.HTML">SHOW</A>
</BODY>
</HTML>

2. Layout Tags
These tags add white spaces to web page to display contents in a better look or design and it I
equivalent to <Ente> key in word processing documents. It supports following features:
 Helps in displaying the contents of web pages into logical section.
 It affects the structure, spacing and layout of a web page.
 Layout tags consist of following tags:
1. Break Tag
2. Paragraph Tag
<BR> Tag (Line Break)
The <BR> tag inserts a line break into a text flow. When the text needs to starts from a new lines
and not continue on the same line, the <BR> tag should be used. It has no ending tag.
Example:
Write a program for illustration of 'Line Break tag'.
<HTML>
<HEAD>
<TITLE>
DEMONSTRATION OF ATTRIBUTES
</TITLE>
</HEAD>
<BODY TEXT="NAVY"LINK="BLUE"ALINK="RED"VLINK="BLUE" BGCOLOR="GREEN">
<P>THIS IS THE DEMO TEXT </P>
<BR>
<BR>
<A HREF="E:\BCAFINAL\HTM\PRG1.HTML">SHOW</A>
</BODY>
</HTML>

Developed By. Dr. Munesh Thakre Page 12 of 306


Web Engineering BE CSE SEM-VII

<P> Tag ( Paragraph Tag)


The <P> tag defines the paragraph of the text. Each paragraph is starts with <P> and end with
the corresponding closing </P> tags. The end </P.> is usually omitted. The <P> tag contents
text. The <P> tag provides four kinds of contents four kind of justification Left, Right, Justify
and Center can be assign with the attribute ALIGN.

Example:
Write a program for illustration of 'Paragraph Tag'.

<HTML>
<HEAD>
<TITLE>
DEMONSTRATION OF ATTRIBUTES
</TITLE>
</HEAD>
<BODY>
<P ALIGN="RIGHT">
It is called the relative address because it is "relative to our present location" which in the above
example.
</P>
<!--Illustration of comment-->
</BODY
</HTML>

Attributes of Paragraph Tag


<P> tag has one optional attribute called align which by default is left align. It allows to specify
wher the text appear on the screen.
1. <P Align= “Left”> text is aligned to left (default).
2. <P Align= “Right”> text is aligned to right.
3. <P Align= “Center”> text is aligned to center.
When a paragraph has align other than left value than some browsers do not use default
alignment i.e. left for the next paragraph implicitly.

3. Text and Character Formatting Tags


In the page the character can be made bold, italic, underline etc. by using some HTML tags.
There are two methods of formatting characters. They are:
1. Logical Styles
2. Physical Styles
1. Logical Styles

Developed By. Dr. Munesh Thakre Page 13 of 306


Web Engineering BE CSE SEM-VII

The logical styles inform the browser what kind of text to present. The browser takes care of how
to present it. For example consider the <em> tag. This tag tells that emphasis must be given. The
browser takes care of how to present it so that it gets the emphasis required. Lists of the logical
style tags are given below:
<CITE>---</CITE> This tag is used for citation or references to other sources or
writing information regarding the authorship. This element
can be used for writing short quotations. Internet Explorer
rendered text within these elements in Italics.
<CODE>--</CODE> Used for source code example. Internet Explorer renders this
text in small font. It is normally used for writing source code
example.

<DFN>---</DFN> This text is an element i.e. used to indicate that a word or


phrase is a definition. Internet Explorer renders text in Italic.
<EM>---</EM> This text is used to put emphases on the enclosed text.
Internet Explorer renders the text in Italic.
<KBD>---</KBD> This is used to identify text that a user is supposed to enter
generally rendered in small font.
<SAMP>---</SAMP> This element describes text that is output from a program. It
is renders in small font.
<STRONG>---</STRONG> Render the text with strong emphasis. It appears in bold.
<VAR> ……… </VAR> This value is displayed as italic or underline and it indicates
the name of the variable.
Example:
<HTML>
<HEAD>
<TITLE>Demo of Logical Format</TITLE>
</HEAD>
<BODY>
<EM>Education means knowing from known</EM><BR>
<STRONG>Life is what you decide</STRONG>
</BODY>
</HTML>

2. Physical Styles
The physical styles format tags implicitly informs the browser how the characters must be shown
bold, italic, etc. Physical style tags are given below with its meaning.
<B> …. </B> The <B> tag Boldfaces of characters or segments of text i.e.
enclosed between the tag </B> and its corresponding </B>
end tag.
<BIG>---</BIG> <BIG> Tag: It renders tags between it and its </BIG> tag one

Developed By. Dr. Munesh Thakre Page 14 of 306


Web Engineering BE CSE SEM-VII

fonts size larger than surrounding text.


<I>---</I> The <I> tag and its </I> end tag render the enclosed text in an
italic Typeface.
<SMALL>---</SMALL> <SMALL> Tag: It renders tags between it and its </SMALL>
tag one fonts size smaller than surrounding text.
<STRIKE>---</STRIKE>
<SUB>---</SUB> <SUB> Tag i.e.(Subscript): The <SUB> tags text content
between the <SUB> tag and its </SUB> tag can display half a
character height lower, but in the same font and size i.e. this
tag is used to subscript the text.
<SUP>---</SUP> <SUP> Tag i.e.(Superscript): The <SUP>tag and </SUP> tag
superscripts the enclosed tags. It gets displayed half a
character height higher, but in the same font and size as the
current text flow i.e. this tag is used to superscript the text.
<TT> …. </TT> The <TT> tag and necessary of </TT> tag directs the browser
to display the enclosed text in a monospaced Typeface.
<U>---</U> The underline tag underlines the content between it and its
corresponding </U>tag.

Boldface
A physical tag <B> i.e. Boldface is used to specify that the selected text, within a container tag,
to be displayed in boldface. For example,
<BODY>
Today there is an <B> Important Meeting </B> at 4.00 P.M.
</BODY>
Output: Today there is an Important Meeting at 4.00 P.M.
Italics
A physical tag <I> i.e. italic tag is used to specify that the selected text, within a container tag, to
be displayed in italic. For example,
<BODY>
Venue of Metting <I> Subhedar Hall</I>
</BODY>
Output: Venue of Meeting Subhedar Hall
Underline
A physical tag <U> i.e. Underline tag is used to specify that the selected text, within a container
tag, to be displayed with an underline. For example,
<BODY>
Bring <U> an Important Document </U> for Meeting
</BODY>

Developed By. Dr. Munesh Thakre Page 15 of 306


Web Engineering BE CSE SEM-VII

Output: Bring an Important Document for Meeting


Strikeout
A physical tag <STRIKE> i.e. Strikeout tag is used to stikeout the text or word within a container
tag. For example,
<BODY>
Circulate Meeting Agenda to Manager/<STRIKE>Assistant Manager</STRIKE>/Clerk
</BODY>
Output: Circulate Meeting Agenda to Manager/Clerk
BIG
A physical container tag <BIG> tag is used to specify that the selected text be displayed in a
bigger font size compared to the font for the rest of the text and it also display, the text in bold.
For example,
<BODY>
<BIG>ICAT Computer </BIG> Institute
</BODY>
Output: ICAT Computer Institute.
SMALL
A physical container tag <SMALL> tag is used to specify that the selected text be displayed in a
smaller font size compared to the font for the rest of the text. For example,
<BODY>
<SMALL>18, Opposite Mount Convent </SMALL> Chandrapur
</BODY>
Output: 18, Opposite Mount Convert Chandrapur.
SUBSCRIPT
A physical container tag <SUB> is used to specify that the selected text be displayed as a
subscript. It lowers the text below the baseline and changes it to a smaller font size. For example,
<BODY>
H<SUB>2</SUB>SO<SUB>4</SUB>
</BODY>
Output: H2SO4
SUPERSCRIPT
A physical container tag <SUP> is used to specify that the selected text be displayed as a
superscript. It raise the selected text above the baseline. For example,

Developed By. Dr. Munesh Thakre Page 16 of 306


Web Engineering BE CSE SEM-VII

<BODY>
A<SUP>2</SUB>b
</BODY>
Output: a2b
TYPEWRITER
A physical container tag <TT> is used to display text or word in mono-typewriter font style,
<BODY>
<TT> The text appears in small type writer font</TT>
</BODY>
Difference between Logical and Physical Style
Sr.No. Physical Style Logical Style
1 Physical style tags mark the specific It is used for showing importance.
appearance of a section of text.
2 Supported by all Browsers Some Browser doesn’t support any effect
of this style.
3 A physical character tag controls how It do not specify format and leave the
to format the text. rendering of the style up to the browser
either in its default or configurable
settings.
4 A physical style would not convey any Logical style would be used to convey
meaning. some meaning.
5 All browsers will display the Some browser will display the logical tag
formatting with same effect. effect in different way.
6 Browser independent. Browser dependent.
7 Ex. This<B> Bold <?B> output. Ex. This <EM> Emphasis </EM> output.

Block Formatting Tags


Headings
User can specify the heading for selected text in an HTML document. One can specify this
container heading upto six levels via tags H1, H3, H4, H5 and H6. Here H1 will make a bigger
heading than H2, which is largere one that H3 and so on i.e. each heading size will be displayed
in the decreasing order. Thus this tag is useful to display some important headings in larger size
compare to normal text. The features of this tag is,

Developed By. Dr. Munesh Thakre Page 17 of 306


Web Engineering BE CSE SEM-VII

 It automatically format the contents in bold.


 It inserts white spaces before and after the heading text.
 Formatting tag like paragraph and line break tags are not required.
Syntax: <Hn> Heading Text</Hn>
Where n is a number between 1 and 6.
<HTML>
<HEAD>
<TITLE>
INTRODUCTION
</TITLE>
<BODY>
<H1>D.B.SCIENCE GONDIA</H1>
<H2>D.B.SCIENCE GONDIA</H2>
<H3>D.B.SCIENCE GONDIA</H3>
<H4>D.B.SCIENCE GONDIA</H4>
<H5>D.B.SCIENCE GONDIA</H5>
<H6>D.B.SCIENCE GONDIA</H6>
</BODY>
</HEAD>
</HTML>
Block Alignment
Block Alignment of text is done using the <DIV> tag. The <DIV> tag is used to align a block of
text and all come within the <DIV> and </DIV> is affected by this element. A major advantage
of this tag is that by usin it once you are able to align a whole text unlike the align tag. You can
align <DIV> tag to the value of left, right and center by using align within the <DIV> tag.
Example:
<HTML>
<HEAD>
<TITLE>Demo of Block Alignment </TITLE>
</HEAD>
<BODY>
<H1>IT Contents</H1>
<DIV ALIGN= “Center”>
<H3>Networking</H3>
<H3>Internet</H3>
<H3>E-Commerce</H3>
</DIV>
</BODY>
</HTML>

Pre-Format Text
The <PRE> tag and its required </PRE> defines a segment inside which the browser render a
block of text without any formatting. This displays the text in exactly same format as the
character and line spacing format define in source HTML document.

Developed By. Dr. Munesh Thakre Page 18 of 306


Web Engineering BE CSE SEM-VII

The Attribute provide by <PRE> tag are:


Attributes Description
ALIGN Allows to set Alignments left, Center or right or justify.
WIDTH Determine the number of characters to fit on a single line within the pre block.
Write a program for illustration of Subscribed, Superscript and PRE tags.
<HTML>
<HEAD>
<TITLE>
DEMONSTRATION OF ATTRIBUTES
</TITLE>
</HEAD>
<BODY>
<CENTER>
<PRE>
<H1>X<SUB>1</SUB><SUP>2</SUP>+Y<SUB>1</SUB><SUP>2
</SUP></H1>
</PRE>
</CENTER>
</BODY>
</HTML>

Address
The address element is used to display an address in HTML. In address you can specify different
types of information such as Signature of developer or name of organization who created the web
page within <ADDRESS> and </ADDRESS>. This tag automatically indents the text and
formats it in italic.
Example:
<HTML>
<BODY>
<ADDRESS>
R.T.M. Nagpur University, Nagpur<BR>
Opposite MaharajBag <BR>
Sitabuldi, Nagpur – 442401(M.S.)
</ADDRESS>
</BODY>
</HTML>

FONT Tag
Using this tag you can control the font, font size and color of the text using attribute FACE,
SIZES and COLOR.
Font Face
This tag is used to change the whole face of the text. Using the <font face> tag you can specify
the font name between quotation marks. When the browser encounters a page with <font fact> it
searches the system for the given font names and then displays the text in that font. You must

Developed By. Dr. Munesh Thakre Page 19 of 306


Web Engineering BE CSE SEM-VII

also remember that fonts have different names on different system. So if you are using this tag
then it is safe to give two or three font names as in case the browser fails to find the first one, it
will display the text in another font.
Syntax : <FONT FACE = “value1” [“value2”], [“value3”]…..>
<FONT FACE= “Arial”, “Times New Roman”, “Helvetica”, “Comic same ms”> this is the font
face section </FONT>
Font Size
Just as you can change the font face, you can also manipulate font sizes. You can use the <font
size> tag on one word or a whole paragraph.
Syntax: <FONT SIZE=N>Text</FONT>
The value for size can be from 1 to 7 where number 3 is the default font size. Font size is also
defined by using the relative value to the default size of 3. This is done by using the + or –
symbol.
Syntax: <FONT SIZE = +VALUE>
Changing font size using the relative value.
Example: <FONT SIZE=+3>. If current font is suppose 3 then the text that it follows will be
displayed in the font size 7(=4+3).
<HTML>
<BODY>
<P><FONT FACE= “TIMES NEW ROMAN SIZE=1>Keyboard</FONT></P>
<P><FONT SIZE=2>Mouse</FONT></P>
<P><FONT SIZE=3>Light Pen</FONT></P>
<P><FONT SIZE=4>Optical Mark Reader</FONT></P>
<P><FONT SIZE=5>Scanner</FONT></P>
<P><FONT SIZE=+3>Printer</FONT></P>
<P><FONT SIZE=7>Plotter</FONT></P>
</BODY>
</HTML>
Font Color
User can use the Color Attribute to specify the color of the enclosed text. Syntax to represent
Color attribute is “
<FONT COLOR= “VALUE”>

Developed By. Dr. Munesh Thakre Page 20 of 306


Web Engineering BE CSE SEM-VII

One can specify the name of color such as RED, GREEN, BLUE, YELLOW, WHITE, LIME etc or
can specify the color using a hexadecimal value that is basically a combination of three primary
colors called Red, Green and Blue in the format #RRGGBB. For example, #000000 represent Black,
#FFFFFF represent white. Thus 00 and FF indicate the decimal value 0 to 255 respectively. Thus we
can specify 256 colors.
Example:
Example:
<FONT COLOR = “RED”>HELLO </FONT>
OR
<FONT COLOR = “FF0000”>HELLO </FONT>

<HR> Tag (Horizontal Rules)


Horizontal line can be added to the HTML document using <HR> tag. This tag does not have any
closing tag i.e. it is a singular tag. This tag is useful to divide different sections of text in an HTML
document and it inserts a shaded line, which is also called horizontal rule at a specific point in the
page. When <HR> tag is used at the end of a sentence or a paragraph then horizontal line is inserted
above it.
The <HR> tag draws the lines and horizontal rules. This tags draws a horizontal lines across the
whole page, if not specified.
Attributes Description
ALIGN ALIGN the line on the browser screen to left, center or right. By default
the line is aligned to the center of screen.
SIZE Changes the Size of the rule.
WIDTH Sets the Width of the rule.
COLOR To display ruler line in specific color. For example: <HR COLOR= “red”>
NOSHADE When a solid bar is required then this attribute specify that the horizontal
rule should not be shaded. It does not require any value.
Write a program for the illustration of 'Horizontal Rule'.
<HTML>
<HEAD>
<TITLE>
DEMONSTRATION OF HR
</TITLE>
</HEAD>
<BODY>
<H3>Object Based Languages</H3>
<HR>
<P>C++<BR>
VISUAL C++<BR>
Java
</P>
</BODY>
</HTML>

Developed By. Dr. Munesh Thakre Page 21 of 306


Web Engineering BE CSE SEM-VII

Lists
List is collection of similar items or sequence you steps. In general, when you visit the restaurant,
waiter shows you a menu which shows list of items available in different way or format. HTML
offers authors several mechanism for specifying lists of information. All list must contain one or
more list elements. Inside a list item you can put text, line breaks, images, links other formatting tags
for better appearance and presentation. Lists are created using either <UL>, <OL> or <DL> tags.
Types of lists supported by HTML are:
 Unordered Information List
 Ordered Information Lists
 Definition Lists

Unordered List:
Unordered list are a type of list where the points are not numbered. Instead there are three types of
bullets that can be used. The <UL> tag is used to mark the beginning of unordered list. The list is
closed by using </UL> tag. The points in the list are indicated using the <LI> tag. It is not
compulsory to close the <LI>tag but it always better to closed it using the </LI>. <UL> tag has
following attribute.
The use of TYPE attribute will allow you to change the bullet to be displayed. The TYPE attribute
text the following three values circle, square, disk.

Ordered List:
Ordered list are a numbered list and can have numbers instead of bullets that unordered list has. The
tag used to mark the beginning of ordered list is <OL>. The tag used to mark the end of it is </OL>.
It can have attributes: TYPE and START
TYPE:
This attribute can take the following values 1, a, A, i, I. If the value assign to type is '1', then the
ordered list has no. starting from 1. If 'a' is assigned then the list is ordered as a, b, c,..., z . Similarly
'A' is numbers list as A, B, C,..., Z. 'I' or 'i' uses roman numerical to number the list.
START:
This attribute of <OL> tag decides where the numbering will start from. By default it starts from '1'.
This can be changed through the START attribute. The numbering will start from number which is
assigned to start attribute. Even if the type is '0' or 'I' etc, the START attribute will always accept an

Developed By. Dr. Munesh Thakre Page 22 of 306


Web Engineering BE CSE SEM-VII

integer value. If the type is 'A' and if you want numbering to start from'0' then you have to set value
of start to 4.
The <LI> tag can have following attribute:
TYPE:
It has same values as the type attribute mentioned above it is used to change the type of current list
item.
VALUE:
This attribute is used to change the type of not only current list item but also list item following it.
<HTML>
<HEAD>
<TITLE>
Ordered List
</TITLE>
</HEAD>
<BODY>
<OL>
<LI>NAGPUR UNIVERSITY</LI>
<OL TYPE="A">
<LI VALUE=1>SCIENCE</LI>
<OL TYPE="i">
<LI>C.J.PATELCOLLEGE, TIRRORA</LI>
<LI>J.M.PATELCOLLEGE, BHANDARA</LI>
<LI>M.M.PATELCOLLEGE, SAKOLI</LI>
<LI>D.B.SCIENCE COLLEGE, GONDIA</LI>
</OL>
<LI>COMMERCE</LI>
<OL TYPE="i">
<LI>C.J.PATELCOLLEGE, TIRRORA</LI>
<LI>J.M.PATELCOLLEGE, BHANDARA</LI>
<LI>M.M.PATELCOLLEGE, SAKOLI</LI>
<LI>N.M.D COLLEGE, GONDIA</LI>
</OL>
<LI>ARTS</LI>
<OL TYPE="i">
<LI>C.J.PATELCOLLEGE, TIRRORA</LI>
<LI>J.M.PATELCOLLEGE, BHANDARA</LI>
<LI>M.M.PATELCOLLEGE, SAKOLI</LI>
<LI>N.M.D COLLEGE, GONDIA</LI>
</OL>
</OL>
<LI > AMARAWATI UNIVERSITY</LI>
<LI> PUNE UNIVERSITY</LI>
</OL>
</BODY>
</HTML>

PROGRAMME 14 ://"Illustration of Unordered List in HTML".


<HTML>
<HEAD>
<TITLE>
Unordered List
</TITLE>
</HEAD>

Developed By. Dr. Munesh Thakre Page 23 of 306


Web Engineering BE CSE SEM-VII

<BODY>
<UL>
<LI>NAGPUR UNIVERSITY</LI>
<UL TYPE=square>
<LI>SCIENCE</LI>
<UL TYPE=circle>
<LI>C.J.PATELCOLLEGE, TIRRORA</LI>
<LI>J.M.PATELCOLLEGE, BHANDARA</LI>
<LI>M.M.PATELCOLLEGE, SAKOLI</LI>
<LI>D.B.SCIENCE COLLEGE, GONDIA</LI>
</UL>
<LI>COMMERCE</LI>
<UL TYPE=circle>
<LI>C.J.PATELCOLLEGE, TIRRORA</LI>
<LI>J.M.PATELCOLLEGE, BHANDARA</LI>
<LI>M.M.PATELCOLLEGE, SAKOLI</LI>
<LI>N.M.D COLLEGE, GONDIA</LI>
</UL>
<LI>ARTS</LI>
<UL TYPE=circle>
<LI>C.J.PATELCOLLEGE, TIRRORA</LI>
<LI>J.M.PATELCOLLEGE, BHANDARA</LI>
<LI>M.M.PATELCOLLEGE, SAKOLI</LI>
<LI>N.M.D COLLEGE, GONDIA</LI>
</UL>
<LI> AMARAWATI UNIVERSITY</LI>
<LI> PUNE UNIVERSITY</LI>
</UL>
</BODY>
</HTML>

Definition List
It consists of term and followed by its definition. It is also referred as Glossary list of Dictionary list.
An definition list created by using the <DL>…</DL> tags followed by the <DT> (Definition Terms)
tag and the <DD> (Definition Description) tag. Here <DT> and <DD> tag pair indicates a term and
its definition and must appear in the same order. Definition lists are unordered list. Here
 The <DL> tag is a pair tag.
 <DT> and <DD> is a singular tag.
Example:
<HTML>
<HEAD><TITLE>Demo of Definition List</TITLE></HEAD>
<BODY>
<H3>Computer Toy</H3>
<DL>
<DT>Lower Cost
<DD>Product costs significantly less compare to any other company
product

Developed By. Dr. Munesh Thakre Page 24 of 306


Web Engineering BE CSE SEM-VII

<DT> <B>Easier to user </B>


<DD>Due new technology it’s much easier to use!
<DT>Safe for kids
<DD><B>You can leave your kids alone in a room with this
product</B>
</DL>
</BODY>
</HTML>
Nested Lists
It is possible to nest the different types of lists within one another or to nest multiple list of same
type.
<HTML>
<HEAD><TITLE>Demo of Nested UnOrder List</TITLE></HEAD>
<BODY>
<H3>Course Details</H3>
<UL>
<LI>Information Technology
<LI>DBMS and Oracle
<LI>Principle of Technique of Management
<LI>Operation Research
<LI>Optional
<UL>
<LI>C++
<LI>Web Design
<LI>Software Engineering
</UL>
</UL>
</BODY>
</HTML>
Difference between Ordered and Unordered List
Ordered List Unordered List
List items are prefixed by relative order of items. List items are prefixed by a special symbol.
One can start with specific Arabic numbers or START attribute can not specify with

Developed By. Dr. Munesh Thakre Page 25 of 306


Web Engineering BE CSE SEM-VII

letters or roman numericals using Attribute Unordered list.


START.
Useful when order of list items should Useful where order of list is not important.
beemphasized.
Default list type is Arabic Number (1, 2, 3, …) Default list type is Disc.
In a Nested List, type value does not change In a nested list, type value changes from
compare to previous type value automatically. previous type with new one automatically in
the order Disc to Circle to Square. For
example, if previous type is Disc then the new
list will be assigned a circle type
automatically.
Structure is Structure is
<OL> <UL>
<LI> <LI>
<LI> <LI>
</OL> </UL>

Special Characters:
There are times when you have to display certain special characters on the screen like ©, ® etc.
These characters are not available on the keyboard. So how will they be printed on the screen and
also any space in the HTML code are reduced to one. So how do we show more than one space in
the web page? These were UNICODE come into the picture. Here is a list of a few of UNICODES.

Sr.no Decimal Character Example Explanation


1 &#160; &nbsp; No-breaking Space
2 &#161; &iexcl; ! Inverted Exclamation Mark
3 &#162; &cent: ¢ Cent Sign
4 &#163; &pound; £ Pound Sign
5 &#164; &curren; ¤ Currency Sign
6 &#165; &yen; ¥ Yen Sign
7 &#166; &brvbar; | Broken Bar/Vertical Bar
8 &#167; &sect; § Selection Sign
9 &#168; &uml; " Diaeresis
10 &#169; &copy; © Copyright Sign
11 &#170; &ordf; Feminine Ordinal Indicator
12 &#171; &laquo; « Left pointing double quotation mark
13 &#172; &not; ¬ Not Sign
14 &#173; &shy; - Soft Hyphen
15 &#174; &reg; ® Regstered Sign
16 &#175; &macr; ¯ Macron

Developed By. Dr. Munesh Thakre Page 26 of 306


Web Engineering BE CSE SEM-VII

17 &#176; &deg; º Degree Sign


18 &#177; &plusmn; ± Plus Minus Sign
19 &#178; &sup2; ² superscript 2
20 &#179; &sup3; ³ superscript3
21 &#180; &acute: ' Acute Accent
22 &#181; &micro: μ Microsign
23 &#182; &para; Π Pilcrow Sign/ Paragraph Sign
24 &#183; &middot; ∙ Middle Dot
25 &#184; &ccedil , Cadilla
26 &#185; &sup1; ¹ Superscript 1
27 &#186; &ordm; Musculine Ordinal Indicator
28 &#187; &raquo; » Right pointing double angle quotation mark
29 &#188; &frac14; ¼ Vulgar Fraction One Quarter
30 &#189; & frac12; ½ Vulgar Fraction One and a Half
&frac12;
31 &#190; & frac34; ¾ Vulgar Fraction Three Quarter
32 &#191; &iquest; i Inverted Question Mark
33 &#192; &Agrave À Latin Capital Letter A with grave.
34 &#193; &Aacute; Á Latin Capital Letter A with acute.
35 &#194; &Acirc; Ã Latin Capital Letter A with circumflex

Linking
Instead of creating single documents web page with lot of information one can breakup this
information into parts and store them in a separated documents and access them by means of link.
Thus linking can be defined as “A mechanism to connect related web page file”. It can be
achieved by means of formatting a given text (hypertext) and which helps to link another web page.
This process is known as hyperlink. Thus hyperlink is a process of linking source web page with that
of target web page. One must specify the Path or URL of target web page in source web page. A
hyperlink can be created in HTML using anchor tag <A>…</A>.
Advantages of Linking to other Document
1. Reuse the web page with other HTM documents.
2. Reduce the time and cost for creating web page which already exists.
3. Navigating various web pages.
4. Linking can be made bidirectional.
Appearance of Hyperlink
Browser distinguishes hyperlinks from normal text by following features.
1. By default every hyperlinks appear in Blue color.
2. Hyperlink Text/Image is underlined.
3. When the mouse is placed over hypertext the mouse shape is changed to hand.

Developed By. Dr. Munesh Thakre Page 27 of 306


Web Engineering BE CSE SEM-VII

Steps/Stages to be follow while linking the Web Page


In general one can follow the following steps to link to web page.
1. Create a Source web page.
2. Attach formatting tag for better appearance.
3. Save the current HTML document using extension .html.
4. Check the Section in theweb document where one has created the link or not.
5. Check the Target web page where to link is made is existing or not and the URL path is mention
correctly in the source web page.
6. Run your source web page using browser.
7. Check all links are executed properly or not.
Type of Hyperlink Creation
One can hyperlink either by clicking to.
1. Text: Hyperlink text is denoted as link to text via blue color and underlined.
2. Inline Image: Hyperlink images are denoted as links via blue frame.
Once clicked, color of link will change from blue to purple to indicate that it has been visited. Thus
helps the user to identify the visisted and unvisited links.
Working with Links (Anchor Tag)
In order to link various web document with the current document HTML uses container tag <A> and
</A> and known as Anchor tag. Thus anchor elements help to create hyperlink. The syntax of anchor
tag is:
For Text
<A HREF = “URL”> Text_Link_Lable </A>
For Image
<A HREF = “URL”> <IMG SRC = “Image_File”> </A>
Here,
 Attribute HREF is used to reference the URL of the target web page. One can specify URL by
specifying relative path or by means of absolute path. HREF stands for Hyperlink Reference. It is
mandatory attribute that must be specified with Anchor <A> tag.
 The text TEXT_LINK_LABEL would appear underlined and in a color different from any other
text in the document to distinguish it as a link from normal text. These links are basically called
as hypertext links or hotspots.

Developed By. Dr. Munesh Thakre Page 28 of 306


Web Engineering BE CSE SEM-VII

 Images can be made as a hyperlink by including <IMG> tag within anchor pair tags called <A>
and </A>.
Pathname (URLs)
Pathnames refer to the URL (Uniform Resource Locator) which is written in the text field of the web
browser running on a client machine. These URLs are of two types.
1. Relative
2. Absolute
Relative URLs
Relative URLs are relatve to their base element i.e. relative to current page. If the current page is
visible during browsing then the web browser will know that hyperlink files are also stored in that
director.
Example:
<A HREF = “table.html”> View Next Table </A>
If the current page says file table1.html visible in the browser as http://www/web.com/table1.html
then the browser will know that the hyperlink in this HTML points to
http://www/web.com/table2.html.
Absolute URLs
This kind of pathnames does not rely on relative to anything. Here one must specify a page’s full
web address. For example,
http://www.spcollegechandrapur.com/mca.html. It refers to the mca.htm page in the mca directory of
the www.spcollegechandrapur.com server.
Difference between Absolute and Relative Path
Generic Paths/ Absolute Paths Relative Paths
It is referred to as Absolute paths because they Relative paths change depending upon what
refer to the very specific location. page the links are located on.
One must also specify the domain name. Not necessary to specify domain name.
Absolute paths are usually used while It is generally used in referering user web
referencing web site. document stored in a folder.
The absolute path is the “full path”. Absolute The relative path is the “partial path”.
path contains the exact path.
Absolute path always begins with a / (slash). It specifies location relative to your current
working directory i.e. relative path do not
begin with /.

Developed By. Dr. Munesh Thakre Page 29 of 306


Web Engineering BE CSE SEM-VII

An absolute path contains full path, contains the Relative path contains only the path relatively
root directory and all other sub directories. to a certain folder. The path may appear as
Absolute path may appear as images/sunset.jpg.
/home/user/picture/images/sunset.jpg.
Used for referring server side web page and Usually used for referring client side web page
known as Server Relative URLs. and known as Document Relative URLs.
They are shorter and saves lot of time while It is usually lengthy and hence more time to
writing. type.
If you move your web pages to another directory If you move your all web pages to another
all relative address will remain valid. directory all absolute path become invalid and
known as broken links. In short, one must
change all paths pointing to new directory.

Types of Linking or Anchors


Internal Links
Linking to user created web pages i.e. the files that reside within local computer.
1. Within Current Page (Creating Targets)
2. Link to Different Web Page.
3. Link to specific Section of different Web Page.
External Links
A link to specific web site i.e. files that are placed at remote computers, it is important that in order
to link the web sites, internet connection must be on.
1. Link to Web Sites.
2. Link to Compose mail.
3. Link to Download files.
Example:
<HTML>
<HEAD><TITLE>Demo of Link within Page</TITLE></HEAD>
<BODY>
<A NAME= “TOP”></A>
<P><H1>Ms-Office Applications</H1>
<H4><A HREF = “#WORD”>1. Word </A><BR>
<A HREF = “#EXCEL”> 2. Excel</A><BR>

Developed By. Dr. Munesh Thakre Page 30 of 306


Web Engineering BE CSE SEM-VII

<A HREF = “#POWERPOINT”> 3. Power Point</A><BR>


<A HREF = “#ACCESS”> 4. Access</A><BR>
</H4>
</P>
<HR SIZE= “7”>
<A NAME= “WORD”><B>WORD</B></A>
<PRE>
MS-Word is the application software and one of the most powerful word
processor in Windows operating system. It is used for formatting of letter or
the text. In simple meaning it is a word processor having various functions for
text you may insert different objects like pictures, sound and video or calendar
in word file.
</PRE><BR><BR>
<A NAME= “EXCEL”><B>EXCEL</B></A>
<PRE>
MS-Excel is a powerful spreadsheet or worksheet application that can use for
managing, analyzing and presenting data in tabular format. It also helps to
display data in graphical format using charts.
</PRE><BR><BR>
<A NAME= “POWERPOINT”><B>POWER POINT</B></A>
<PRE>
Ms-Powerpoint is a powerful tool to create professional looking presentation
and slide shows.
</PRE><BR><BR>
<A NAME= “ACCESS”><B>ACCESS</B></A>
<PRE>
Ms-Access is a powerful program to create and manage database.
</PRE>
<A HREF= “#TOP”>GO TOP</A>
</BODY>
</HTML>
Kinds of Linking / Types of Linking:
1. Linking two or more web pages.

Developed By. Dr. Munesh Thakre Page 31 of 306


Web Engineering BE CSE SEM-VII

2. Linking within a web page.


3. Linking to a specific point in another web page.
4. Linking to External web pages.

1) Linking two or more web pages:


You can create these pages in a text editor and then navigate them using a browser. We have created
two files, index.html, which is the main file and link to support.html. You can go ahead and tryout
the example by cutting and pasting the code. Remember to save the file in the same folder or
directory. The HTML code for index.html is

PROGRAMME 15://"Illustration of linking of two or more web pages in HTML".

<HTML>
<HEAD>
<TITLE>
JM Software
</TITLE>
</HEAD>
<BODY>
<UL>
<LI>Software Development</LI>
<LI>Marketing</LI>
<LI> <A HREF="Support.html">Customer Support</A></LI>
</UL>
</BODY>
</HTML>

PROGRAMME16 ://"Illustration of linking of two or more web pages in HTML".

<HTML>
<HEAD>
<TITLE>
LINKING TWO OR MORE WEB PAGES.
</TITLE>
</HEAD>
<BODY>
<P>
<H3> Master Software</H3>
<H3><A HREF="BCA2.HTML">CCI Software</A></H3>
</P>
</BODY>
</HTML>

PROGRAMME17 ://"Illustration of linking of two or more web pages in HTML".

<HTML>
<HEAD>
<TITLE>
SUB FILE
</TITLE>
</HEAD>

Developed By. Dr. Munesh Thakre Page 32 of 306


Web Engineering BE CSE SEM-VII

<BODY>
<P>
CCI Software Company NAGPUR</A></H3>
</P>
</BODY>
</HTML>

The HTML code for support.html File is:


<HTML>
<HEAD>
<TITLE>Customer Support</TITLE>
</HEAD>
<BODY>
<H3> Customer Support </H3>
<P>
We aim to provide support to all those business and individuals who are
using our software product our customer support services are divided into the
following main section.
</P>
<UL>
<LI> <A HREF ="online.html"> online support </A> </LI>
<LI> <A HREF ="Knbase.html">Knowledge base support </A> </LI>
</UL>
</BODY>
</HTML>

2) Linking within a web page:


Local linking is very useful in situations where you may have to link menu selection within one page
itself. To do this, you need to set marks within the document. This is done by using the
<A NAME>...</A>
<A NAME= "Software"> <B> Software Development </B> </A>
Once you have marked a section you have to now correct your hyperlink to that section and i.e. done
by using same old <A HREF>...</A>. While doing linking within a web page you have to write (#)
hash symbol along with the name section.
EX: <A HREF="#Software"> Software Development </A>
<HTML>
<HEAD>
<TITLE>
LINKING WITHIN A WEB PAGE
</TITLE>
</HEAD>
<BODY>
<P><H3> Master Software</H3></P>
<HR>
<P>
<UL>
<LI><A HREF="#BCA">COURSE DETAILS </A></LI>
<LI>BCA1</LI>
<LI>BCA2</LI>
<LI>BCA3</LI>
</UL>
<LI> FEES DETAILS</LI>
<UL>

Developed By. Dr. Munesh Thakre Page 33 of 306


Web Engineering BE CSE SEM-VII

<LI>BCA1 11000</LI>
<LI>BSC 7000</LI>
</UL>
</P>
<P><A NAME="BCA">COURSE DETAILS </A></P>
<P>
WE OFFER SEVERAL COURCES AS PER STUDENT REQUIREMANTS <BR>
WE PROVIDE OTHER ACTIVITIES AS PER STUDENTS DEMANDS
</P>
</BODY>
</HTML>

3) Linking to a specific point in another web page:


In real time web development there may be situation where you may have to create a hyperlink top a
specific point in another web page. In this case you are not only hyper linking to an External page
but also to specific point in that page.
The following picture you have to follow the same procedure as you did while hyper linking within
same web. So for linking SINGAPORE address from file support .html to office.html. You will
define the <A NAME> tag in office.html.
<A NAME="Singapore"> JM Software, Singapore </A>
The only difference is when use you the < A HREF> tag in support. html, you will have to specify
file name first and then the name of anchor tag.
<A HREF=" office.html #Singapore"> Singapore</A>
Support.html Office.html
JM Software JM Software, India
23, Pali Road
Mumbai
Customer Support
Branches JM Software, USA
12 Rich Road,
India Florida
Singapore USA
USA
JM Software, Singapore
04#21 Rightway
Singapore

4) Linking to External web Pages:


There will be pages where you may need to call External web sites for instance you may like to
include some web site that offers free software or content some other information relevant to your
web site. The scenarios could be something like shown in following figure: When you providing a
hyperlink to a External site.

Developed By. Dr. Munesh Thakre Page 34 of 306


Web Engineering BE CSE SEM-VII

index.html

JM Software External Web Site

http:///www.browsers.com/
Software Development
Marketing
Customer Support

Site best viewed with IE 5.0


Download

List of Tags used in HTML


Description DTD
<!--...--> Defines a comment STF
<!DOCTYPE> Defines the document type STF
<a> Defines an anchor STF
<abbr> Defines an abbreviation STF
<acronym> Defines an acronym STF
<address> Defines an address element STF
<applet> Deprecated. Defines an applet TF
<area> Defines an area inside an image map STF
<b> Defines bold text STF
<base> Defines a base URL for all the links in a page STF
<basefont> Deprecated. Defines a base font TF
<bdo> Defines the direction of text display STF
<big> Defines big text STF
<blockquote> Defines a long quotation STF
<body> Defines the body element STF
<br> Inserts a single line break STF
<button> Defines a push button STF
<caption> Defines a table caption STF
<center> Deprecated. Defines centered text TF
<cite> Defines a citation STF
<code> Defines computer code text STF
<col> Defines attributes for table columns STF
<colgroup> Defines groups of table columns STF
<dd> Defines a definition description STF
<del> Defines deleted text STF
<dir> Deprecated. Defines a directory list TF
<div> Defines a section in a document STF
<dfn> Defines a definition term STF
<dl> Defines a definition list STF
<dt> Defines a definition term STF

Developed By. Dr. Munesh Thakre Page 35 of 306


Web Engineering BE CSE SEM-VII

<em> Defines emphasized text STF


<fieldset> Defines a fieldset STF
<font> Deprecated. Defines text font, size, and color TF
<form> Defines a form STF
<frame> Defines a sub window (a frame) F
<frameset> Defines a set of frames F
<h1> to <h6> Defines header 1 to header 6 STF
<head> Defines information about the document STF
<hr> Defines a horizontal rule STF
<html> Defines an html document STF
<i> Defines italic text STF
<iframe> Defines an inline sub window (frame) TF
<img> Defines an image STF
<input> Defines an input field STF
<ins> Defines inserted text STF
<isindex> Deprecated. Defines a single-line input field TF
<kbd> Defines keyboard text STF
<label> Defines a label for a form control STF
<legend> Defines a title in a fieldset STF
<li> Defines a list item STF
<link> Defines a resource reference STF
<map> Defines an image map STF
<menu> Deprecated. Defines a menu list TF
<meta> Defines meta information STF
<noframes> Defines a noframe section TF
<noscript> Defines a noscript section STF
<object> Defines an embedded object STF
<ol> Defines an ordered list STF
<optgroup> Defines an option group STF
<option> Defines an option in a drop-down list STF
<p> Defines a paragraph STF
<param> Defines a parameter for an object STF
<pre> Defines preformatted text STF
<q> Defines a short quotation STF
<s> Deprecated. Defines strikethrough text TF
<samp> Defines sample computer code STF
<script> Defines a script STF
<select> Defines a selectable list STF
<small> Defines small text STF
<span> Defines a section in a document STF
<strike> Deprecated. Defines strikethrough text TF
<strong> Defines strong text STF
<style> Defines a style definition STF
<sub> Defines subscripted text STF
<sup> Defines superscripted text STF
<table> Defines a table STF
<tbody> Defines a table body STF
<td> Defines a table cell STF
<textarea> Defines a text area STF
<tfoot> Defines a table footer STF
<th> Defines a table header STF
<thead> Defines a table header STF
<title> Defines the document title STF
<tr> Defines a table row STF

Developed By. Dr. Munesh Thakre Page 36 of 306


Web Engineering BE CSE SEM-VII

<tt> Defines teletype text STF


<u> Deprecated. Defines underlined text TF
<ul> Defines an unordered list STF
<var> Defines a variable STF
<xmp> Deprecated. Defines preformatted text

TABLE
Basically, a table is a two dimensional matrix consisting of rows and columns. HTML helps you to
present the information in a tabular form i.e. in the form of rows and columns. The basic elements of
table is cell (intersection of Rows and Column) or the grid. In a table, cells are arranged from left to
right and from top to bottom. By default each cell in a table is spread across one row and one
column. One can use other HTML formatting tags with table to improve its appearance for better
presentation. One can create table in HTML using tag <TABLE>.
Table Usage
In following situation displaying data in a tabular format is useful:
 Express Relationship: It is usually used to display the relationship among columns within
table. For example, Roll_no, Name and Address show that it constitutes student information.
 Tabular Form: Tables enable the show or display information in a tabular form rather
simply a textual form.
 Control Layout: It helps a web designer to control the layout of text and position a group of
images that is usually used in news-paper publication.
Features of HTML Tables
1. One can change the height and width of single cell.
2. Span table cells across rows.
3. Span table across columns.
4. All columns data are aligned properly.
5. Can provide the spaces between cells.
6. Inserting image within table cell.
7. Hyperlink table cell item.
8. Nesting Tables etc.
TABLE Tag
All table related tags are included between the pair tags <TABLE> … </TABLE>. Each row of the
table is described between the <TR> … </TR> tags while each column of a table is described
between pair tags <TD> … </TD>. Here,
 <TR> tag specifies table row and is a non-empty or pair tag.

Developed By. Dr. Munesh Thakre Page 37 of 306


Web Engineering BE CSE SEM-VII

 <TD> tag specifies table cell or table data.


Types of Table Rows
HTML supports two types of rows.
Header Rows
A text that spans across the columns of table is called the Header rows and it automatically appeared
in center and in boldface. It is useful to identify column heading for data value entered for the
column. It is specified using pair tags <TH> … </TH>. Here TH stands for table Head.
Data Rows
It is default table rows and contains data within cell. It is specified using pair tag <TD> … </TD>.
Here TD stands for Table Data.
Attributes of TABLE
Sr. Tag Attribute Values Description
No. range
1 <TABLE> BORDER 1-100% Specifies a visible border and its
BORDERCOLOR RGB thickness.
CELLSPACING 1-100% Specifies the color of outside border.
CELLPADDING 1-100% Specifies amount of spacing between
WIDTH 1-100% table cells.
Speficies amount spacing inside table
cell.
Specifies the width of the table relative to
the width of the web page.
2 <TR>, <TD> ALIGN Left, Specifies the horizontal alignment of text
BGCOLOR Center, within a row or individual cell.
VLINK Right Specifies a fill color for rows or cells.
COLSPAN RGB Specifies the cell defined by the tag to
ROWSPAN Codes make more than one column.
Top,
Middle,
Bottom
3 <CAPTION> ALIGN TOP, Specifies a Table heading or title for the
BOTTOM table.
4 <TH> BGCOLOR RGB Specifies a Column heading. One can

Developed By. Dr. Munesh Thakre Page 38 of 306


Web Engineering BE CSE SEM-VII

Codes also specify the color for it.

HTML - Forms
Forms are used to collect all the input information from the user for further processing. For
providing such input, the form are created using controls like textboxes, click buttons, radio buttons,
check boxes, list boxes etc for entering or selecting data via GUI (Graphical User Interface) controls.
A form is the physical carrier of data and information and it also carries the authority for action. One
may have more than one form in the document to collect related information from each form.
Generally form are classified as,
 Registration forms
 Subscription forms
 Response forms
 Ordered Entry forms
 Complaint form etc.
After completion of data entry one must submit the data for further processing using say SUBMIT
button. This helps browser tosend the data to the web server to process using JavaScript. VbScript,
ASP, JSP, PERL, CGI program etc. At then end it must acknowledge user by means of some
response. Thus forms are useful for:
 Interacting with user on the web to gather necessary data and hence known as user interface.
 Upload this data from user to server i.e. data filled by user becomes database for web page
designer.
Principle guidelines for Form design
A form design is a highly intuitive human computer interaction method whereby data fields are
formatted in a manner similar to paper based forms. Form interaction is effective for both the input
and presentation of information and hence one should design it very effectively. The general
considerations of form design are given below:
1. Order of data items shuld be proper and must be in the same sequence as that of source
documents i.e. screen should simulate the paper document.
2. Forms title, Label title, commands button caption should be meaningful.
3. Ease of data entry.
4. Highlighting the important things by means of Bold, Blinking, Underline, etc.
5. Size of form should fit within window.

Developed By. Dr. Munesh Thakre Page 39 of 306


Web Engineering BE CSE SEM-VII

6. Use proper color, sound, menu (popup, pushdown, cascading, iconic, menu bars etc). Dialog
box, function keys and icons to different part of forms of the system according to requirement.
7. Balanced layout between screens and spacing among different fields or labels.
8. Easy navigation by showing how to move forward and backward.
9. Whenever there is a need of compromise then sacrifice decorations but retain the clarity.

The HTML <form> tag is used to create an HTML form and it has following syntax −
<form action = "Script URL" method = "GET|POST">
form elements like input, textarea etc.
</form>
Form Attributes
Apart from common attributes, following is a list of the most frequently used form attributes −

Sr.No Attribute & Description

1 action
Backend script ready to process your passed data.

2 method
Method to be used to upload data. The most frequently used are GET and POST methods.

3 target
Specify the target window or frame where the result of the script will be displayed. It
takes values like _blank, _self, _parent etc.

4 enctype
You can use the enctype attribute to specify how the browser encodes the data before it
sends it to the server. Possible values are −
application/x-www-form-urlencoded − This is the standard method most forms use in
simple scenarios.
mutlipart/form-data − This is used when you want to upload binary data in the form of
files like image, word file etc.

HTML Form Controls


There are different types of form controls that you can use to collect data using HTML form −
 Text Input Controls

Developed By. Dr. Munesh Thakre Page 40 of 306


Web Engineering BE CSE SEM-VII

 Checkboxes Controls
 Radio Box Controls
 Select Box Controls
 File Select boxes
 Hidden Controls
 Clickable Buttons
 Submit and Reset Button
Text Input Controls
There are three types of text input used on forms −
 Single-line text input controls − This control is used for items that require only one line of user
input, such as search boxes or names. They are created using HTML <input> tag.
 Password input controls − This is also a single-line text input but it masks the character as soon
as a user enters it. They are also created using HTMl <input> tag.
 Multi-line text input controls − This is used when the user is required to give details that may
be longer than a single sentence. Multi-line input controls are created using

HTML <textarea> tag.


Single-line text input controls
This control is used for items that require only one line of user input, such as search boxes or names.
They are created using HTML <input> tag.
Example
Here is a basic example of a single-line text input used to take first name and last name −
<html>
<head>
<title>Text Input Control</title>
</head>
<body>
<form >
First name: <input type = "text" name = "first_name" />
<br>
Last name: <input type = "text" name = "last_name" />
</form>
</body>
</html>
Attributes
Following is the list of attributes for <input> tag for creating text field.

Developed By. Dr. Munesh Thakre Page 41 of 306


Web Engineering BE CSE SEM-VII

Sr.No Attribute & Description

1 Type
Indicates the type of input control and for text input control it will be set to text.

2 Name
Used to give a name to the control which is sent to the server to be recognized and get the
value.

3 Value
This can be used to provide an initial value inside the control.

4 Size
Allows to specify the width of the text-input control in terms of characters.

5 Maxlength
Allows to specify the maximum number of characters a user can enter into the text box.

Password input controls


This is also a single-line text input but it masks the character as soon as a user enters it. They are
also created using HTML <input>tag but type attribute is set to password.
Example
Here is a basic example of a single-line password input used to take user password −
<!DOCTYPE html>
<html>
<head>
<title>Password Input Control</title>
</head>
<body>
<form >
User ID : <input type = "text" name = "user_id" />
<br>
Password: <input type = "password" name = "password" />
</form>
</body>
</html>

Attributes
Following is the list of attributes for <input> tag for creating password field.

Sr.No Attribute & Description

Developed By. Dr. Munesh Thakre Page 42 of 306


Web Engineering BE CSE SEM-VII

1 Type
Indicates the type of input control and for password input control it will be set
to password.

2 Name
Used to give a name to the control which is sent to the server to be recognized and get the
value.

3 Value
This can be used to provide an initial value inside the control.

4 Size
Allows to specify the width of the text-input control in terms of characters.

5 Maxlength
Allows to specify the maximum number of characters a user can enter into the text box.

Multiple-Line Text Input Controls


This is used when the user is required to give details that may be longer than a single sentence.
Multi-line input controls are created using HTML <textarea> tag.
Example
Here is a basic example of a multi-line text input used to take item description −
<html>
<head>
<title>Multiple-Line Input Control</title>
</head>
<body>
<form>
Description : <br />
<textarea rows = "5" cols = "50" name = "description">
Enter description here...
</textarea>
</form>
</body>
</html>

Attributes
Following is the list of attributes for <textarea> tag.

Sr.No Attribute & Description

Developed By. Dr. Munesh Thakre Page 43 of 306


Web Engineering BE CSE SEM-VII

1 name
Used to give a name to the control which is sent to the server to be recognized and get the
value.

2 rows
Indicates the number of rows of text area box.

3 cols
Indicates the number of columns of text area box

Checkbox Control
Checkboxes are used when more than one option is required to be selected. They are also created
using HTML <input> tag but type attribute is set to checkbox..
Example
Here is an example HTML code for a form with two checkboxes −
<html>
<head>
<title>Checkbox Control</title>
</head>
<body>
<form>
<input type = "checkbox" name = "maths" value = "on"> Maths
<input type = "checkbox" name = "physics" value = "on"> Physics
</form>
</body>
</html>

Attributes
Following is the list of attributes for <checkbox> tag.

Sr. Attribute & Description


No

1 type
Indicates the type of input control and for checkbox input control it will be set to checkbox..

2 name
Used to give a name to the control which is sent to the server to be recognized and get the
value.

Developed By. Dr. Munesh Thakre Page 44 of 306


Web Engineering BE CSE SEM-VII

3 value
The value that will be used if the checkbox is selected.

4 checked
Set to checked if you want to select it by default.

Radio Button Control


Radio buttons are used when out of many options, just one option is required to be selected. They
are also created using HTML <input> tag but type attribute is set to radio.
Example
Here is example HTML code for a form with two radio buttons −
<html>
<head>
<title>Radio Box Control</title>
</head>
<body>
<form>
<input type = "radio" name = "subject" value = "maths"> Maths
<input type = "radio" name = "subject" value = "physics"> Physics
</form>
</body>
</html>

Attributes
Following is the list of attributes for radio button.

Sr. Attribute & Description


No

1 type
Indicates the type of input control and for checkbox input control it will be set to radio.

2 name
Used to give a name to the control which is sent to the server to be recognized and get the
value.

3 value
The value that will be used if the radio box is selected.

Developed By. Dr. Munesh Thakre Page 45 of 306


Web Engineering BE CSE SEM-VII

4 checked
Set to checked if you want to select it by default.

Select Box Control


A select box, also called drop down box which provides option to list down various options in the
form of drop down list, from where a user can select one or more options.
Example
<html>
<head>
<title>Select Box Control</title>
</head>
<body>
<form>
<select name = "dropdown">
<option value = "Maths" selected>Maths</option>
<option value = "Physics">Physics</option>
</select>
</form>
</body>
</html>

Attributes
Following is the list of important attributes of <select> tag −

Sr. Attribute & Description


No

1 name
Used to give a name to the control which is sent to the server to be recognized and get the
value.

2 size
This can be used to present a scrolling list box.

3 multiple
If set to "multiple" then allows a user to select multiple items from the menu.

Following is the list of important attributes of <option> tag −

Sr. Attribute & Description

Developed By. Dr. Munesh Thakre Page 46 of 306


Web Engineering BE CSE SEM-VII

No

1 value
The value that will be used if an option in the select box box is selected.

2 selected
Specifies that this option should be the initially selected value when the page loads.

3 label
An alternative way of labeling options

File Upload Box


If you want to allow a user to upload a file to your web site, you will need to use a file upload box,
also known as a file select box. This is also created using the <input> element but type attribute is
set to file.
Example
<html>
<head>
<title>File Upload Box</title>
</head>
<body>
<form>
<input type = "file" name = "fileupload" accept = "image/*" />
</form>
</body>
</html>

Attributes
Following is the list of important attributes of file upload box −

Sr. Attribute & Description


No

1 name
Used to give a name to the control which is sent to the server to be recognized and get the
value.

2 accept
Specifies the types of files that the server accepts.

Developed By. Dr. Munesh Thakre Page 47 of 306


Web Engineering BE CSE SEM-VII

Button Controls
There are various ways in HTML to create clickable buttons. You can also create a clickable button
using <input>tag by setting its type attribute to button. The type attribute can take the following
values −

Sr. Type & Description


No

1 submit
This creates a button that automatically submits a form.

2 reset
This creates a button that automatically resets form controls to their initial values.

3 button
This creates a button that is used to trigger a client-side script when the user clicks that
button.

4 image
This creates a clickable button but we can use an image as background of the button.

Example
<html>
<head>
<title>File Upload Box</title>
</head>
<body>
<form>
<input type = "submit" name = "submit" value = "Submit" />
<input type = "reset" name = "reset" value = "Reset" />
<input type = "button" name = "ok" value = "OK" />
<input type = "image" name = "imagebutton" src = "/html/images/logo.png" />
</form>
</body>
</html>

Hidden Form Controls


Hidden form controls are used to hide data inside the page which later on can be pushed to the
server. This control hides inside the code and does not appear on the actual page. For example,
following hidden form is being used to keep current page number. When a user will click next page

Developed By. Dr. Munesh Thakre Page 48 of 306


Web Engineering BE CSE SEM-VII

then the value of hidden control will be sent to the web server and there it will decide which page
will be displayed next based on the passed current page.
Example
<html>
<head>
<title>File Upload Box</title>
</head>
<body>
<form>
<p>This is page 10</p>
<input type = "hidden" name = "pagename" value = "10" />
<input type = "submit" name = "submit" value = "Submit" />
<input type = "reset" name = "reset" value = "Reset" />
</form>
</body>
</html>

Developed By. Dr. Munesh Thakre Page 49 of 306


Web Engineering BE CSE SEM-VII

Introduction to CSS
CSS stands for Cascading Style Sheet. CSS describes how HTML elements are to displayed on
screen, paper, or in other media. It saves a lot of work. It can control the layout of multiple web
pages all at once. CSS allows you to control the look and feel of several pages by changing a single
source. External style sheets are stored in CSS files.
CSS was developed by W3C in 1996 for a rather simple reason. HTML element was not designed to
have tags that would help format the page. You were only supposed to write the markup for the web
page.
Advantages
 CSS saves time
You can write CSS once and reuse the same sheet in multiple HTML pages.
 Easy Maintenance
To make a global change simply change the style, and all elements in all the web pages will be
updated automatically.
 Search Engines
CSS is considered a clean coding technique, which means search engines won’t have to struggle
to “read” its content.
 Superior styles to HTML
CSS have a much wider array of attributes that HTML, so you can give a far better look to your
HTML page in comparison to HTML attributes.
 Offline Browsing
CSS can store web applications locally with the help of an offline cache. Using this we can view
offline websites.
 Faster Page Speed
More code means slower page speed. And CSS enables you to use less code. CSS allows you to
use one CSS rule and apply it to all occurrences of a certain tag within an HTML document.
 Better User Experience
CSS not only makes web pages easy on the eye, but it also allows for user-friendly formatting.
When buttons and text are in logical places and well organized, user experience improves.
 Quicker Development Time
With CSS, you can apply specific formatting rules and styles to multiple pages with one string of
code. Once cascading style sheet can be replicated across several website pages. If, for instance,

Developed By. Dr. Munesh Thakre Page 50 of 306


Web Engineering BE CSE SEM-VII

you have product pages that should all have the same formatting, look, and feel, writing CSS
rules for one page will suffice for all pages of that same type.
 Easy Formatting Changes
If you need to change the format of a specific set of pages, it’s easy to do so with CSS. There’s
no need to fix every individual page. Just edit the corresponding CSS stylesheet and you’ll see
changes applied to all the pages that are using that style sheet.
 Compatibility across Devices
Responsive web design matters. In today’s day and age, web pages must be fully visible and
easily navigable on all devices. Whether mobile or tablets, desktop, or even smart TV, CSS
combines with HTML to make responsive design possible.

Overview of CSS
CSS stands for Cascading Styel Sheets. It is the language for describing the presentation of Web
pages, including colors, layout, and fonts, thus making our web pages presentable to the users.
CSS is designed to make style sheets for the web. It is independent of HTML and can be used with
any XML based markup language. Now let’s try to break the acronym”
Cascading: Falling of Styles
Style: Additing designs/|Styling our HTML tag.
Sheets: Writing our style in different documents.

CSS History
1994: First Proposed by HakonWium Lie on 10th October.
1996: CSS was published on 17th November with influencers Bert Bos. Later he became co-author of
the CSS.
1996: CSS became official, CSS was published in December.
1997: Created CSS level 2 on 4th November.
1998: Published on 12th May.

CSS Editors
Some of the popular editors that are best suited to write CSS code are as follows:
1. Atom
2. Visual Studio Code
3. Brackets

Developed By. Dr. Munesh Thakre Page 51 of 306


Web Engineering BE CSE SEM-VII

4. Espresso (For Mac OS User)


5. Notepad++ (Greate for HTML & CSS)
6. Komodo Edit (Simple)
7. Sublime Text (Best Editor)

CSS Versions
Cascading Style Sheet (CSS) is a separate language with its syntax, which enables you to lay out web
pages exactly as you want them. As HTML grew, it came to encompass a wider variety of stylistic
capabilities to meet the demands of web programmers. By the end of 1996, Cascading Style Sheets
was ready to become official, and the CSS level 1 recommendation was published in December,
which is considered the first version of CSS. Each level of CSS builds upon the last, typically adding
new features and typically denoted as CSS level 1, CSS level 2, CSS level 3 and CSS level 4.
CSS Level 1
CSS Level 1 (CSS1) was officially released in 1996 and included properties for addition font
properties such as typeface and emphasis color of text, backgrounds, and other elements. Text
attributes such as spacing between words, letters, and lines of text. Unfortunately, the lack of
dependable web browser support prevented the popularity of CSS Level 1 for several years.
CSS Level 2
CSS Level 2 (CSS2) specification was developed by W3C and published as a recommendation in
1998. Its most notably added properties for positioning that allowed CSS to be used for page layout.
It also introduced styles for other media types and more sophisticated methods for selecting elements
for styling.
CSS Level 3
The earlist CSS Level 3 (CSS3) drafts were published in 1999. CSS3 adds presentation style
properties, allowing you to effectively build presentations from Web documents. CSS Level 3 is
divided into several separate documents called modules. Due to modularization, different modules
have different stability and statuses.
CSS Level 4
There is no single CSS4 specification and there is no standard named CSS4. But a few levels 4
modules exist such as Image Values, Backgrounds & Borders, Selectors, etc. which build on the
functionality of a preceding level 3 module. The level 4 modules can collectively be referred to as
CSS level 4. There is only a CSS standard, and each module can level up independently.

Developed By. Dr. Munesh Thakre Page 52 of 306


Web Engineering BE CSE SEM-VII

Creation of CSS
CSS is one of three cornerstone technologies used on the web (the other two are HTML and
JavaScript).
CSS is used as a way of defining how HTML code is going to look on a website. Whereas HTML is
used to create content, including written text, CSS alters the way a web page will look.
So, depending on the data they want to display, a developer might choose to have a page with tabs
running across the top of the page or along the side. Or, another developer might choose to use
headings and subheading style to ensure that the words leap off the page or, change or revamp an
existing webpage entirely.
Why do we need CSS?
Firstly, using CSS ensures that your web pages are consistent. Imagine a website with 100s of pages,
now imagine having to input the code to define heading sizes, layout, and other display data and mix
that all in with the content each time you wanted to produce a new page. Also, imagine having a site
with 100s of pages and being able to change just one of them while keeping all the rest the same –
CSS also makes that a possibility. Using CSS delivers consistency where it is needed but is flexible
enough to enable you to make changes to individual pages or sections. Using CSS allows a user to
specify:
 Fonts
 Color of text and links
 User colors in the text’s background
 Where and how boxes within the content look and are placed.
 CSS also improves user accessibility, efficiency, and flexibility and ensures browser
compatibility.
Who Invented CSS?
According to Wikipedia, the birth of CSS is largely credited to Norwegian HakonWium Lie, who
back in 1994 sought to create a universal standardized style sheet for the World Wide Web.

Maintenance of CSS
Cascading Styel Sheets, or CSS in short, is used when we need to apply styles to our websites. The
use of CSS makes it easier for us to make a website presentable. It separates the structure, which is
made up of an HTML document, from the presentation, which implies the part which the user sees
and interacts with.

Developed By. Dr. Munesh Thakre Page 53 of 306


Web Engineering BE CSE SEM-VII

Why do we need CSS for the presentation?


Having a different and creative style has become a must-have property for a website, as it makes the
website fun to interact with, instead of a plain and dull-looking website that can be made using only
HTML. There are three ways in which we can apply CSS to our website.
What was before CSS?
Before CSS was available, HTML introduced tags like <font> or color attributes which were used
for styling purposes. But large websites that incorporated font and color information to each page
where time consuming and expensive processes to create. This is why CSS was introduced which
eliminated HTML formatting using such weird tag.
The introduction of CSS separated the structure and styling, where HTML was used for structuring
the web page while CSS focused on incorporating style and presentation in the web page.

CSS Syntax
A CSS Syntax rule consists of a selector, property, and its value. The selector points to the HTML
element where the CSS style is to be applied. The CSS property is separated by semicolons. It is a
combination of the selector name followed by the property:value pair that is defined for the specific
selector.
A CSS rule set consists of a selector and a declaration block.

The Selector indicates the HTML elements you want to style. The declaration block contains one or
more declarations separated by semicolons. Each declaration includes a CSS property name and a
value, separated by colon. A CSS declaration always ends with a semicolon, and declaration blocks
are surrounded by curly braces.
A Property is a type of attribute of HTML element. It could be color, border etc. Values are
assigned to CSS properties.
Example:
In this example all <p> elements will be center-aligned, with a red text color:
p{

Developed By. Dr. Munesh Thakre Page 54 of 306


Web Engineering BE CSE SEM-VII

color:red;
text-align:center;
}
Here p is a selector in CSS, color is a property, and red is the property value, text-align is a
property, and center is the property value.

Types of CSS or Multiple Style Rules


CSS can be added to HTML elements in 3 ways:
 Inline: by using the style attribute in HTML, elements.
 Internal or Embedded: by using a <style> element in the <head> section.
 External: by using an external CSS file.
Inline CSS
An inline CSS is used to apply a unique style to a single HTML, element. An inline CSS uses the
style attribute of an HTML element.
Example:
<h1 style= “color:blue;”>This is a Blue Heading</h1>
Above code sets the text color of the <h1> element to blue.
Output:

Internal CSS
An internal CSS is used to define a style for a single HTML page. An internal CSS is defined in the
<head> section of an HTML page, within a <style> element.
Example:
<HTML>
<HEAD>
<TITLE>
Internal CSS
</TITLE>
<STYLE>
h1{color:red;}
p{color:green;}
</STYLE>
</HEAD>
<BODY>
<h1>This is Heading1</h1>

Developed By. Dr. Munesh Thakre Page 55 of 306


Web Engineering BE CSE SEM-VII

<p>This is Paragraph1</p>
<h1>This is Heading2</h1>
<p>This is Paragraph2</p>
</BODY>
</HTML>
Output:

External CSS
External style sheet is used to define the style for many HTML pages. With an external style sheet,
you can change the look of an entire web site, by changing one file.
To use an external style sheet, add a link to it in the <head> section of the HTML page:
Example: Prog004.html
<HTML>
<HEAD>
<TITLE>
External CSS
</TITLE>
<LINK rel="stylesheet" href="CSSProg1.css">
</HEAD>
<BODY>
<h1>This is External CSS Heading1</h1>
<p>This is External CSS Paragraph1</p>
<h1>This is External CSS Heading2</h1>
<p>This is External CSS Paragraph2</p>
</BODY>
</HTML>

Example: CSSProg1.css
h1{color:blue;}
p{color:red;}

Output:

Developed By. Dr. Munesh Thakre Page 56 of 306


Web Engineering BE CSE SEM-VII

CSS Basic Properties


 Text Properties
 Font Properties
Text Properties
Property Description Values Example
Color Sets the color of text. Color-name, hex- H1{color:red}
number, rgb-number.
Background- Sets the background color Color-name, hex- Body{background-
color in webpage. number, rgb-number. color:pink}
Letter-spacing Increases or decreases the Normal, length H1{letter-
space between characters. spacing:5pt}
Text-align Aligns the text in an Left, right, center, justify H1{text-align:center}
element.
Text-decoration Adds decoration to text. None, underline, P{text-
overline, line-through decoration:underline}
Padding Adds padding (blank Pixel H1{padding:30px}
spaces) around the content
of an element.
Background- Sets an image at the Path of image file Body{background-
image background of your image:url(‘back.jpg’)}
webpage.
Margin-left Sets margin area on the Px, pt, cm etc H1{margin-left:10px}
left side of the element.
Border Adds a border to a Solid, double, groove, H1{border:solid}
webpage element. ridge, inset, outset,
dotted or dashed
Border-color Sets the color of the four Color-name, hex- H1{border-

Developed By. Dr. Munesh Thakre Page 57 of 306


Web Engineering BE CSE SEM-VII

borders number, rgb-number. color:green}


Border-style Sets the style of the four None, hidden, dotted, dashed, H1{border-
solid, double, groove, ridge,
borders. style:dotted}
inset, outset, inherit
Border-width Sets the width of the four Thin, medium, thick, H1{border-
border length, inherit width:thin}

Font Properties
Property Description Values Examples
Font-family Specifies the font Family-name, generic- P{font-family:Times
family for text. family, inherit New Roman}
Font-size Specifies the font size xx-small, x-small, P{font-size:15px}
of text. small, medium, large,
x-large, xx-large,
smaller, larger, length,
%, inherit.
Font-style Specifies the font style Normal, italic, oblique, P{font-style:normal}
for text. inherit
Font-variant Specifies whether or Normal, small-caps, P{font-variant:small-
not a text should be inherit caps}
displaed in a small
caps font.
Font-weight Specifies the weight of Normal, bold, bolder, P{font-
a font. lighter, 100, 200, 900 weight:normal}

Question 1: Write a program using html5 with following CSS specification.


 The background color of the company name should be in green.
 The text color of the company name should be red.
 The heading should be large with font “comic sans ms”.
 The description of the company should be displayed in blue color in a paragraph.
Solution:
<HTML>
<HEAD>
<TITLE>
Company Info

Developed By. Dr. Munesh Thakre Page 58 of 306


Web Engineering BE CSE SEM-VII

</TITLE>
<STYLE>
H1{background-color:green; color:red; font-family:comic sans ms; }
P{color:blue}
</STYLE>
</HEAD>
<BODY>
<H1>Nagpur University</H1>
<P>The University was established before freedom. <br>This is one of the premier university
of India.</P>
</BODY>
</HTML>

Output:

Types of Selector
The CSS id Selector
The id selector uses the id attribute of an HTML element to select a specific element. The id of an
element is unique within a page, so the id selector is used to select one unique element. To select an
element with a specific id, write a hash (#) character, followed by the id of the element.
Example: The CSS rule below will be applied to the HTML element with id= “para”:
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>
Illustration of ID selector
</TITLE>
<STYLE>
#para{text-align:center;color:red;}
</STYLE>
</HEAD>
<BODY>
<h1 id="para">This is Heading 1</h1>
<h1>This is Heading 2</h1>
<p id="para">This is First Paragraph</p>
<p>This is Second Paragraph</p>
</BODY>

Developed By. Dr. Munesh Thakre Page 59 of 306


Web Engineering BE CSE SEM-VII

</HTML>
Output:

The CSS class Selector


The class selector selects HTML elements with a specific class attribute. To select elements with a
specific class, write a period (.) character, followed by the class name.
Example: Here all HTML elements with class= “center” will be red and center-aligned.
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>
Illustration of class selector
</TITLE>
<STYLE>
.center{text-align:center;color:red;}
</STYLE>
</HEAD>
<BODY>
<h1 class="center">This is Heading 1</h1>
<h1>This is Heading 2</h1>
<p class="center">This is First Paragraph</p>
<p>This is Second Paragraph</p>
</BODY>
</HTML>

Output:

Class selector for specific element


You can also specify that only specific HTML elements should be affected by a class. In this case
you should use the element name with class selector.

Developed By. Dr. Munesh Thakre Page 60 of 306


Web Engineering BE CSE SEM-VII

Example:
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>
Illustration of class selector specific
</TITLE>
<STYLE>
p.center{text-align:center;color:red;}
</STYLE>
</HEAD>
<BODY>
<h1 class="center">This is Heading 1</h1>
<h1>This is Heading 2</h1>
<p class="center">This is First Paragraph</p>
<p>This is Second Paragraph</p>
</BODY>
</HTML>

Output:

The CSS Universal Selector


The universal selector is used as a wildcard character. The universal selector (*) selects all HTML
elements on the page.
Example:
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>
Illustration of CSS universal selector
</TITLE>
<STYLE>
*{
text-align:center;
color:blue;
}
</STYLE>
</HEAD>
<BODY>

Developed By. Dr. Munesh Thakre Page 61 of 306


Web Engineering BE CSE SEM-VII

<h1>This is Heading 1</h1>


<p>This is Paragraph 1</p>
<p>This is Praragraph 2</p>
</BODY>
</HTML>
Output:

Grouping Selector
The grouping selector is used to select all the elements with the same style definitions. It is used to
minimize the code. Commas are used to separate each selector in grouping.
For example without group, the syntax will be:
b{color:blue;background-color:pink}
i{color:blue;background-color:pink}
u{ color:blue;background-color:pink}
It can be grouped as:
b,i,u{ color:blue;background-color:pink}
Above <b>, <i> and <u> tags will use the same style for formatting. In any of the selector is to be
given additional formatting that tag needs to be redefined.
Example:
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>
Illustration of Grouping Selector
</TITLE>
<STYLE>
b,i,u{color:blue;background-color:pink}
</STYLE>
</HEAD>
<BODY>
<b>This is First Line</b><br><br>
<i>This is Second Line</i><br><br>
<u>This is Third Line</u>
</BODY>
</HTML>
Output:

Developed By. Dr. Munesh Thakre Page 62 of 306


Web Engineering BE CSE SEM-VII

Descendant Selectors
Descendant Selector is one of the types of Combinators in CSS where the combinators combine two
selectors in such a way that if an ancestor element matches with the first selector, then the elements
matched by the second selector will be selected and these selectors use the descendant Combinator
are Descendant Selector. In simple words, the Descendant Selectors can be any selector having white
space in between the elements without using any combinators. Descendant is a manner to nest
anywhere within the DOM tree. This selector is used to select all the child elements of the specified
tag.
Syntax
first_selectorsecond_selector{
css properties: values;
}
The simple selector (first_selector) represents the ancestor element or parent element, and the second
simple selector (second_selector) represents the descendant element. We use white space between
these two to represent the descendant selector.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Descendant Selector
</title>
<style>
div p{
background-color:lightblue;
font-weight:bold;
}
</style>
</head>
<body>
<div>
This is Division 1
<p>This is the First Paragraph in the Division1</p>

Developed By. Dr. Munesh Thakre Page 63 of 306


Web Engineering BE CSE SEM-VII

<p>This is the Second Paragraph in the Division1</p>


<div>
This is Division 2
<p>This is First Paragraph of Nested Division</p>
<p>This is Second Paragraph of Nested Division</p>
</div>
</div>
<p>This is Outside Paragraph</p>
</body>
</html>

Output:

Child Selectors
CSS Child Selector is defined as the CSS selector that selects only elements that are direct children
which is clearer than the contextual selector. This selector uses greater than the symbol “>” that
appears between two different selectors, and it is more specific than the descendant selector, which
helps to simplify the CSS style code. The second selector should be the immediate children of the
elements.
Syntax
Element1 > Element2 {
Style properties code…;
}
How does Child Selector work in CSS?
The working process is very simle. This child selector has two selectors to work with and is
separated by the “>” symbol. The first selector says that it is a parent element, and the second
selector says it is a child element with style properties.

Developed By. Dr. Munesh Thakre Page 64 of 306


Web Engineering BE CSE SEM-VII

Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Child Selector
</title>
<style>
div > p{
background-color:salmon;
color:azure;
font-size:10px;
padding:3px;
}
</style>
</head>
<body>
<div>
This is Division 1
<p>This is the First Paragraph in the Division1</p>
<p>This is the Second Paragraph in the Division1</p>
<div>
This is Division 2
<p>This is First Paragraph of Nested Division</p>
<p>This is Second Paragraph of Nested Division</p>
</div>
</div>
<p>This is Outside Paragraph</p>
</body>
</html>

Output:

Developed By. Dr. Munesh Thakre Page 65 of 306


Web Engineering BE CSE SEM-VII

Attribute Selectors
The CSS attribute selector is used when we want to style multiple HTML, elements that have the
same attribute or attribute values. It is a very convenient way to style multiple element by grouping
them based on simple attributes. The attribute selector selects all the elements that have a particular
attribute and sets the styling for all of them. The attribute selectors are by default case sensitive and
can be written in the square brackets [].
Types of Attribute Selectors
There are several types of attribute selectors, which are given below:
 CSS [attribute] selector
 CSS [attribute= “value”] selector
 CSS [attribute ~= “value”]
 CSS [attribute |= “value”]
 CSS [attribute ^= “value”]
 CSS [attribute $= “value”]
 CSS [attribute *= “value”]
CSS [attributes] selector
The [attribute] selector selects all the elements that contain the name attribute and applies the CSS
properties to all of them at once. For example, the selector [class] will select and style all the
elements that have the same class name.
Syntax of [attributes] selector
HTML element[attribute]/[attribute] {
/*CSS properties */
}
Example: Applying [attribute] selector
In the given example, we have created four paragraphs using the <p> element. In the first and last
paragraph, we have specified the class attribute along with its value para then we have specified the
CSS properties using the CSS [attribute] selector for the <p> element using the class attribute.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Attribute Selector
</title>
<style>
[class]{

Developed By. Dr. Munesh Thakre Page 66 of 306


Web Engineering BE CSE SEM-VII

background-color: red;
color:black;
}
</style>
</head>
<body>
<p class="para">This is First Paragraph</p>
<p>This is Second Paragraph</p>
<p>This is Third Paragraph</p>
<p class="para">This is Fourth Paragraph</p>
</body>
</html>

Output:

CSS [attribute= “value”] selector


This [attribute= “value”] selector allows us to select and set styling properties to all the elements
whose attribute value is the same as the assigned value.
Syntax of [attribute= “value”] selector
HTML element [attribute= “value”] {
/*CSS property */
}
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Attribute Selector
</title>
<style>
p[class="test"]{
background-color: yellow;
color:black;
}
</style>
</head>
<body>

Developed By. Dr. Munesh Thakre Page 67 of 306


Web Engineering BE CSE SEM-VII

<h2 class="test" >This is First Heading</h2>


<p class="para">This is First Paragraph</p>
<p class="test">This is Second Paragraph</p>
<p class="para">This is Third Paragraph</p>
<p class="test">This is Fourth Paragraph</p>
</body>
</html>

Output:

CSS [attribute ~= “value”] selector


The CSS [attribute ~= “value”] selector allows us to set CSS properties to all the elements whose
value contains a specified word.
Syntax of [attribute ~= “value”] selector
HTML element [attribute ~= “value”] {
/*CSS property */
Property:value;
}
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Attribute Selector
</title>
<style>
[class~="test"]{
border:2px solid red;
}
</style>
</head>
<body>
<h2 class="test demo" >This is First Heading</h2>

Developed By. Dr. Munesh Thakre Page 68 of 306


Web Engineering BE CSE SEM-VII

<p class="para">This is First Paragraph</p>


<p class="test">This is Second Paragraph</p>
<p class="para">This is Third Paragraph</p>
<p class="demo test">This is Fourth Paragraph</p>
</body>
</html>

Output:

CSS [attribute |= “value”] selector


The CSS [attribute |= “value”] selector is used to select the elements with specified attributes that
start with a particular value.
Syntax of [attribute |= “value”] selector
HTML element [attribute |= “value”] {
/*CSS property */
Property:value;
}
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Attribute Selector
</title>
<style>
[class|="test"]{
border:2px solid blue;
}
</style>
</head>
<body>
<h2 class="test-heading" >This is First Heading</h2>
<p class="para-test">This is First Paragraph</p>
<p class="test-para">This is Second Paragraph</p>

Developed By. Dr. Munesh Thakre Page 69 of 306


Web Engineering BE CSE SEM-VII

<p class="test-1">This is Third Paragraph</p>


<p class="demo test">This is Fourth Paragraph</p>
</body>
</html>

Output:

CSS [attribute ^= “value”] selector


The CSS [attribute ^= “value] selector is used to select a value whose attribute value begins with a
particular value.
Syntax of [attribute ^= “value”] selector
HTML element [attribute ^= “value”] {
/*CSS property */
Property:value;
}
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Attribute Selector
</title>
<style>
[class^="test"]{
border:2px solid yellow;
}
[class^="para"]{
border:2px solid red;
}
</style>
</head>
<body>
<h2 class="test heading" >This is First Heading</h2>
<p class="test 2">This is First Paragraph</p>

Developed By. Dr. Munesh Thakre Page 70 of 306


Web Engineering BE CSE SEM-VII

<p class="para-1">This is Second Paragraph</p>


<p class="demo test">This is Third Paragraph</p>
<p class="para-2">This is Fourth Paragraph</p>
</body>
</html>

Output:

CSS [attribute $= “value”] selector


The CSS [attribute $= “value”] selector selects the element whose attribute value ends with the
particular value.
Syntax of [attribute $= “value”] selector
HTML element [attribute $= “value”] {
/*CSS property */
Property:value;
}
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Attribute Selector
</title>
<style>
[class$="test"]{
border:2px solid lightgreen;
}
</style>
</head>
<body>
<h2 class="heading test" >This is First Heading</h2>
<p class="test 1">This is First Paragraph</p>
<p class="3 test">This is Second Paragraph</p>

Developed By. Dr. Munesh Thakre Page 71 of 306


Web Engineering BE CSE SEM-VII

<p class="demo test">This is Third Paragraph</p>


<p class="para-2">This is Fourth Paragraph</p>
</body>
</html>

Output:

CSS [attribute *= “value”] selector


The CSS [attribute *= “value”] selector selects the element in which the attribute value contains a
specified value.
Syntax of [attribute *= “value”] selector
HTML element [attribute *= “value”] {
/*CSS property */
Property:value;
}
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Attribute Selector
</title>
<style>
[class *="te"]{
border:2px solid red;
}
</style>
</head>
<body>
<h2 class="test" >This is First Heading</h2>
<p class="demo test">This is First Paragraph</p>
<p class="temple">This is Second Paragraph</p>

Developed By. Dr. Munesh Thakre Page 72 of 306


Web Engineering BE CSE SEM-VII

<p class="demo">This is Third Paragraph</p>


<p class="para-2">This is Fourth Paragraph</p>
</body>
</html>

Output:

Positioning in CSS
CSS helps to position the HTML elements. The position property defines how an element will be
positioned on a page. The element can be positioned using the top, bottom, left and right properties.
Syntax:
Selector{position:value;top:value;left:value;bottom:value;right:value}
Where values in positions are fixed, absolute, relative and values of top, bottom, left, right are in
pixels.
Positioning Methods
Positioning elements appropriately on the web pages is a necessity for a good layout design. There
are four types of positioning in CSS.
Static Positioning
A static positioned element is always positioned according to the normal flow of the page. HTML
elements are positioned static by default.
Static positioned elements are not affected by the top, bottom, left, right and z-index properties.
Example:
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>
Illustration of Static Positioning
</TITLE>
<STYLE>
div.static{
position:static;

Developed By. Dr. Munesh Thakre Page 73 of 306


Web Engineering BE CSE SEM-VII

border:3px solid#73Ad21;
}
</STYLE>
</HEAD>
<BODY>
<h2>Position Static</h2>
<p>A static positioned element is always positioned
according to the format flow of the page</p>
<div class="static">
This div element has position:static;
</div>
</BODY>
</HTML>

Output:

Relative Positioning
A relative positioned element is positioned relative to its normal position. In the relative positioning
scheme the elements box position is calculated according to the normal flow. Then the box is shifted
from this normal position according to the properties – top or bottom and/or left or right.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Relative Positioning
</title>
<style>
div.relative{
position:relative;
left:30px;
border:3px solid #73ad21;
}
</style>
</head>
<body>
<h2>Position Relative</h2>
<p>An element with position relative is positioned

Developed By. Dr. Munesh Thakre Page 74 of 306


Web Engineering BE CSE SEM-VII

relative to its normal position.


</p>
<div class="relative">
This div element has position:relative;
</div>
</body>
</html>

Output:

Absolute Positioning
An absolute positioned element is positioned relative to the first parent element that has a position
other than static. If no such element is found, it will be positioned on a page relative to the ‘top-left’
of the browser window.
The box’s offsets further can be specified using one or more of the properties top, right, bottom, and
left.
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Absolute Positioning
</title>
<style>
div.relative{
position:relative;
width:400px;
height:200px;
border:3px solid #73ad21;
}
div.absolute{
position:absolute;
top:80px;
right:0;
width:200px;
height:100px;
border:3px solid #73AD21;
}
</style>

Developed By. Dr. Munesh Thakre Page 75 of 306


Web Engineering BE CSE SEM-VII

</head>
<body>
<h2>Position Absolute</h2>
<div class="relative">This div element has position
relative;
<div class="absolute">This div element has position
absolute.
</div>
</div>
</body>
</html>

Output

Fixed Positioning
Fixed positioning is a subcategory of absolute positioning. This property helps to put the text fixed
on the browser. The FIXED property forces an element into a fixed position relative to the browser
window. The fixed element does not move, even when the page is scrolled.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Fixed Positioning
</title>
<style>
div.fixed{
position:fixed;
bottom:0;
right:0;
width:300px;
border:3px solid #73ad21;

Developed By. Dr. Munesh Thakre Page 76 of 306


Web Engineering BE CSE SEM-VII

}
</style>
</head>
<body>
<h2>Position Fixed</h2>
<p>An element with position fixed is positioned
relative to the viewpoint</p>
<div class="fixed">This div element has position
fixed;
</div>
</body>
</html>

Output:

Float Property
Float is a CSS property written in CSS file or directly in the style of an element. This property
specifies how an element should float.
CSS Syntax
float:name[left|right]
Property Values
None The element doest not float. (will be displayed just where it occurs in the text).
This is default.
Left The element floats to the left of its container.
Right The element floats the right of its container.
Example:
<!DOCTYPE html>
<html>
<head>

Developed By. Dr. Munesh Thakre Page 77 of 306


Web Engineering BE CSE SEM-VII

<title>
Illustration of Float Property
</title>
<style>
img{
float:left;
}
</style>
</head>
<body>
<h2>Float Property</h2>
<p><img src="Books.jpg" alt="Books" style="width:50px;height:50px;"></p>
<p>Fixed positioning is a subcategory of absolute positioning.
This property helps to put the text fixed on the browser.
The FIXED property forces an element into a fixed position
relative to the browser window. The fixed element does
not move, even when the page is scrolled.</p>
</body>
</html>

Output:

Display Property
The display property specifies the display behavior (the type of rendering box) of an element. This is
most important CSS property for controlling layout.
The display property specifies how an element is displayed. This property is used to define the
display of different parts of a web pages.
CSS Syntax
display:value;
Property Values
Values Description
Inline Displays an element as in inline element (like <span>). Any height and width
properties will have no effect.

Developed By. Dr. Munesh Thakre Page 78 of 306


Web Engineering BE CSE SEM-VII

Block Displays an element as a block element (line <p>). It starts on a new line, and
takes up the whole width of the browser window.
Inline-block Displays an element as an inline level block container. The element itself is
formatted as an inline element, but you can apply height and width.
None The element is completely removed.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Display Property
</title>
<style>
p{
display:inline;
}
</style>
</head>
<body>
<h2>Display Property</h2>
<p>Welcome to Nagpur University</p>
<p>Colleges</p>
<p>Gondia</p>
</body>
</html>
Output:

Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Display Property
</title>
<style>
A{
display:block;background-color:pink;
}
</style>
</head>
<body>

Developed By. Dr. Munesh Thakre Page 79 of 306


Web Engineering BE CSE SEM-VII

<h2>Display Property</h2>
<p>Welcome to Nagpur University</p>
<p><A href="https://www.nmdcgondia.org">Visit to N.M.D. College, Gondia</A></p>
</body>
</html>
Output:

Question 2: Write a program using html5 with CSS to present school/college information.
 Write name of the school/college with larger heading with blue color.
 The color of remaining text should be red and background color pink.
 Insert appropriate image related to the theme. Use float property to wrap the text aound it.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Solution of Problem Number 2
</title>
<style>
h1{
color:blue;
text-align:center;
}
body{
color:red;
background-color:pink;
}
</style>
</head>
<body>
<h1>N.M.D. College, Gondia</h1>
"Following is the reaming text."
<p><img src="College.jpg" alt="College Image" style="width:120px; height:100px;float:left">
Natwarlal Maniklal Dalal College, the pioneering
educational institution of Gondia Education
Society is committed to carry forward the
legacy bestowed upon us by the great visionary
late Shri Manoharbhai Patel. It visualizes to
impart quality education to the poorest of the
poor.

Developed By. Dr. Munesh Thakre Page 80 of 306


Web Engineering BE CSE SEM-VII

</p>
</body>
</html>

Output:

Question 3: Write Html5 code with CSS as follows:


 Create form to accept name, age, email address from the user.
 Create a submit button to send the data.
 The heading of the form should have a background color and a different font style.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Solution of Problem Number 3
</title>
<style>
h2{
background-color:pink;
font-style:italic;
}
</style>
</head>
<body>
<h2>Registration Form</h2>
<form>
Name :<input type="text"><br><br>
Age :<input type="number" min="16" max="35"><br><br>
Email :<input type="email"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Output:

Developed By. Dr. Munesh Thakre Page 81 of 306


Web Engineering BE CSE SEM-VII

Question 4: Write Html5 code with CSS as follows:


 Create ordered list with names of tourist cities.
 Create unordered list with tourist places of those cities.
 Divide the list into two sections left and right by using CSS.
Example:
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>
Solution of Problem Number 4
</TITLE>
<STYLE>
.left{float:left;background-color:blue;width:50%;height:200px;border:solid;border-color:red}
.right{float:right;background-color:red;width:49%;height:200px;border:solid;border-
color:blue}
</STYLE>
</HEAD>
<BODY>
<h2 align="center">Tourist City and Place Details</h2>
<div class="left">
<h3>Tourist Cities in India</h3>
<ol>
<li>Mumbai</li>
<li>Delhi</li>
<li>Chennai</li>
<li>Kolkatta</li>
</ol>
</div>
<div class="right">
<h3>Mumbai</h3>
<ul>
<li>Gateway of India</li>
<li>Elephanta Caves</li>
<li>Marine Drive</li>
</ul>
</div>
</BODY>
</HTML>
Output:

Developed By. Dr. Munesh Thakre Page 82 of 306


Web Engineering BE CSE SEM-VII

Question 5: Create Login screen using Html5 code and CSS as follows:
 Create form which accepts username and password.
 Give the heading with background color – Tomato. Heading should takes up the whole width
of the browser window. Also increases font size and set top morgin.
 Make the provision to submit form data. Create button element of type “Submit” with
background color – black and text color – white. Also set the padding and increase font size.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Program for Solution of Problem Number 5
</title>
<style>
h2{
background-color: Tomato;
text-align:center;
display:block;
font-size:2.5Sem;
margin-top:0.8Sem;
}
.button{
color:white;
background-color:black;
padding:15px 100px;
font-size:20px;
}
</style>
</head>
<body>
<h2>Login Screen</h2>
<form>
User Name:<input type="text"><br><br>
Password :<input type="password"><br><br>
<center>
<button class="button">Submit</button>
</center>
</form>

Developed By. Dr. Munesh Thakre Page 83 of 306


Web Engineering BE CSE SEM-VII

</body>
</html>
Output:

Question 6: Write Html5 code with CSS as follows:


 Create user registration form having the fields – name, gender, address, and field of interest.
 Give appropriate heading with larger size and center alignment.
 Set background color of body to light grey and color of text blue.
 Create submit button to submit form data and reset button for clearing entries in form.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Program for Solution of Problem Number 6
</title>
<style>
h1{
color:red;
text-align:center;
}
body{
color:blue;
background-color:lightgrey;
}
</style>
</head>
<body>
<h1>Registration Form</h1>
<form>
Name :<input type="text"><br><br>
Gender :<input type="Radio" name="gender">Male <input type="Radio"
name="gender">Female<br><br>
Address :<textarea rows="3" cols="35"></textarea><br><br>
Field of Interest :<input type="checkbox">Reading
<input type="checkbox">Playing
<input type="checkbox">Singing<br><br>
<input type="Submit"><input type="Reset">
</form>
</body>
</html>
Output:

Developed By. Dr. Munesh Thakre Page 84 of 306


Web Engineering BE CSE SEM-VII

Question 7: Write Html5 code with CSS as follows:


 Write two separate texts – “CSS and Java Script” and “July 2023” separated with paragraph.
 Define bold tag for first text and italic tag for second text using Internal CSS with common
effect of font size 25 pixels, letter spacing 20 pixels, color blue. Also text should contain
blink effect.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Solution of Problem Number 7
</title>
<style>
b,i{
font-size:25px;
color:blue;
text-decoration:blink;
letter-spacing:20px;
}
</style>
</head>
<body>
<p><b>CSS and Java Script</b></p>
<p><i>July 2023</i></p>
</body>
</html>

Output:

Question 8: Write Html5 code with CSS as follows:

Developed By. Dr. Munesh Thakre Page 85 of 306


Web Engineering BE CSE SEM-VII

 Write text “Maharashtra State Board” using larger heading.


 Set background color yellow to this text. Also underline the text using any css with letter
spacing 20pts.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Solution of Problem Number 8
</title>
<style>
h1{
background-color: yellow;
text-align:center;
text-decoration:underline;
letter-spacing:20px;
}
</style>
</head>
<body>
<h1>MAHARASHTRA STATE BOARD</h1>
</body>
</html>

Output:

Question 9: Write Html5 code with CSS as follows:


 Design a form which accepts the user name.
 Also create radio button to display the mode of payment as COD, Debit, Credit, PAYTM etc.
 Make provision for submitting and clearing the form contents.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Solution of Problem Number 9
</title>

Developed By. Dr. Munesh Thakre Page 86 of 306


Web Engineering BE CSE SEM-VII

<style>
body{
background-color: chocolate;
color:white;
}
</style>
</head>
<body>
<form>
User Name :<input type="text"><br><br>
Mode of Payment :<br><input type="radio" name="mop">COD<br>
<input type="radio" name="mop">Debit<br>
<input type="radio" name="mop">Credit<br>
<input type="radio" name="mop">PayTM<br><br>
<input type="submit"><input type="reset">
</form>
</body>
</html>

Output:

Question 10: Write Html5 code with CSS as follows:


 Design personal information form that accepts name, age, address, status as working or non
working, qualification as X, XII, Graduate, Post Graduate.
 Buttons should be provided for submitting the form and clearing the form.

Question 11: Write Html5 code with CSS as follows:


 Design a form which accepts the Customer name.
 User dropdown list to display “Milkshake” which list as Strawberry, Banana, Mixed Berry.
 Providision should be made to submit and clear the form.
Example:
<!DOCTYPE html>

Developed By. Dr. Munesh Thakre Page 87 of 306


Web Engineering BE CSE SEM-VII

<html>
<head>
<title>
Solution of Problem Number 11
</title>
<style>
body{
background-color: chocolate;
color:white;
}
</style>
</head>
<body>
<form>
Customer Name :<input type="text"><br><br>
Milkshake :<select name="ms">
<option value="sb">Strawberry</option>
<option value="b">Banana</option>
<option value="mb">Mixed Berry</option>
</select><br><br>
<input type="submit"><input type="reset" value="Clear">
</form>
</body>
</html>

Output:

Question 12: Write Html5 code with CSS as follows:


 Design a form to accept name, address, and display snacks items with checkbox.
 Display ORDER button on web page using any css.
Question 13: Write Html5 code with CSS as follows:
 Design a form which displays a text “Maharashtra State” in three various heading level. All
three heading should have different background color. Also set underline, overline, and
strickethrough effect to headings. The web page should have background color yellow.
 Create 3 checkboxes to display 3 cities as Pune, Mumbai and Nagpur.
 Buttons should be provided for submitting the form and clearing the form.

Developed By. Dr. Munesh Thakre Page 88 of 306


Web Engineering BE CSE SEM-VII

Question 14: Write Html5 code with CSS as follows:


 Design a form in which creates a drop-down list of five cricket players name.
 The list should display Sachine Tendulkar, Rahul Dravid, M.S. Dhoni, Verendra Shewagh
and Vriat Kohali.
 The list should allow multiple selection by user. The font style of the list items should be
Verdana and background color red.
 Buttons should be provided for submit and clearing the form.
Question 15: Write Html5 code with CSS as follows:
 The background color of the institute name should be in violet with font style ‘Bookman Old
Style”.
 The text color of the paragraphs describing institute should be indigo.
 List the salient features of the institute using unordered list.

CSS Inclusion
There are the following four methods to use CSS stylesheet in HTML documents:
The internal style sheet – Embedded CSS
The external style sheet – External CSS
The inline style sheet – Inline CSS
The Imported CSS
In these methods, we use mostly External CSS and Inline CSS methods.
The Internal style sheet – Embedded CSS
The internal style sheet – Embedded CSS is written always in the HEAD element of the HTML
documents. The syntax in HTML document in written as follows:
<style type= “text/css” media= “all”>
Selector[property:value;]
</style>
Attribute:
Attributes associated with <style> elements are −

Attribute Value Description

type text/css Specifies the style sheet language as a content-type


(MIME type). This is required attribute.

Developed By. Dr. Munesh Thakre Page 89 of 306


Web Engineering BE CSE SEM-VII

media Screen, tty, tv, projection, Specifies the device the document will be
Handheld, print, Braille, aural, displayed on. Default value is all. This is an
all optional attribute.

Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Embedded CSS Inclusion
</title>
<style type="text/css" media="all">
body{
background-color:linen;
}
h1{
color:maroon;
margin-left:40px;
}
</style>
</head>
<body>
<h1>This is Heading</h1>
<p>This is Paragraph</p>
</body>
</html>

Output:

The External Style Sheet : External CSS


In this method, all CSS which you want ot use in your website or blog is declared in an external style
sheet. It’s separate file of CSS, which use to control the website user interface design that file
typically has an extension of “.CSS”. You can include it in all of your HTML, web pages.

Developed By. Dr. Munesh Thakre Page 90 of 306


Web Engineering BE CSE SEM-VII

Importing: The external style sheet, linked uses @import rules, here the @import keyword is used,
followed by the URL of the style sheet to which you want to import the style rules. The following
code shows an example of the @import rules.
<style type= “text/css”>
@import url[“new_stylesheet.css”]
H2{color:green;font-style:italic;}
</style>
Linking: The HTML link element is used to link a style sheet. This LINK element has the following
three attributes:
rel, href, type
<link rel= “stylesheet” href= “new_stylesheet.css” type= “text/css”>
Example:
CSS Program
h1,h2,h3{
color: #36C;
font-weight: normal;
letter-spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}

HTML Program
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of External CSS Inclusion
</title>
<link type="text/css" rel="stylesheet" href = "CSSProg2.css" media = "all">
</head>
<body>
<h1>This is Heading 1</h1>
<h2>This is Heading 2</h2>
<h3>This is Heading 3</h3>
<h4>This is Heading 4</h4>
</body>
</html>

Output:

Developed By. Dr. Munesh Thakre Page 91 of 306


Web Engineering BE CSE SEM-VII

Inline Style – Inline CSS


The inline style – inline CSS, properties are always written in single lines separated by semicolons
and inline CSS properties placed inside the HTML element.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Inline CSS Inclusion
</title>
</head>
<body>
<h1 style="color:blue;font-style:italic">This is Heading 1</h1>
<h2>This is Heading 2</h2>
<h3>This is Heading 3</h3>
<h4>This is Heading 4</h4>
</body>
</html>

Output:

Imported CSS
We can import additional CSS file inside another CSS declaration. The @import rule is used for this
purpose as it links a stylesheet in a document. This is generally used when one stylesheet is

Developed By. Dr. Munesh Thakre Page 92 of 306


Web Engineering BE CSE SEM-VII

dependent upond another. It is specified at the top of the document after @charset declaration inside
<head>.
Syntax: The syntax of the @import rule is as follows:
@import /*url or list of media queries */
The media queries can be compounded statements that may specify the behavior of the document in
different media.
Example:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
@import url(CSSProg1.css);
body{
background-color:honeydew;
}
</style>
</head>
<body>
<h1>This is Heading 1</h1>
<p>This is Demo Paragraph</p>
</body>
</html>

Output:

The Element of CSS


The element element selector in CSS is used to select elements inside the elements i.e. it combines
two selectors such that elements matched by the second selector are selected if they have an ancestor
element matching the first selector.
Syntax
element element{
//CSS Property
}
Example:
<!DOCTYPE html>

Developed By. Dr. Munesh Thakre Page 93 of 306


Web Engineering BE CSE SEM-VII

<html>
<head>
<title>
Illustration of Element CSS
</title>
<style>
div p{
background-color:green;
color:white;
}
</style>
</head>
<body>
<h2>Division 1</h2>
<div>
<p>This is Division 1 Paragraph</p>
</div>
<p>This is General Paragraph</p>
</body>
</html>

Output:

@Import Rule
CSS is the design backbone for the majority of web pages. It specifies how the items should be
shown on the screen. This is where the CSS @import at rule comes in.
The @import rule directs the CSS engine to import an external style sheet into another style sheet.
This enables the addition of style rules from one style sheet to another. This rule can be combined
with media queries to import a style sheet dependent on the type of device.
The @import style rule is useful since it can be used to avoid duplicating style rules and even import
specific styles dependent on the device that is accessed. The @import rule must be placed at the very
top of the style sheet.
@import “style.css”; /*using a string */
@import url(“example.css”); /*using a URL*/

Developed By. Dr. Munesh Thakre Page 94 of 306


Web Engineering BE CSE SEM-VII

@import “mediaquery.css” print; /*using a media query*/


Syntax:
@import url|string list-of-mediaqueries;
Here,
url|string – The location of the resource to be imported is represented by a URL or a string.
The URL might be either relative or absolute.
list-of-mediaqueries – The list of media queries defines how the CSS rules given in the linked
URL are applied.
Advantages of CSS @import
The most advantageious aspect of CSS @import is that it saves your time and frustration. If you
don’t use @import, you’re wither using old CSS to copy and paste the information you need or
handling all style rules in a single style sheet. As your website increases in size and the code become
more difficult to find, this can be time consuming, frustrating, and even difficult. Even worse, having
redundant styles results in a larger style sheet, which might reduce website performance.
CSS @import not only saves time but also delivers excellent accuracy. Rather then potentially
establishing bad style rules or copying and pasting incorrect information, simply import the existing
rules. This is straightforward and precise, especially when compared to the alternatives. It can also be
used to segregate your style rules into different style sheets, for example:
@import “buttons.css”;
@import “links.css”;
@import “forms.css”;
Disadvantages of CSS @import
 The only negative of using the @import declaration is that it increases page load time if it is
used during the build process.
 It reads the imports and then applies them as it proceeds.
 At the time of searching bot and page loading time to calculate a ranking.

CSS Rules Overriding


CSS allows you to apply styles to web pages. More importantly, CSS enables you to do this
independently of the HTML that makes up each web page.
Overriding: Overriding in CSS means that you are providing any style property to an element for
which you have already provided a style. For example, if you have provided some style to an
element by using the external CSS and after that, you need to change the CSS but if you didn’t find

Developed By. Dr. Munesh Thakre Page 95 of 306


Web Engineering BE CSE SEM-VII

where you have written the code then you can just override the style by using in-line CSS which has
the highest priority.
Order of Priority
inline stylesheet (highest) >><style>….</style>tags >> external style sheet(lowest)
Inline stylesheet: If you are using any Inline stylesheet, then it takes the highest priority, and
therefore, it will override any property defined in <style>…</style> tags or property defined in an
external style sheet file.
Style tag: If you are using any property defined in <style>…</style> tag, it will override the
property defined in any external style sheet file.
External CSS: If you are using any property defined in the external style sheet file then it takes the
lowest priority, and the property defined in this file will be applied only when the above two
properties are not applicable.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of CSS Rules Overriding
</title>
<link rel="stylesheet" href="CSSProg1.css">
</head>
<body>
<h1>This is Heading 1</h1>
<p>This is Paragraph 1</p>
<h1 style="color:green">This is Heading 2</h1>
<p style="color:yellow">This is Paragraph 2</p>
<h1>This is Heading 3</h1>
<p>This is Paragraph 3</p>
</body>
</html>
Output:

Developed By. Dr. Munesh Thakre Page 96 of 306


Web Engineering BE CSE SEM-VII

CSS Comments
It is a common practice to add comments in the code to enhance readability and add helpful notes
alongside the code. Like most languages, CSS allows the users to add comments in the stylesheet.
Comments in CSS can be added by using the /* tag, which is then closed off by using */. This
technique can be used to add both single and multi-line comments.
Single-line comments:
Single-line comments can be added as follows:
/* This is a single line comment */
Users may observe that the // tag can be used to add single line comments. However, this not the
standard practice in CSS and therefore should not be used.
Multi-Line comments:
Multi-line comments can be added using the same /* tag.
/* This is a
Multi-line comment
In CSS */
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of CSS Comments
</title>
<style>
h1{
/*background-color:azure;*/
color:black;
font-size:40px;
}
p{
background-color:lightcoral ;
color:blue;
/*font-size:25px;
font-family:Arial;*/
}
</style>
</head>
<body>
<h1>This is Heading 1</h1>
<p>This is Paragraph 1</p>
<h1>This is Heading 2</h1>
<p>This is Paragraph 2</p>
<h1>This is Heading 3</h1>
<p>This is Paragraph 3</p>

Developed By. Dr. Munesh Thakre Page 97 of 306


Web Engineering BE CSE SEM-VII

</body>
</html>
Output:

Developed By. Dr. Munesh Thakre Page 98 of 306


Web Engineering BE CSE SEM-VII

CSS Text, Colors, and Borders


Measurement Units
Every property like margin, padding, height, width, font size, etc in CSS that has some dimensions or
length needs a unit. CSS provides us with lots of untis, some of whose values are fixed and are called
absolute units while there are others whose values are relative to other values like that of the parent
element or to the default value for that particular HTML element, these are called relative units.
Among the absolute units in CSS, we have centimeter, millimeter, pixel, etc; While among the
relative units in CSS, we have percentage, em, vh, rem, etc.
What is a CSS Unit?
When you talk about the distance between two places like your house and your friend’s house, you
talk in kilometers or meters. Whereas talking about the height of a person we, usually, talk in
centimeters or feet. And similarly often you might talk in relative terms like your new books are
double in thickness compared to your earlier books.
Very similar to real-world units, we have units in CSS for expressing the dimensions of several
properties like margin, padding, length, width etc of an HTML element, like we can set the margin of
an HTML element to a specific value. That value consists of some numeric figures followed by a
unit.
Two Major Types of Units in CSS
1. Absolute
2. Relative
Absolute Units
These units are the ones whose values are fixed irrespective of any other factors like parent element
or viewing window i.e. the screen size won’t affect the size of the element. There are different types
of absolute units:
We shall be applying the different absolute units on the same text to understand the difference better.
The HTML containing the text goes as follows:
Absolute units are : px, pt, pc, cm etc.
CSS px: px stands for Pixel. Pixel can be defined as 1/96th part of an inch.
CSS pt: pt stands for point. 1 CSS pt is defined as 1/72th of an inch.
CSS pc: pc stands for pica or picas. 1 CSS pc is defined as 1/6th of an inch.
CSS cm: This is our good centimeter that we all know.
Example:

Developed By. Dr. Munesh Thakre Page 99 of 306


Web Engineering BE CSE SEM-VII

<!DOCTYPE html>
<html>
<head>
<title>Illustration of Absolute Units</title>
<style>
.absoluteUnits1{
font-size:20px;
}
.absoluteUnits2{
font-size:20pt;
}
.absoluteUnits3{
font-size:3pc;
}
.absoluteUnits4{
font-size:1cm;
}
</style>
</head>
<body>
<div class="absoluteUnits1">
<p>My First Dimensions are Absolute</p>
</div>
<div class="absoluteUnits2">
<p>My Second Dimensions are Absolute</p>
</div>
<div class="absoluteUnits3">
<p>My Third Dimensions are Absolute</p>
</div>
<div class="absoluteUnits4">
<p>My Fourth Dimensions are Absolute</p>
</div>
</body>
</html>
Output:

Developed By. Dr. Munesh Thakre Page 100 of 306


Web Engineering BE CSE SEM-VII

Relative Units
These units are relative to some other length property like the parent elements font size or the size of
the viewport.
In relative units, we talk in terms of the same property, like, if we are talking about the width of an
element in relative units then it is relative to the WIDTH of the parent element/viewport.we shall be
seeing this in the example section in a while.
Relative units, if used correctly, are suitable for making elements scale properly concerning other
things on the same page i.e. to make the element responsive. We shall see this in the example below.
CSS %: This is the percentage unit. The measurement of the element is relative to the dimensions of
the parent. Like if we set the width of an HTML element to be K% then its width is calculated as
follows:
Width of HTML element = (K/100) * width of parent element.
CSS em: em refers to the default size of the property. So precisely, em is equivalent to 100%. This is
mostly used to achieve the same values dynamically as is the case with % but applies specifically to
font size.
CSS rem: This unit counters the adding-up effect of units like % and em, rem rather stands for Root
em. This means the browser will ignore all the adjustments made to the parent elements and will
scale the HTML element, to which the property is applied, based on the root/default value for that
particular element.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Illustration of Relative Units</title>
<style>
.relativeUnits1{
font-size:400%;
}
.relativeUnits2{
font-size:5em;
}
.relativeUnits3{
font-size:4rem;
}
</style>
</head>
<body>
<div class="relativeUnits1">
<p>My First Dimensions are Relative</p>
</div>

Developed By. Dr. Munesh Thakre Page 101 of 306


Web Engineering BE CSE SEM-VII

<div class="relativeUnits2">
<p>My Second Dimensions are Relative</p>
</div>
<div class="relativeUnits3">
<p>My Third Dimensions are Relative</p>
</div>
</body>
</html>

Output:

CSS Colors
CSS Color property is used to set the color of HTML elements. This property is used to set font
color, background color, etc. The color of an element can be defined in the following ways:
1. Built-in Color
2. RGB Format
3. RGBA Format
4. Hexadecimal Notation
5. HSL
6. HSLA
1. Built-in Color
There are a set of predefined colors which are used by its name. For example, red, blue, green, etc.
Syntax:
H1{
color: color-name;
}

Developed By. Dr. Munesh Thakre Page 102 of 306


Web Engineering BE CSE SEM-VII

Example:
H1{
color: red;
}
2. RGB Format
The RGB (Red, Green, Blue) format is used to define the color of an HTML element by
specifying the R, G, and B values range between 0 to 255. For example, the RGB value of
redcolor is (255,0,0), Green color is (0,255,0), Blue color is (0,0,255), etc.
Syntax:
H1{
color: rgb(R,G,B);
}
Example:
H1{
color: rgb(0,153,0);
}
3. RGBA Format
The RGBA format is similar to the RGB, but the difference is RGBA contains A (Alpha) which
specifies the transparency of elements. The value of alpha lies between 0.0 to 1.0. Where 0.0
represents fully transparent and 1.0 represents not transparent.
Syntax:
H1{
Color:rgba(R,G,B,A);
}
Example:
H1{
color:rgba(0,153,0,0.5);
text-align:center;
}
4. Hexadecimal Notation
The hexadecimal notation begins with the # symbol followed by 6 characters each ranging from 0
to F. For example: Red #FF0000, Green #00FF00, Blue #0000FF etc.
Syntax:

Developed By. Dr. Munesh Thakre Page 103 of 306


Web Engineering BE CSE SEM-VII

H1{
Color:#(0-F)(0-F)(0-F)(0-F)(0-F)(0-F);
}
Example:
H1{
Color:#009900;
}
5. HSL
HSL stands for Hue, Saturation and Lightness respectively. This format uses the cylindrical
coordinate system.
 Hue: Hue is the degree of the color wheel. Its value lies between 0 to 360 where 0 represents
red, 120 represents green and 240 represents blue color.
 Saturation: It takes a percentage value, where 100% represents completely saturated, while
0% represents completely unsaturated (gray).
 Lightness: It takes percentage value, where 100% represents white, while 0% represents
black
Syntax:
H1{
Color:hsl(H,S,L);
}
Example:
H1{
Color:hsla(0,153%,10%,0.5);
}
6. HSLA
The HSLA color property is similar to the HSL property, but the difference is HSLA contains A
(Alpha) which specifies the transparency of elements. The value of alpha lies between 0.0 to 1.0
where 0.0 represents fully transparent and 1.0 represents not transparent.
Syntax:
H1{
Color:hsla(H,S,LA);
}
Example:

Developed By. Dr. Munesh Thakre Page 104 of 306


Web Engineering BE CSE SEM-VII

H1{
Color:hsla(0,153%,10%,0.5);
}

CSS Hex Codes


Color codes are ways of representing the colors we see every day in a format that a computer can
interpret and display. Commonly used in websites and other software applications, there are a variety
of formats, including Hex color, RGB and HSL values, and HTML color names, amongst others.
The most popular are Hex color codes; three-byte hexadecimal numbers (meaning they consists of
six digits), with each byte, or pair of characters in the Hex code, representing the intensity of red,
green, and blue in the color respectively.

#xx xx xx
Hex code byte values range from 00, which is the lowest intensity of a color, to FF which represents
the highest intensity. The color white, for example, is made by mixing each of three primary colors at
their full intensity, resulting in the Hex color code of #FFFFFF.

#FFFFFF
Black, the absence of any color on a screen display, is the complete opposite, with each color
displayed at their lowest possible intensity and a Hex color code of #000000.

#000000
Understanding the basics of Hex color code notation, we can create grayscale colors very easily since
they consist of equal intensities of each color:

#454545 #999999
The three primary colors, red, green and blue, are made by mixing the highest intensity of the desired
color with the lowest intensities of the other two:

#FF0000 #00FF00 #0000FF


With modern browsers supporting the full spectrum of 24-bit color, there are 16,777,216 different
color possibilities.

Developed By. Dr. Munesh Thakre Page 105 of 306


Web Engineering BE CSE SEM-VII

CSS Short Hex Codes


Shorthand hex notation abbreviates 6-character RRGGBB CSS colors into 3-character RGB
shorthand. Combined with shorthand properties and grouping, shorthand hexadecimal colors can
shrink style sheets dramatically, often by 50%.
There are five ways to specify colors in CSS; four uses numberic RGB values and one uses named
colors. The two most efficient ways are hexadecimal and named colors. Hexadecimal colors come in
two flavors: RGB triplets and shorthand. So instead of this:
.orange{color:#ff6600;}
Do this:
.orange{color:#f60;}
Hexadecimal values are base – 16, so they are usually shorter than base-10 numbers. To specify 0 to
255 in hex, you’d use 00 of ff, saving a byte for higher colors.
Shorthand Hexadecimal Colors:
Nearly all browsers (version 3 and above, except IE3 Mac) support shorthand hex colors. RGB
triplets can be abbreviated if each of the Red, Green and Blue hex pairs are the same. So, when you
use colors where there are three pairs, you can abbreviate each color channel using one character
instead of two identical characters. So, this:
.dark-yellow{color:#ffcc00;}
Become this:
.dark-yellow{color:#fc0;}
Browsers automatically expand these three character colors into six by replicating the R, G and B
values. This technique saves a few bytes for each color abbreviated with shorthand hex notation.
Named Colors:
In most cases using shorthand hex colors is the most efficient way to specify colos. However, in
some cases named colors are shorter than their hex equivalents. The 16 named colors supported by
the HTML and XHTML specifications are shown below:
Colors Hex Pair Short Hex
Aqua #00ffff #0ff
Black #000000 #000
Blue #0000ff #00f
Fuchsia #ff00ff #f0f
Gray #808080

Developed By. Dr. Munesh Thakre Page 106 of 306


Web Engineering BE CSE SEM-VII

Green #008000
Lime #00ff00 #0f0
Maroon #800000
Navy #000080

RGB Values
Generally, hex colors and rgbcolors are identical – they just use a different numeric system and
syntax (but the colors are the same). RGB is an acronym that stands for Red Green and Blue.
Instead of using six hexadecimal characters as we did for the hex color values, with RGB each
parameter pair defines the intensity and brightness of each color (red, green, and blue), with an
integer number ranging from 0-255 or a percentage ranging from (0% - 100%).
It expresses colors system in terms of the amount of red, green, and blue they are made up of and
uses a human counting system in comparison to hex colors that speak computer language. The
number is a code to represent how dark or bright the color is:
The minimum value of 0 represents that none of the colors is being shown, so it is at its darkest. On
the the other hand, the maximum value of 255 represents the full amount of color and the full
intensity is on display.
RGB Color Syntax:
The general look of an rgb declaration is rgb(red, green,blue).
 The keyword rgb followed by a set of parentheses ().
 Three numeric decimal values separated by commas inside the parentheses (which represent
the three colors).
 And finally, it ends with a semicolon.
Taking again the cyan example, the equivalent rgb code is:
H2{
Color:rgb(0,255,255);
}

Browser Safe Colors


Browser safe colors contains RGB 0, 51, 102, 153, 204, and 205. While looking at these numbers
you must be wondering are these numbers just random values? No, these numbers are multiple of 51
because 51 is 20% of 255.

Developed By. Dr. Munesh Thakre Page 107 of 306


Web Engineering BE CSE SEM-VII

We are living in the 21st century and there are billions of users with mllions of computers platforms.
As a developer, we need to make sure that on all computer platforms, the color should be the same.
We don’t need that if we use other devices then the color of the site will change. So, it is highly
recommended to use browser-safe colors.
Browser-safe colors are a set of 216 colors that are commonly supported by web browsers and
operating systems, and they were selected to ensure that they would display consistently across
different devices and platforms.
While browser-safe colors are not as widely used today as in the past due to advance in technology,
they remain a useful tool for ensuring consistent color display across different platforms, particularly
in situations where color accuracy is critical.

CSS – Background
The CSS background properties are used to define the background effects for elements. There are
lots of properties to design the background. CSS background properties are as follows:
 CSS Background-color Property: The background-color property in CSS is used to specify
the background color of an element.
 CSS Background-image Property: The background-image property is used to set one or
more background images to an element.
 CSS Background-repeat Property: The background-repeat property in CSS is used to
repeat the background image both horizontally and vertically.
 CSS Background-attachment Property: The background attachment property in CSS is
used to specify the kind of attachment of the background image concerning its container.
 CSS Background-positions Property: In CSS body position property is mainly used to set
an image at a certain position.
 CSS Background-origin Property: The background-origin is a property defined in CSS
which helps in adjusting the background image of the webpage.
 CSS Background-clip Property: The background-clip property in CSS is used to define
how to extend the background (color or image) within an element.
 CSS Background-color Property: This property specifies the background color of an
element. A color name can also be given as: “green”, a Hex value as “#5570f0”, and an RGB
as “rgb(25,255,2)”.
Syntax:
Body{

Developed By. Dr. Munesh Thakre Page 108 of 306


Web Engineering BE CSE SEM-VII

Background-color: color-name;
}
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Background Property
</title>
<style>
body{
background-color:aqua;
}
h1{
background-color:blueviolet;
text-align:center;
}
</style>
</head>
<body>
<h1>BCCA Second Year</h1>
</body>
</html>
Output:

Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Background Image
</title>
<style>
body{
background-image:url("Books.jpg");
background-repeat:no-repeat;
background-position:center;
}
h2{
color:red;

Developed By. Dr. Munesh Thakre Page 109 of 306


Web Engineering BE CSE SEM-VII

background-clip:content-box;
}
</style>
</head>
<body>
<h2>This is Demostration Heading</h2>
</body>
</html>

CSS Fonts
The CSS fonts module defines font-related properties and how font resources are loaded. It lets you
define the style of a font, such as its family, size and weight, line height, and the graph variants to
use when multiple are available for a single character.
CSS Font property is used to control the look of texts. By the use of CSS font property you can
change the text size, color, style and more. Here, you will also know how to resize your font using
percentage. These are some important font attributes.
1. CSS Font Color: This property is used to change the color of the text.
2. CSS Font Family: This property is used to change the face of the font.
3. CSS Font Size: This property is used to increase or decrease the size of the font.
4. CSS Font Style: This property is used to make the font bold, italic, or oblique.
5. CSS Font Variant: This property creates a small-caps effect.
6. CSS Font Weight: This property is used to increase or decrease the boldness and lightness of the
font.
CSS Font Color:
CSS font color is a standalone attribute in CSS although it seems that it is a part of CSS fonts. It is
used to change the color of the text. There are three different formats to define a color:
 By a color name.
 By hexadecimal value.
 By RGB.
Example:
H1{color:red;}
H2{color:#9000A1;}
P{color:rgb(0,220,98);}

Developed By. Dr. Munesh Thakre Page 110 of 306


Web Engineering BE CSE SEM-VII

Setting of Font Familty:


This CSS property is used to provide a comma-separated list of font families. It sets the font-face for
the text content of an element. This property can hold multiple font names as a fallback system, i.e. if
one font is unsupported in the browser, then other can be used. The different font-family is used for
making attractive web page. CSS font family can be divided into two types:
1. Generic Family: It includes Serif, Sans-serif, and Monospace.
2. Font Family: It specifies the font family name like Arial, New Times Roman, etc.

F F F
(Arial) (Monotype Corsiva) (Times New Roman)

CSS Font Size:


CSS font size property is used to change the size of the font. These are the possible values that can
be used to set the font size. The font-size property in CSS is used to specify the height and size of the
font. It affects the size of the text of an element. Its default value is medium and can be applied to
every element. The value of this property include xx-small, small, x-small, etc.
Syntax:
font-size: medium |large|x-large|xx-large|xx-small|x-small|small|;
The font size can be relative or absolute.
 Absolute size – It is used to set the text to a definite size. Using absolute size, it is not
possible to change the size of the text in all browsers. It is advantageous when we known the
physical size of the output.
 Relative size – It is used to set the size of the text relative to its neighboring element. With
relative size, it is possible to change the size of the text in browsers.
Font Size Value Description
xx-small Used to display the extremely small text size.
x-small Used to display the extra small text size.
Small Used to display small text size.
medium Used to display medium text size.
Large Used to display large text size.
x-large Used to display extra-large text size.

Developed By. Dr. Munesh Thakre Page 111 of 306


Web Engineering BE CSE SEM-VII

xx-large Used to display extremely large text size.


smaller Used to display comparatively smaller text size.
larger Used to display comparatively larger text size.
size in pixel or % Use to set value in percentage or pixels.
Example:
<p style= “font-size:xx-small;”>
CSS Font Style
CSS Font style property defines what type of font you want to display. It may be italic, oblique, or
normal.
Example:
Body{
Font-size:100%;
}
H2{
Font-style:italic;
}
CSS FontVariant
CSS font variant property specifies how to set the font variant of an element. it may be normal and
small caps.
Example:
P{
Font-variant:small-caps;
}
H3{
Font-variant:normal;
}
CSS Font Weight
CSS font weight property defines the weight of the font and specify that how bold a font is. The
possible values of font weight may be normal, bold, bolder, lighter or number(100,200,… up to 900).
This property is used for setting the thickness and boldness of the font. It is used to define the weight
of the text. The available weight depends on the font family, which is used by the browser.
Syntax:
Font-weight: normal |lighter |bolder |bold |number |initial |unset;

Developed By. Dr. Munesh Thakre Page 112 of 306


Web Engineering BE CSE SEM-VII

Property Values
1. Normal: It is the default font-weight whose numeric value is 400.
2. Lighter: It considers the existing font-weight of the font family and makes the font-weight lighter
compared to the parent element.
3. Bolder: It considers the existing font-weight of the font family and makes the font-weight heavier
compared to the parent element.
4. Bold: As its name implies, it is used to define the bold font-weight, and its numeric value is 700.
5. Number: It is used to set the font-weight based on the specified number. Its range can be between
1 to 1000.
6. Initial: It is used to set the font-weight to its default value.
Example:
P{
Font-weight:bold;
Font-weight:lighter;
Font-weight:400;
}
CSS Font Stretch
The font-stretch property in CSS allows us to select a normal, expanded, or condensed face from the
font’s family. This property sets the text wider or narrower compared to the default width of the font.
It will not work on any font but only works on the font-family that has a width-variant face.
This CSS property only works for the fonts with additional faces like expanded and condensed faces;
otherwise, it will be affectless for the fonts that don’t have condensed or expanded faces.
The nine keyword values for choosing the width of the font face are given below:
Syntax:
Font-stretch: normal | semi-condensed | condensed | extra-condensed | ultra-condensed | semi-
expanded | expanded | extra-expanded | ultra-expanded

CSS Shorthand Property


Shorthand properties allow us to write multiple properties in a single line and in a compact way.
They are useful as they provide clean code and also decrease the LOC (Line of Code). The shorthand
properties we will be covering:
Background
Font

Developed By. Dr. Munesh Thakre Page 113 of 306


Web Engineering BE CSE SEM-VII

Border
Outline
Margin
Padding
List

Background
The CSS Background property is used to set the backgraound on a web page. The background can be
applied to any element like the body, h1, p, div, etc. There are many properties available with a
background such as color, image, position, etc. Some of them are used in the below code.
Background: #000 url(images/bg.png) no-repeat left top;
Example:
<!DOCTYPE html>
<html>
<head>
<title>Illustration of shorthand background</title>
<style>
body{
background:#000 url("Books.jpg") no-repeat center top;
}
</style>
</head>
<body></body>
</html>

Font
The CSS font property is used to apply different fonts to the text on the webpage. The various
attributes that can be set using the font are font family, font size, font weight, etc. Some of them are
used as follows:
Example:
<!DOCTYPE html>
<html>
<head>
<title>Illustration of shorthand font</title>
<style>
h1{
font:italic bold 30px/150% Arial, San-serif;
}
</style>
</head>

Developed By. Dr. Munesh Thakre Page 114 of 306


Web Engineering BE CSE SEM-VII

<body>
<h1>This is Heading Demo</h1>
</body>
</html>

Border
The CSS border property is used to apply a border to different elements of a web page. There are
many attributes of the border like width, style, color, etc.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Illustration of shorthand border</title>
<style>
h1{
border: 1px solid #000;
}
</style>
</head>
<body>
<h1>This is Heading Demo</h1>
</body>
</html>

Outline
The CSS outline property is used to apply an outline to various elements that are present on a web
page.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Illustration of shorthand outline</title>
<style>
h1{
outline: 10px solid #000;
}
</style>
</head>
<body>
<h1>This is Heading Outline Demo</h1>
</body>
</html>

Developed By. Dr. Munesh Thakre Page 115 of 306


Web Engineering BE CSE SEM-VII

Margin
The CSS margin properties are used to create space around elements, outside of any defined borders.
We can define the margin for all 4 sides i.e. top, bottom, left and right.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Illustration of shorthand margin</title>
<style>
h1{
margin: 100px 50px 100px 50px;
}
</style>
</head>
<body>
<h1>This is Heading Margin Demo</h1>
</body>
</html>

Padding
The CSS padding properties are used to generate space around an element’s content, inside of any
defined borders. Padding can also be applied as top, bottom, left and right padding.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Illustration of shorthand padding</title>
<style>
h1{
padding: 100px 50px 100px 50px;
}
</style>
</head>
<body>
<h1>This is Heading Padding Demo</h1>
</body>
</html>

List
There are mainly two types of lists in CSS: 1. Ordered list <ol> 2. Unordered list <ul>. Unordered
lists have bullet points while ordered lists have numbers.
Example:

Developed By. Dr. Munesh Thakre Page 116 of 306


Web Engineering BE CSE SEM-VII

<!DOCTYPE html>
<html>
<head>
<title>Illustration of shorthand list</title>
<style>
li{
list-style: lower-alpha inside;
}
</style>
</head>
<body>
<li>BBA</li>
<li>BCCA</li>
</body>
</html>

CSS TextSetting
The CSS text formatting properties are used to format text, style the text and perform different types
of manipulations like word spacing, alignment, justification, and text transformation.
Syntax:
Selector {
Property-name: /* value */;
}
CSS Text Formatting Properties:
There are the following text formatting properties.
 Text Color: This property is used to set the color of the text and the color can be set by using a
color name like ‘red”, hex value “#ff0000”, or by its RGB value “rgb(255,0,0)”.
 Text-align: This property in CSS is used to specify the horizontal alignment of text in an element
inside a block element or table-cell box.
 Text-align-last: It is used to set tha last line of the paragraph just before the line break. It sets the
alignment of all the last lines occurring in the element in which the text- align-last property is
applied.
 Text-decoration: Text-decoration property is used to “decorate” the content of the text.
 Text-decoration-color: It is used to set the color of the decorations (overlines, underlines, and
line-throughs) over the text.
 Text-decoration-lines: It is used to set the various kinds of text decorations. This may include
many values such as underline, overline, line through, etc.

Developed By. Dr. Munesh Thakre Page 117 of 306


Web Engineering BE CSE SEM-VII

 Text-decoration-style: This property is used to set the text-decoration of the element. it is the
combination of the text-decoration-line and text-decoration-color properties.
 Text-indent: It is used to indent the first line of the paragraph and the size can be in px, cm, pt.
 Text-justify: This property is used to set the text-align to justify. It spreads the words into
complete lines.
 Text-overflow: The property of text formatting specifies that some text has overflow and is
hidden from the view.
 Text-transform: It is used to control the capitalization of the text.
 Text-shadow: It is used to add shadow to the text.
 Letter-spacing: This property is used to specify the space between the characters of the text.
 Line-height: It is used to set the space between the lines.
 Direction: This property is used to set the direction of the text.
 Word-spacing: It is used to specify the space between the words of the line.

Text Color
The color of the text is defined by the CSS color property. The style rules in the following example
will define the default text color for the page.
Body {
Color: #434343;
}
Although the color property seems like it would be a part of the CSS text, it is a standalone property
in CSS. The color property defines the text color of an element.
For instance, the color property specifies in the body selector defines the default text color for the
whole page.
Defining Color Values
Colors in CSS are most often specified in the following formats:
 A color keyword – like “red”, “green”, “blue”, “transparent”, etc.
 A HEX value – like “#ff0000”, “#00ff00”, etc.
 An RGB value – like “rgb(255,0,0)”.
CSS has introduced several other color formats such as HSL, HSLA, and RGBA that also support
alpha transparency.

Developed By. Dr. Munesh Thakre Page 118 of 306


Web Engineering BE CSE SEM-VII

Color Keyword
CSS defines the few color keywords which lets you easily specify color values. These basic color
keywords are aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver,
teal, white, and yellow. The color names are case-insensitive.
H1{
Color:red;
}
Modern web browsers however practically support many more color names than what is defined in
the CSS standard, but to be on the safer side you should use hex color values instead.

Text Direction
The following example demonstrated how to set the direction of a text. Possible values are ltr and rtl.
Example:
<p style= “direction:rtl;”>
This text will be rendered from right to left.
</p>
Text Indent
The following example demonstrates how to indent the first line of a paragraph. Possible values are
% or a number specifying indent space.
Example:
<p style= “text-indent:1cm;”>
This text will have the first line indented by 1 cm and this line remains at its
actual position this is done by CSS text-indent property.
</p>
Text Alignment
The text-align property property is used to control how text is aligned within its containing content
box. The available values are listed below. They work in pretty much the same way as they do in a
regular word processor application.
 Left: Left justifies the text.
 Right: Right-justifies the text.
 Center: Centers the text
 Justify: Makes the text spread out, varying the gaps between the words so that all lines of text
are same width.

Developed By. Dr. Munesh Thakre Page 119 of 306


Web Engineering BE CSE SEM-VII

Example:
<p style= “text-align:right”>
This will be right aligned.
</p>

Decorating the Text


Its also important to note that a ruleset can include more than one decoration at once. For example,
let’s say you wanted to make some changes to the main header to which you attached the #header id.
You can add just one ruleset to your stylesheet.
#header {
}
And then add multiple declaration all in a stack.
#header{
Font-size: 18px;
Font-family: Georgia;
Font-weight:bold;
Text-align:center;
}
Setting of white space between Text
There two types of white spacing.
1. Letter Spacing
2. Word Spacing
1. Letter Spacing
The letter spacing property is used to set the extra spacing between the characters of text. This
property can take a length value in pixels, ems, etc. It may also accept negative values. When
setting letter spacing, a length value indicates spacing in addition to the default inter-character
space. Check out the following example to understand how it works:
H1{
Letter-spacing:-3px;
}
P{
Letter-spacing:10px;
}

Developed By. Dr. Munesh Thakre Page 120 of 306


Web Engineering BE CSE SEM-VII

2. Word Spacing
The word-spacing property is used to specify the additional spacing between the words. This
property can accept a length value in pixel, ems, etc. Negative values are also allowed. Try out the
following example to understand how this property works:
p.normal{
word-spacing:20px;
}
p.justified{
word-spacing:20px;
text-align:justify;
}

Text Cases
The following example demonstrates how to set the cases for a text. Possible values are none,
capitalize, uppercase, and lowercase.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of text cases
</title>
</head>
<body>
<p style="text-transform:capitalize;">This will be capitalized</p>
<p style="text-transform:uppercase;">This will be uppercase</p>
<p style="text-transform:lowercase;">This will be lowercase</p>
</body>
</html>
Output:

Developed By. Dr. Munesh Thakre Page 121 of 306


Web Engineering BE CSE SEM-VII

Text Shadow
You can apply drop shadows to your text using the text-shadow property. This takes up to four
values, as shown in the example below:
text-shadow: 4px 4px 5px red;
The four properties are as follows:
1. The horizontal offset of the shadow from the original text – this can take most available CSS
length and size units, but you’ll most commonly use px; positive values move from the shadow
right, and negative values left. This value has to be included.
2. The vertical offset of the shadow from the original text. This behaves similarly to the horizontal
offset, except that it moves the shadow up/down, not left/right. This value has to be included.
3. The blur radius: a higher value means the shadow is dispersed more widely. If this value is not
included, it defaults to 0, which means no blur. This can take the most available CSS length and
size units.
4. The base color of the shadow, which can take any CSS color unit. If not included, it defaults to
currentcolor, i.e. the shadow’s color is taken from the element’s color property.
Multiple shadows:
You can apply multiple shadows to the same text by including multiple shadow values separated by
commas, for example:
H1{
Text-shadow: 1px 1px 1px red, 2px 2px 1px red;
}
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of text shadow
</title>
<style>
h1{
text-shadow: 1px 1px 1px red, 2px 2px 1px red;
}
</style>
</head>
<body>
<h1>Tommay the cat</h1>
<p>Well I remember it as though it were a mean ago...</p>

Developed By. Dr. Munesh Thakre Page 122 of 306


Web Engineering BE CSE SEM-VII

<p>Said Tommay the Cat as he reeled back to clear whatever foreign matter
may have.
nested the way into his mighty throat.
</p>
</body>
</html>
Output:

CSS Borders
CSS border properties allow us to set the style, color, and width of the border. Different properties
can be set for all the different borders i.e. top border, the right border, the bottom border, and the left
border. The CSS border is a shorthand property used to set the border on an element.
The border properties allow you to specify how the border of the box representing an element should
look. There are three properties of a border you can change.
1. The border-color specifies the color of a border.
2. The border-style specifies whether a border should be a solid, dashed line, double line, or one
other possible values.
3. The border width specifies the width of a border.
The Border Color Property
The border-color property allows you to changing the color of the border surrounding an element.
You can individually change the color of the bottom, left, top, and right sides of the element’s border
using the properties.
 border-bottom-color changes the color of the bottom border.
 border-top-color changes the color of the top border.
 border-left-color changes the color of the left border.
 border-right-color changes the color of the right border.
Example:
<!DOCTYPE html>
<html>

Developed By. Dr. Munesh Thakre Page 123 of 306


Web Engineering BE CSE SEM-VII

<head>
<title>
Illustration of border-color property
</title>
<style>
p.example1{
border:1px solid;
border-bottom-color:#009900;
border-top-color:#FF0000;
border-left-color:#330000;
border-right-color:#0000CC;
}
p.example2{
border: 1px solid;
border-color:#009900;
}
</style>
</head>
<body>
<p class="example1">
This example is showing all borders in different colors.
</p>
<p class="example2">
This example is showing all borders in green color only.
</p>
</body>
</html>
Output:

The Border Style Property


The border-style property allows you to select one of the following styles of the border:
 none – No border. (Equivalent to border-width:0;)
 solid – Border is a single solid line.
 Dotted – A border is a series of dots.
 Dashed – Border is a series of short lines.
 Groove – The border looks as though it is coverd into the page.

Developed By. Dr. Munesh Thakre Page 124 of 306


Web Engineering BE CSE SEM-VII

 Ridge – Border looks the opposite of groove.


 Inset – The border makes the box look like it is embedded in the page.
 Outset – The border makes the box look like it is coming out of the canvas.
 Hidden – Same as none, except in terms of border-conflict resolution for table elements.
You can individually change the style of the bottom, left, top and right borders of an element using
the following properties.
 Border-bottom-style changes the style of the bottom border.
 Border-top-style changes the style of the top border.
 Border-left-style changes the style of the left border.
 Border-right-style changes the style of the right border.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Border style property
</title>
</head>
<body>
<p style="border-width:4px; border-style:none;">
This is border with none with
</p>
<p style="border-width:4px; border-style:solid;">
This is solid border
</p>
<p style="border-width:4px; border-style:dotted;">
This is dotted border
</p>
<p style="border-width:4px; border-style:dashed;">
This is dashed border
</p>
<p style="border-width:4px; border-style:groove;">
This is groove border
</p>
<p style="border-width:4px; border-style:ridge;">
This is ridge border
</p>
<p style="border-width:4px; border-style:inset;">
This is inset border
</p>
<p style="border-width:4px; border-style:outset;">
This is outset border
</p>
<p style="border-width:4px; border-style:hidden;">

Developed By. Dr. Munesh Thakre Page 125 of 306


Web Engineering BE CSE SEM-VII

This is hidden border


</p>
<p style="border-width:4px;
border-top-style:solid;
border-bottom-style:dashed;
border-left-style:groove;
border-right-style:double;">
This is all different border
</p>
</body>
</html>

Output:

The Border Width Property


The border width property allows you to set the width of an elements border. The value of this
property could be either a length in px, pt, or cm or it should be set the thin, medium, or thick.
You can individually change the width or the bottom, top, left and right borders of an element using
the following properties.
 Border-bottom-width changes the width of the bottom border.
 Border-top-width changes the width of the top border.
 Border-left-width changes the width of the left border.
 Border-right-width changes the width of the right border.

Developed By. Dr. Munesh Thakre Page 126 of 306


Web Engineering BE CSE SEM-VII

Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of border width property
</title>
</head>
<body>
<p style="border-width:4px; border-style:solid">
This is solid border whose width is 4px
</p>
<p style="border-width:4pt; border-style:solid">
This is solid border whose width is 4pt
</p>
<p style="border-width:thin; border-style:solid">
This is solid border whose width is thin
</p>
<p style="border-width:medium; border-style:solid">
This is solid border whose width is medium
</p>
<p style="border-width:thick; border-style:solid">
This is solid border whose width is thick
</p>
<p style="border-bottom-width:8px; border-top-width:10px;
border-left-width:2px; border-right-width:15px;
border-style:solid">
This is a border with four different width
</p>
</body>
</html>

Output:

Developed By. Dr. Munesh Thakre Page 127 of 306


Web Engineering BE CSE SEM-VII

Border Properties using Shorthand


The border property allows you to specify the color, style, and width of lines in one property.
The following example shows how to use all three properties in a single property. This is the most
frequently used property to set a border around any element.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Illustration of Border Property using Shorthand
</title>
</head>
<body>
<p style="border:4px solid red">
This example is showing shorthand property for border.
</p>
</body>
</html>

Output:

Developed By. Dr. Munesh Thakre Page 128 of 306


Web Engineering BE CSE SEM-VII

Unit – II
JAVA SCRIPT BASICS
Introduction
A program composed of commands from a particular language is referred to as a script. Script adds
life to the web page or intranet application. JavaScript was initially created to make webpage alive. It
can make a static page and interactive user and data aware page.
JavaScript is an interpreted scripting language. An interpreted language is a type of programming
language that executes its instructions directly and freely without compiling machine language
instructions in precious program.
What is JavaScript
JavaScript is object-based scripting language and it is light weighted. It was first implemented by
Netscape (with help from Sun Microsystems). JavaScript was created by Brendan Eich at Netscape
in 1995 for the purpose of allowing code in web-pages (performing logical operations on client side).
JavaScript is most commonly used as a client side scripting language. This means that JavaScript
code is written into an HTML page. When a user reqqquts an HTML page with JavaScript in it, the
script is sent to the browser and it’s up to the browser to do something with it.
JavaScript is not compiled but translated, JavaScript Translator is responsible to translate the
JavaScript code which is embedded in browser. It is supported by major browsers including NN, IE,
AOL, MOZILLA, and Opera.
Originally the JavaScript language was called Live Script, but when it was about to be released Java
had become immensely popular. At the last possible moment Netscape changed the name of its
scripting language to “JavaScript”.

Features of JavaScript
1. Light Weight: JavaScript is a lightweight scripting language because it is made for data
handling at the browser level only. Since it is not a general purpose language so it has a limited
set of libraries.
2. Achieves dynamic effects in web page: Using this feature available in JavaScript, the
designer can deciede to have dynamically placed text at run time.
3. React to events: A JavaScript can be set to execute when something happens, like when a
page has finished loading or when a user clicks on an HTML element.

Developed By. Dr. Munesh Thakre Page 129 of 306


Web Engineering BE CSE SEM-VII

4. Validate Data: A JavaScript can be used to validate form data before it is submitted to a
server. This saves the server from extra processing.
5. Object-Based Language: JavaScript is an object-based scripting language that provides built-
in objects like String, Math, Date, etc.
6. Saves Time: JavaScript also has the feature of validating data submitted at the client level.
This helps in saving the processing time of server because JavaScript initially creates the
validation on client side.
7. DOM: Client side JavaScript is embedded inside HTML. This embedded JavaScript is used
along with DOM (Document Object Model) for control over the browser by means of objects.
8. Interpreted Language: JavaScript is an interpreted language, meaning that it can be used or
execute with ease without pre-compilation.
9. Visual JavaScript: Visual JavaScript is a component-based visual development tool for the
Netscape Open Network Environment used by programmers who want to build cross-platform
web-based applications.
10. Create new functions: An important part of JavaScript is the ability to create new functions
within scripts. Declare a function in JavaScript using function keyword.
11. Platform Independent: JavaScript is platform independent scripting language. Any
JavaScript-enabled browser can understand and interpreted JavaScript code. Due to different
features, JavaScript is known as universal client side scripting language.

Difference in Client and Server Side Scripting


Clinet Side Script
Client side script generally occurs on the client computer (executed by web browser). Client-side
script is embedded in an HTML page. One of the most useful applications of client-side scripting is
for data entry validation such as checking values, ranges, dates etc.
Server Side Script
Server side script is interpreted by web server. It is an instruction set that is processed by the server
and generates HTML. The resulting HTML is sent as part of the HTTP response to the browser.
Following are some points which differentiate between Client Side Script and Server Side Script.
1. A client-side script is executed by the client (i.e. web browser) whereas web server processes
server-side script.

Developed By. Dr. Munesh Thakre Page 130 of 306


Web Engineering BE CSE SEM-VII

2. Generally client-side scripting is used for data entry validation such as checking values, ranges,
dates etc., whereas server-side scripting is used for heavy-duty processing at server such as
saving data to the database, accessing, modifying and deleting data from the database.
3. The client-side scripting language involves languages such as HTML5, JavaScript etc. In
contrast, programming languages such as PHP, ASP.net, Ruby, ColdFusion, Python, C# etc. are
server side scripting languages.
4. Server-side scripting is useful in customizing the web pages and implements the dynamic
changes in the websites. Conversely, the client-side scripts are generally used for validation
purpose and effectively minimize the load to the server.
5. Special software (web server) is required to execute server-side script, whereas client side scripts
requires web browser as an interface.
6. Client-side script and server-side scripts cannot interact with one another. The client-side scripts
are executed on the client, after the server-side scripts have finished processing completely.

History of JavaScript
 In 1993, Mosaic, the first popular web browser, came into existence.
 In 1994, Netscape was founded by Marc Adnreeseen. He realized that the web needed to
become more dynamic. Thus, a ‘glue language’ was belived to be provided to HTML to
make web designing easy for designers and part-time programmers.
 Consequently, in 1995, the company recruited Brendam Eich intending to implement and
embed Scheme programming language into the browser.
 But, before Brendan could start, the company merged with Sun Microsystems for adding Java
into its Navigator so that it could compete with Microsoft over web technologies and
platforms.
 Now, two languages were there: Java and the scripting language. Further, Netscape decided
to give a similar name to the scripting language as Java. It led to ‘JavaScript’.
 Finally, in May 1995, Marc Andreessen coined the first code of JavaScript named ‘Mocha’.
 Later, the marketing team replaced the name with ‘LiveScript’.
 But, due to trademark reasons and certain other reasons, in December 1995, the language was
finally renamed to ‘JavaScript’. From them, JavaScript came into existence.

Application of JavaScript
JavaScript is used to create interactive website. It is maily used for:

Developed By. Dr. Munesh Thakre Page 131 of 306


Web Engineering BE CSE SEM-VII

 Web Development
 Web Applications
 Server Application
 Games
 Smartwatches
 Art
 Machine Learning
 Mobile Appilcations

 Web Development
Adding interactivity and behavior to static sites JavaScript was invented to do this in 1995. By
using AngularJS that can be achieved so easily.
 Web Applications
With technology, browsers have improved to the extent that a language was required to create
robust web applications. When we explore a map in Google Maps then we only need to click
and drag the mouse. All detailed view is just a click away, and this is possible only because of
JavaScript. It uses Application Programming Interfaces (API) that provide extra power to the
code. The Electron and React are helpful in this department.
 Server Application
With the help of NodeJs, JavaScript made its way from client to server and NodeJs is the most
powerful on the server side.
 Games
Not only in websites, but JavaScript also helps in creating games for leisure. The combination of
JavaScript and HTML5 makes JavaScript popular in game development as well. It provides the
EaseJS library which provides solutions for working with rich graphics.
 Smartwatches
JavaScript is being used in all possible devices and applications. It provides a library PebbleJS
which is used in smartwatch applications. This framework works for applications that require the
Internet for their functioning.
 Art
Artists and designers can create whatever they want using JavaScript to draw on HTML5
canvas, and make the sound more effective also can be used P5JS library.
 Machine Learning

Developed By. Dr. Munesh Thakre Page 132 of 306


Web Engineering BE CSE SEM-VII

This JavaScript ml5JS library can be used in web development by using machine learning.
 Mobile Appilcations
JavaScript can also be used to build an application for non-web contexts. The features and uses
of JavaScript make it a powerful tool for creating mobile applications. This is a Framework for
building web and mobile apps using JavaScript. Using React Native, we can build mobile
applications for different operating systems. We do not requied to write code for different
systems. Write once use it anywhere!

Limitation of JavaScript
 Security risks
 Performance
 Complexity
 Weak error handling and type checking facilities
 Security risks
JavaScript can be used to fetch data using AJAX or by manipulating tags that load data such as
<img>, <object>, <script>. These attacks are called cross-site script attacks. They inject JS that
is not part of the site into the visitor’s browser thus fetching the details.
 Performance
JavaScript does not provide the same level of performance as offered by many tranditional
languages as a complex program written in JavaScript would be comparatively slow. But as
JavaScript is used to perform simple tasks in a browser, so performance is not considered a big
restriction in its use.
 Complexity
To master a scripting language, programmers must have a thorough knowledge of all the
programming concepts, core languages objects, and client and server side objects otherwise it
would be difficult for them to write advanced scripts using JavaScript.
 Weak error handling and type checking facilities
It is a weakly typed language as there is no need to specify the data type of the variable. So
wrong type checking is not performed by compile.

Internal Vs. External Scripts


JavaScript provides 3 places to put the JavaScript code:
 Inline JavaScript: Between the <body></body> tag of html.

Developed By. Dr. Munesh Thakre Page 133 of 306


Web Engineering BE CSE SEM-VII

 Internal JavaScript: Between the <head></head> tag of html.


 External JavaScript: in the .js file.
Inline JavaScript
When a script tag is used in the HTML file, it is called inlining. This means no external JS file is
used instead JavaScript is put into an HTML file.
When JavaScript was written within the html element using attributes related to events of the
element then it is called inline JavaScript.
Benefits of Inline JavaScript
This is extremely advantageous as it can save the web browser round trips to the server. This is
because it no longer requires an external file to download from the server side.
Inline scripts are often seen in places such as Google Analytics tracking code, site verification, and
introducing and setting proprietary and external scripting criteria for Webmaster Tools.
Example of Inline JavaScript:
<html>
<form>
<input type= “button” value= “Click” onClick= “alert(‘Button Clicked’)”/>
</form>
</html>
Using inline JavaScript is a bad practice and is not recommended.

Internal JavaScript
Internal JavaScript code is a code that’s placed anywhere within the web page between the HTML
tags. Many web developers choose to place their JavaScript code before the tag. We can add
JavaScript directly to out HTML file by writing the code inside the <script> tag. The <script> tag
can either be placed inside the <head> or the <body> tag according to the requirement.
When JavaScript was written within the section using an element then it is called internal JavaScript.
Example:
<!doctype html>
<html lang= “en”>
<head>
<title>
Basic Example to Internal JavaScript
</title>

Developed By. Dr. Munesh Thakre Page 134 of 306


Web Engineering BE CSE SEM-VII

</head>
<body>
<!.. JavaScript code can be embedded inside head section or body section ..>
<script>
document.write(“Welcome to JavaScript”);
</script>
</body>
</html>
Advantages of Internal JavaScript
If the number of lines of JavaScript is relatively small, a web page with internal JavaScript loads
faster than pages that must reference external code. This is because, as the web browser loads the
page and encounters the reference to the external code, it must make a separate request to the web
server to fetch the code.

External JavaScript
We can create external JavaScript files and embed them in any html page. It provides code re-
usability because a single JavaScript file can be used in several html pages. An external JavaScript
file must be saved by the .js extension. It is recommended to embed all JavaScript files into a single
file. It increases the speed of the webpage.
Message.js
function msg() {
alert(“Hello JavaScript”);
}
Let’s include the JavaScript file in an html page. It calls the JavaScript function on button click.
Prog069.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="message.js"></script>
<title>Illustration of External JavaScript</title>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="Click" onclick="msg()">

Developed By. Dr. Munesh Thakre Page 135 of 306


Web Engineering BE CSE SEM-VII

</form>
</body>
</html>

Advantages of External JavaScript


1. It helps in the reusability of code in more than one HTML file.
2. It allows easy code readability.
3. It is time-efficient as web browsers cache the external js files, which further reduces the page
loading time.
4. It enables both web designers and coders to work with html and js files parallelly and separately,
i.e. without facing any code conflicts.
5. The length of the code reduces as only we need to specify the location of the js file.

Disadvantages of External JavaScript


1. The stealer may download the coder’s code using the url of the js file.
2. If two js files are dependent on one another, then a failure in one file may affects the execution of
the other dependent file.
3. The web browser needs to make an additional http request to get the js code.
4. A tiny to a large change in the js code may cause unexpected results in all its dependent files.
5. We need to check each file that depends on the commonly created external JavaScript file.
6. If it is a few lines of code, then better to implement the internal JavaScript code.

Understand the JavaScript Language


JavaScript was created over 26 years ago and is currently one of the most popular programming
languages.
JavaScript is used with HTML and CSS to create dynamic and interactive web pages and mobile
applications. We often call it one of the building blocks of web development.
According to W3Techs, JavaScript is used as a client-side programming language by 97.6% of all
the websites.
Is Java the same as JavaScript?
Even though these two languages have similar syntax and share the first four letters of ‘Java’, they
are not the same language. Here are some key differences between the two languages.

Developed By. Dr. Munesh Thakre Page 136 of 306


Web Engineering BE CSE SEM-VII

 Java is compiled programming language. That means before the program is run, the code
needs to be translated into machine code so the computer can understand it.
 JavaScript is an interpreted language. In the browser, an interpreter will read the code and run
it without needing to compile it first.
 Java is used as a server-side (backend) language whereas JavaScript is primarily used as a
client-side(frontend) language. But JavaScript can also be used to create backend web
applications with Node.js.
How do HTML, CSS and JavaScript work together on the web page?
Now that we have learned the history of JavaScript, we need to understand how it works on a
website. HTML renders the content, CSS style the page to make it look good, and JavaScript makes
the site interactive.
How do You Add JavaScript to a Website?
Adding JavaScript code to a web page is a pretty simple process (and a familiar one if you’ve done
any coding with HTML and CSS). JavaScript can be added directly to a page’s code using <script>
tags and giving them type attribute text/JavaScript. Honestly, JavaScript looks very similar to adding
CSS to a site. Here’s a side-by-side comparison:
CSS:
<style>
CSS goes here
</style>
JavaScript:
<script type= “text/JavaScript”>
JavaScript code goes here
</script>

The Document Object Model


The Document Object Model (DOM) is a programming interface for HTML and XML (Extensible
Markup Language) documents. It defines the logical structure of documents and way a document is
accessed and manipulated.
DOM is way to represent the webpage in a structured hierarchical way so that it will become easier
for programmers and users to glide through the document. With DOM, we can easily access and
manipulate tags, IDs, classes, attributes, or elements of HTML using commands or methods provided
by the Dcoument object. Using DOM, JavaScript gets access to HTML as well as CSS of the web

Developed By. Dr. Munesh Thakre Page 137 of 306


Web Engineering BE CSE SEM-VII

page and also add behavior to the HTML elements. So, basically, Document Object Model is an API
(Application Programming Ineterface) that represents and interacts with HTML or XML documents.
Why DOM is required?
HTML is used to structure the web pages and JavaScript is used to add behavior to our web pages.
When an HTML file is loaded into the browser, the JavaScript cannot understand the HTML
document directly. So, a corresponding document is created (DOM). DOM is the representation of
the same HTML document but in a different format with the use of objects. JavaScript interprets
DOM easily i.e. JavaScript cannot understand the tags(<h1>H</h1>) in HTML document but can
understand object h1 in DOM. Now, JavaScript can access each of the object (h1, p, etc) by using
different functions.
Structure of DOM
DOM can be thought of as a Tree or Forest (more than one tree). The term structure model is
sometimes used to describe the tree-like representation of a document. Each branch of the tree ends
in a node, and each node contains object. Event lilsteners can be added to nodes and triggered on an
occurrence of a given event. One important property of DOM structure models is structural
isomorphism: if any two DOM implementations are used to create a representation of the same
document, they will create the same structure model, with precisely the same object and
relationships.
Why called an Object Model?
Docuements are modeled using objects and the model includes not only the structure of a document
but also the behavior of a document and the objects of which it is composed like tag elements with
attributes in HTML.
Properties of DOM
Let’s see the properties of the document object that can be accessed and modified by the document
object.
 Window Objects
A Window Object is an object of the browser that is always at the top of the hierarchy. It is like
an API that is used to set and access all the properties and methods of the browser. It is
automatically created by the browser.
 Document Object
When an HTML document is loaded into a window, it becomes a document object. The
‘document’ object has various properties that refer to other objects which allow access to and
modification of the content of the web page. If there is a need to access any element in an

Developed By. Dr. Munesh Thakre Page 138 of 306


Web Engineering BE CSE SEM-VII

HTML page, we always start with accessing the ‘document’ object. Document object is property
of window object.
 Form Object
It is represented by form tags.
 Link Object
It is represented by link tags.
 Anchor Object
It is represented by a href tag.
 Form Control Elements
Form can have many control elements such as text fields, buttons, radio buttons, checkboxes,
etc.
Methods of Document Object
 write(“string”): Writes the given string on the document.
 getElementById(): returns the element having the given id value.
 getElementByName(): returns all the elements having the given name value.
 getElementBytagName(): returns all the elements having the given tag name.
 getElementByClassName(): returns all the elements having the given class name.

Variable Declaration
In JavaScript, we can declare a variable in different ways by using different keywords. Each
keyword holds some specific reason or feature in JavaScript. We can declare variable in three
different ways by using var, let and const keywords. variables Each keyword is used in some specific
conditions.
JavaScript var JavaScript let JavaScript const
Can be redeclared Cannot be redeclared Cannot be redeclared
Can be reassigned a value Can be reassigned a value Cannot be reassign the value
Only have global and function Can have a block scope Can have a block scope
scope
Variables are hosted on top and Variables must be initialized Variables must be initialized
can be used anywhere before use before use
Can be redeclared anywhere in Can be redeclared inside a Can never be redeclared
the program. block

Developed By. Dr. Munesh Thakre Page 139 of 306


Web Engineering BE CSE SEM-VII

JavaScript var:
This keyword is used to declare variables globally. If you used this keyword to declare a variable
then the variable can be accessed globally and changeable also. It is good for a short length of codes.
If the codes get huge then you will get confused.
Syntax: var variableName = “Variable-Value”;
Example: var sname = “JavaScript”;
Console.log(sname);
Output: JavaScript

JavaScript let:
This keyword is used to declare variables locally. If you used this keyword to declare a variable then
the variable can accessible locally and it is changeable as well. It is good if the code gets huge.
Syntax: let variableName = “Variable-Value”;
Example: if(true) {
Let sname = “JavaScript”;
Console.log(sname);
}
/* This will be an error and show geeks in not defined */
Console.log(geeks);
Output: JavaScript

JavaScript const:
This keyword is used to declare variables locally. If you use this keyword to declare a variable then
the variable will only be accessible within that block similar to the variable defined by using let and
the difference between let and const is that the variables declare using const values can’t be
reassigned. So we should assign the value while declaring the variable.
Syntax: const variableName = “Variable-Value”;
Example: const sname = “JavaScript”;
Console.log(sname);
Output: JavaScript

Developed By. Dr. Munesh Thakre Page 140 of 306


Web Engineering BE CSE SEM-VII

Operators
JavaScript Operators operate the operands, these are symbols that are used to manipulate a certain
value or operand. Operators are used to performing specific mathematical and logical computations
on operands. In other words, we can say that an operator operates the operands. In JavaScript,
operators are used to compare values, perform arithmetic operations, etc.
Types of Operators
There are various operators supported by JavaScript.
 JS Arithmetic Operators
 JS Assignment Operators
 JS Comparison Operators
 JS Logical Operators
 JS Ternary Operators
 JS Bitwise Operators
 JS typeof Operators

JS Arithmetic Operators
There are the operators that operate upon the numerical values and return a numerical values.
1. Addition (+)
Addition ‘+’ operator perform addition on two operands. This ‘+’ operator can also be used to
concatenate (add) strings.
Y = 5 + 5 gives Y = 10
Y = “JavaScript” + “for” + “BCCA” gives Y = “JavaScriptforBCCA”
Y = “BCCA” + 4 + “II” gives Y = “BCCA4II”
2. Subtraction (-)
Subtraction ‘-‘ operator performs subtraction on two operands.
Y = 5 – 3 gives Y = 2
3. Multiplication (*)
The multiplication ‘*’ operator performs multiplication on two operands.
Y = 5 * 5 gives Y = 25
4. Division (/)

Developed By. Dr. Munesh Thakre Page 141 of 306


Web Engineering BE CSE SEM-VII

The division ‘/’ operator performs division on two operands (divide the numerator by the
denominator)
Y = 5/5 gives Y = 1
5. Modulus (%)
Modulus ‘%’ operator gives a remainder of an integer division.
Y = 5%4 gives Y=1
6. Exponentiation (**)
Exponentiation ‘**’ operator gives the power of the first operand raised to the second operand.
Y = 5**3 gives Y = 125
7. Increment (++):
Increment ‘++’ operator increases an integer value by one.
Let A = 10 and Y = A++ then A = 11, Y = 10
If A = 10 and Y = ++A then A=11, Y=11
8. Decrement (--):
The decrement ‘—‘ operator descreases an integer value by one.
Let A = 10 and Y = A-- then A = 9, Y = 10
If A = 10 and Y = --A then A=9, Y=9
9. Unary (+):
Unary ‘+’ is the fastest and preferred way of converting something into a number.
+a means a is a positive number.
10. Negation (-):
The negation ‘-‘ operator gives the negation of an operand.
-a means a is a negative number.

JS Assignment Operators
The assignment operation evaluates the assigned value. Chaining the assignment operator is possible
to assign a signle value to multiple variables.
Operator Meaning Example
Assignment(=) This operator assigns the right operand valued to If a=10 and y = a then
the left operand. y=10
Addition Sums up left and right operand values and then y+= 5 it means y= y+5
Assignment(+=) assigns the result to the left operand.
Subtraction It subtracts the right side value from the left side y-=5 it means y= y-5

Developed By. Dr. Munesh Thakre Page 142 of 306


Web Engineering BE CSE SEM-VII

Assignment(-=) value and then assigns the result to the left


operand.
Multiplication It multiplies a variable by the value of the right Y*=5 it means y=y*5
Assignment(*=) operand and assigns the result to the variable.
Division It divides a variable by the value of the right y/=5 it means y=y/5
Assignment(/=) operand and assigns the result to the variable.
Modules/Remainder It divides a variable by the value of the right y%=5 it means y=y%5
Assignment(%=) operand and assigns the remainder to the variable.
Exponentiation This raise the value of a variable to the power of y**=5 it means y=y**5
Assignment(**=) the right operand.
Left Shift It moves the specified number of bits to the left y<<=4 it means
Assignment(<<=) and assigns the result to the variable. y=y<<4
Right Shift It moves the specified number of bits to the right y>>=3 it means
Assignment(>>=) and assigns the result to the variable. y=y>>3
Bitwise AND It does a bitwise AND operation on the operand y&=5 it means
Assignment(&=) and assigns the result to the variable. y=y & 5
Bitwise OR It does a bitwise OR operation on the operand and y|=6 it means
Assignment(|=) assigns the result to the variable. y=y | 6
Bitwise XOR It does a bitwise XOR operation on the operand y^=7 it means
Assignment (^=) and assigns the result to the variable. y=y^7

JS Comparison and Conditional Operators


Comparison operators are mainly used to perform the logical operations that determine the equality
or difference between the values.
Operators Meaning Example
Equality (= =) Compares the equality of two operands. If equal then the y=5 and x=6
condition is true otherwise false. y==x is false.
Strict Equality Compares the equality of two operands. If equal then the y=5 and x=’5’
(= = =) condition is true otherwise false. y= = =x is false.
Inequality (!=) Compare the inequality of two operands with type. If both Let x=10 then x
value and type are equal than the condition is true otherwise != 11 is true.
false.
Strict Inequality Compares inequality of two operands. True if operands are Let x=10 then x

Developed By. Dr. Munesh Thakre Page 143 of 306


Web Engineering BE CSE SEM-VII

(!==) not equal. !== 11 is true.


Greater than (>) This operator checks whether the left side value is greater Let x=10 then
than the right side value. If yes then it returns true otherwise x>11 is false.
it returns false.
Less than (<) This operator checks whether the left side value is less than Let x=10 then
the right side value. If yes then it returns true otherwise it x<11 is true.
returns false.
Greater than or This operator checks whether the left side operand is greater Let x=10 then
equal to (>=) than or equal to the right side operand. If yes then it returns x>=11 is false.
true otherwise it returns false.
Less than or This operator checks whether the left side operand value is Let x=10 then
equal to(<=) less than or equal to the right side operand value. If yes then x<=10 is true.
it returns true otherwise it returns false.

JS Logical Operators
These operators are used to determine the logic between variables or values.
Operators Meaning Example
Logical AND It checks whether two operands are non-zero (0, false, Y=5 and X=6
(&&) undefined, null or infinity are considered as zero), if yes then Y && X is 6
return the last operand when evaluating from left to right.
Logical OR It checks whether two operands are non-zero (0, false, Y = 5 and X = 0
(||) undefined, null or infinity is considered as zero), if yes then Y || X is 5
return the first operand when evaluating from left to right.
Logical NOT It reverses the Boolean result of the operand (or condition). Y = 5 and X = 0
(!) !(Y || X) is false.

JS Ternary Operators
The ternary operator has three operands. It is the simplified operator of if/else.
Ternary Operator (? :) : It is like the short form of the if-else condition.
Y ==10?A:B;

JS Bitwise Operators

Developed By. Dr. Munesh Thakre Page 144 of 306


Web Engineering BE CSE SEM-VII

Bitwise operators treat its operands as a set of 32-bit binary digits (zeros and ones) and perform
actions. However, the result is shown as a decimal value.
Operator Meaning Example
Bitwise AND & Bitwise AND & returns 1 if the corresponding bits X & Y
of both operands are 1 else it returns 0.
Bitwise OR | Bitwise OR | return 0 if the corresponding bits of X | Y
both operands are 0 else return 1.
Bitwise XOR ^ Bitwise XOR ^ return 0 if one operand is 1 and X ^ Y
another operand is 0 otherwise return 0.
Bitwise NOT ~ Bitwise NOT ~ return 1 if the operand is false ~X
otherwise return 0.
Bitwise Left Shift Shift bits left and set number of 0’s in right. X << 2
<<
Bitwise Right Shift bits right and set number of 0’s in left. X >> 2
Shift >>
Bitwise Right Shift bits right and set number of 0’s in left with X >>> 2
Shift with 0 fill zero fill.

JS typeof Operators
It returns the data type of its operand in the form of a string. The operand can be any object, function
or variable.
JavaScript typeof:
It returns the operand type, the possible types that exist in JavaScript are
typeof variable;
Example:
let a = 17;
let b = “abc”;
let c = “”;
let d = null;
document.write(“Type of a = “ + typeof(a));
document.write(“Type of b = “ + typeof(b));
document.write(“Type of c = “ + typeof(c));
document.write(“Type of d = “ + typeof(d));

Developed By. Dr. Munesh Thakre Page 145 of 306


Web Engineering BE CSE SEM-VII

document.write(“Type of e = “ + typeof(e));

Output:
Type of a = number
Type of b = string
Type of c = string
Type of d = object
Type of e = undefined

Looping Control Statement


JavaScript Loops are used to execute the same block of code a specified number of times or while a
specified conditions is true. Very often when we write code, we want the same block of code to run
over and over again in a row. Instead of adding several almost equal lines in the script, we can use
loops to perform a repetitive task like this. In JavaScript there are three different kinds of loops.
 for loop: Loops through a block of code a specified number of times.
 while loop: Loops through a block of code while a specified condition is true.
 do-while loop: A variant of the while loop which will always be executed at least once, even
if the condition is false because the code is executed before the condition is tested.
The for Loop
The for loop is used when we know in advance how many times the script should run. The for loop is
the most compact form of looping and includes the following three important parts:
 The loop initialization is where we initialize our counter to a starting value. The initialization
statement is executed before the loop begins.
 The test statement (condition) will test if the given condition is true or not. If the conditions
is true then the code given inside the loop will be exeuctued otherwise the loop will come out.
 The iteration statement is where you can increase or decrease your counter.
Syntax:
for(var=startvalue; var<=endvalue; var=var+increment)
{
Code to executed
}
Example:

Developed By. Dr. Munesh Thakre Page 146 of 306


Web Engineering BE CSE SEM-VII

The example below defines a loop that starts with i=1. The loop will continue to run as long as I is
less than, or equal to 5. I will increase by 1 each time the loop runs.
<!DOCTYPE html>
<html lang= "en">
<head>
<title>
Illustration of for loop
</title>
</head>
<body>
<script type="text/javascript">
var i;
for(i=1;i<=5;i++)
{
document.write("<br>The Number is :" + i);
}
</script>
</body>
</html>

Output:
The Number is :1
The Number is :2
The Number is :3
The Number is :4
The Number is :5

The while Loop:


The while loop is used when we want the loop to execute and continue executing while the specified
condition is true. The purpose of a while loop is to execute a statement or code block repeatedly as
long as the expression is true. Once the expression becomes false, the loop will be exited.
Syntax
while(expression)
{
Statement(s) to be executed if the expression is true
}

Developed By. Dr. Munesh Thakre Page 147 of 306


Web Engineering BE CSE SEM-VII

Example:
The example is the same as above

<!DOCTYPE html>
<html lang= "en">
<head>
<title>
Illustration of while loop
</title>
</head>
<body>
<script type="text/javascript">
var i=1;
while(i<=5)
{
document.write("<br>The Number is :" + i);
i++;
}
</script>
</body>
</html>

Output:
The Number is :1
The Number is :2
The Number is :3
The Number is :4
The Number is :5

Developed By. Dr. Munesh Thakre Page 148 of 306


Web Engineering BE CSE SEM-VII

The do…while Loop


The do…while loop is a variant of the while loop. This loop will always execute a block of code at
least once, and then it will repeat the loop as long as the specified condition is true. This loop will
always be executed at least once, even if the condition is false because the code is executed before
the condition is tested.
The do…while loop is similar to the while loop except that the condition check happens at the end of
the loop. This means that the loop will always be executed at least once, even if the condition is
false.
Syntax:
do{
Code to be executed
}while(expression);
Example:

<!DOCTYPE html>
<html lang= "en">
<head>
<title> Illustration of while loop </title>
</head>
<body>
<script type="text/javascript">
var i=5;
do
{
i++;
}while(i<5);
document.write("<br>The Number is :" + i);
</script>
</body>
</html>
Output:
The Number is : 6

Developed By. Dr. Munesh Thakre Page 149 of 306


Web Engineering BE CSE SEM-VII

Conditional Statement
While writing a program, there may be a situation when you need to adopt one out of given set of
paths. In such cases, you need to use conditional statements that allow your program to make correct
decisions and perform right actions.
Conditional statements are used to decide the flow of execution based on different conditions. If a
condition is true, you can perform one action and if the condition is false, you can perform another
action.
JavaScript supports the following forms of if…else statements:
 if statement
 if…else statement
 if…else if statement
if statement:
The if statement is the fundamental control statement that allows JavaScript to make decisions and
execute statements conditionally.
Syntax:
if(expression)
{
Statement(s) to be executed if the expression is true.
}
Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s) are
executed. If the expression is false, then no statement would be not executed. Most of the time, you
will use comparison operators while making decisions.
Example:

if …else statement
The if…else statement is the next form of control statement that allows JavaScript to execute
statements in a more controlled way.
Syntax:
if(expression){
Statement(s) to be executed if the expression is true.
}
else {
Statement(s) to be executed if the expression is false. }

Developed By. Dr. Munesh Thakre Page 150 of 306


Web Engineering BE CSE SEM-VII

Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in the
‘if’ block, are executed. If the expression is false, then the given statement(s) in the else block is
executed.
Example:

if…else if statement
The if…else if statement is an advanced form of if…else that allows JavaScript to make a correct
decision out of several conditions.
Syntax:
if (expression 1){
Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
Statement(s) to be executed if expression 3 is true
} else {
Statement(s) to be executed if no expression is true
}
It is just a series of if statements, where each if is a part of the else clause of the previous statement.
Statement(s) are executed based on the true condition, if none of the conditions is true, then the else
block is executed.
Example:

Switch Statement
You should use the switch statement if you want to select one of many blocks of code to be executed.
The switch statement is a part of JavaScript's "Conditional" Statements, which are used to perform
different actions based on different conditions. Use switch to select one of many blocks of code to be
executed. This is the perfect solution for long, nested if/else statements.
Syntax:

switch(n)

Developed By. Dr. Munesh Thakre Page 151 of 306


Web Engineering BE CSE SEM-VII

{
case 1:
execute code block 1;
break;
case 2:
execute code block 2;
break;
default:
code to be executed if n is different from case 1 and 2
break;
}
Example:

JavaScript Function
Introduction
A function is a set of statements that take inputs, do some specific computation, and produce output.
The idea is to put some commonly or repeatedly done tasks together and make a function so that
instead of writing the same code again and again for different inputs, we can call that function.
JavaScript functions are used to perform operations. We can call the JavaScript function many times
to reuse the code.
Advantages of JavaScript Functions
There are mainly two advantages of javascript functions:
1. Code Reusability: We can call a function several times so it saves coding.
2. Less Coding: It makes our program compact. We don’t need to write many lines of code each
time to perform a common task.
Example: A basic javascript function, here we create a function that divides the 1st element by the
second element.
function myFunction(g1,g2) {
return g1/g2;
}
const value = myFunction(8,2); //Calling the function

Developed By. Dr. Munesh Thakre Page 152 of 306


Web Engineering BE CSE SEM-VII

document.write(value);
Output: 4
JavaScript supports function. JavaScript allows us to create user-defined functions also. We can
create function in JavaScript using the keyword function.

Function Declaration
The basic syntax to create a function in JavaScript is shown below:
function functionName(Parameter1, Parameter2, ….)
{
//Function Body
}
To create a function in JavaScript, we have to first use the keyword function, separated by the name
of the function and parameters within parenthesis. The part of the function inside the curly braces { }
is the body of the function.
In JavaScript, functions can be used in the same way as variables for assignments, or calculations.
Function Definition
Before, using a user-defined function in JavaScript we have to create one. We can use the above
syntax to create a function in JavaScript. A function definition is sometimes also termed a function
declaration or function statement. Below are the rules for creating a function in JavaScript:
1. Every function should begin with the keyword function followed by function name.
2. A user-defined function name that should be unique.
3. A list of parameters enclosed within parenthesis and separated by commas.
4. A list of statements composing the body of the function enclosed within curly braces { }.
Example: This eample shows a basic declaration of a function in JavaScript.
function calcAddition(number1, number2) {
return number1 + number2;
}
document.write(calcAddition(6,8));
Output: 14
In the above example, we have created a function named calcAddition.
 This function accepts two numbers as parameters and returns the addition of these two
numbers.

Developed By. Dr. Munesh Thakre Page 153 of 306


Web Engineering BE CSE SEM-VII

 Accessing the function with just the function name without ( ) will return the function object
instead of the function result.
Type of Writing a Function
There are three ways of writing a function in JavaScript:
Function Declaration
It declares a function with a function keyword. The function declaration must have a function name.
Syntax:
function fun(paramA, paramB) {
//Set of statements.
}
Function Expression
It is similar to a function declaration without the function name. Function expressions can be stored
in a variable assignment.
Syntax:
let fun = function(paramA, paramB) {
//set of statements
}
Example: This example explains the usage of the function expression.
const square = function(number) {
return number*number;
}
const x = square(4); //x gets the value 16
document.write(x);
Output: 16
Arrow Function
It is one of the most used and efficient methods to create a function in javascript because of its
comparatively easy implementation. It is a simplified as well as a more compact version of a regular
function expression or syntax.
Syntax:
let function_name = (argument1, argument2, ….) => expression
Example:
This example describes the usage of the Arrow function.
const a = [“Hydrogen”, “Helium”, “Lithium”, “Beryllium”];

Developed By. Dr. Munesh Thakre Page 154 of 306


Web Engineering BE CSE SEM-VII

const a1 = a.map(function(s){
return s.length;
});
Console.write(“Normal way “, a2); //[8,6,7,9]
const a3 = a.map((s)=>s.length);
console.write(“Using Arrow Function ”, a3); //[8,6,7,9]
Output:
Normal way [8,6,7,9]
Using Arrow Function [8,6,7,9]

Function Parameters
Parameters are additional information passed to a function. For example, in the above example, the
task of the function calcAddition is to calculate the addition of two numbers. These two numbers on
which we want to perform the addition operation are passed to this function as parameters. The
parameters are passed to the function within parentheses after the function name and separated by
commas. A function in JavaScript can have any number of parameters and also at the same time, a
function in JavaScript can not have a single parameter.
Example:
In this example, we pass the argument to the function.
function multiply(a,b){
b = typeofb != “undefined” ?b:1;
return a*b;
}
document.write(multiply(69)); //69
Output: 69

Calling Functions
After defining a function, the next step is to call them to make use of the function. We can call a
function by using the function name separated by the value of parameters enclosed between the
parenthesis and a semicolon at the end. The below syntax shows how to call functions in JavaScript:
Syntax:
functionName(value1,value2,….);

Developed By. Dr. Munesh Thakre Page 155 of 306


Web Engineering BE CSE SEM-VII

Example:
Below is a sample program that illustrate the working of functions in JavaScript:
function welcomeMsg(name){
return (“Hello ” + name + “ welcome to BCCA”);
}
//creating a variable
let nameVal = “Students”;
//calling the function
document.write(welcomeMsg(nameVal);
Output:
Hello Students welcome to BCCA
Return Statement
There are some situations when we want to return some values from a function after performing
some operations. In such cases, we can use of the return statement in JavaScript. This is an optional
statement and most of the time the last statement in a JavaScript function. Look at our first example
with the function named as calcAddition. This function is calculating two numbers and then returns
the result.
Syntax: The most basic syntax for using the return statement is:
return value;
The return statement begins with the keyword return separated by the value which we want to return
from it. We can use an expression also instead of directly returning the value.

Built-in Functions
There are several built-in functions in JavaScript. Each one is discussed below.
 Number Functions
 Boolean Functions
 String Functions
 StringHTML Wrappers
 Array Functions
 Math Functions
 Date and Time Functions

Developed By. Dr. Munesh Thakre Page 156 of 306


Web Engineering BE CSE SEM-VII

Number Functions
The number object contains only the default methods that are part of every object’s definition.
Function Description
constructor() Returns the function that create this object’s instance. By default, this is the
Number object.
toExponential() Forces a number to display in exponential notation, even if the number is in the
range in which JavaScript normally uses standard notation.
toFixed() Formats a number with a specific number of digits to the right of the decimal.
toLocalString() Returns a string value version of the current number in a format that may vary
according to a browser’s local settings.
toPrecision() Defines how many total digits (including digits to the left and right of the
deciamal) to display a number.
toString() Returns the string representation of the number’s value.
valueOf() Returns the number’s value.

Boolean Functions
Here is a list of each method and its description.
Function Description
toSource() Returns a string containing the source of the Boolean object; you can use this
string to create an equivalent object.
toString() Returns a string of either “true” or “false” depending upon the value of the
object.
valueOf() Returns the primitive value of the Boolean object.

String Functions
Here is a list of each method and its description.
Function Description
charAt() Returns the character at the specified index.
charCodeAt() Returns a number indicating the Unicode value of the character at the given
index.
concat() Combines the text of two strings and returns a new string.
indexOf() Returns the index within the calling String object of the first occurrence of

Developed By. Dr. Munesh Thakre Page 157 of 306


Web Engineering BE CSE SEM-VII

the specified value, or -1 if not found.


lastIndexOf() Returns the index within the calling String object of the last oocurrence of
the specified value, or -1 if not found.
length() Returns the length of the string.
match() Used to match a regular expression against a string.
replace() Used to find a match between a regular expression and a string, and to
replace the matched substring with a new substring.
search() Executes the search for a match between a regular expression and a
specified string.
slice() Extracts a section of a string and returns a new string.
split() Splits a String object into an array of strings by separating the string into
substring.
substr() Returns the characters in a string beginning at the specified location through
the specified number of characters.
substrings() Returns the characters in a string between two indexes into the string.
toLocaleLowerCase() The characters within a string are converted to lowercase while respecting
the current locale.
toLocaleUpperCase() The characters within a string are converted to the uppercase while
respecting the current locale.
toLowerCase() Returns the calling string value converted to lowercase.
toString() Returns a string representing the specified object.
toUpperCase() Returns the calling string value converted to uppercase.
valueOf() Returns the primitive value of the specified object.

StringHTML Wrappers
Here is a list of each method that returns a copy of the string wrapped inside the appropritate HTML
tag.
Function Description
anchor() Creates an HTML anchor that is used as a hypertext target.
big() Creates a string to be displayed in a big font as if it were in a <big> tag.
blink() Creates a string to blink as if it were in a <blink> tag.
bold() Creates a string to be displayed as bold as if it were in a <b> tag.

Developed By. Dr. Munesh Thakre Page 158 of 306


Web Engineering BE CSE SEM-VII

fixed() Causes a string to be displayed in fixed-pitch font as if it were in <tt> tag.


fontcolor() Causes a string to be displayed in the specified color as if it were in a <font
color= “color”> tag.
fontsize() Causes a string to be displayed in the specified font size as if it were in a <font
size= “size”> tag.
italics() Causes a string to be italic, as if it were in a <i> tag.
link() Creates an HTML hypertext link that request another URL.
small() Causes a string to be displayed in a small font as if it were in a <small> tag.
strike() Causes a string to be displayed as struck-out text as if it were in a <strike> tag.
sub() Causes a string to be displayed as a subscript as if it were in a <sub> tag.
sup() Causes a string to be displayed as a superscript as if it were in a <sup> tag.

Array Functions
Here is a list of each method and its description.
Function Description
concat() Returns a new array comprised of this array joined with another array(s) and/or
value(s).
every() Returns true if every element in this array satisfies the provided testing function.
filter() Creates a new array with all of the elements of this array for which the provided
filtering function returns true.
forEach() Calls a function for each element in the array.
indexOf() Returns the first (last) index of an element within the array equal to the specified
value, or -1 if none is found.
join() Joins all elements of an array into a string.
lastIndexOf() Returns the last (greatest) index of an element within the array equal to the
specified value, or -1 if none is found.
map() Creates a new array with the results of calling a provided function on every
element in this array.
pop() Removes the last element from an array and returns that element.
push() Adds one or more elements to the end of an array and returns the new length of
the array.
reduce() Apply a function simultaneously against two values of the array (from left to

Developed By. Dr. Munesh Thakre Page 159 of 306


Web Engineering BE CSE SEM-VII

right) to reduce it to a single value.


reduceRight() Apply a function simultaneously against two values of the array (from right to
left) to reduce it to a signle value.
reverse() Reverses the order of the elements of an array – the first becomes the last, and the
last becomes the first.
shift() Removes the first element from an array and returns that element.
slice() Extracts a section of an array and returns a new array.
some() Returns true if a least one element in this array satisfies the provided testing
function.
toSource() Represents the source code of an object.
sort() Sorts the elements of an array.

Math Functions
Here is a list of each method and its description.
Function Description
abs() Return the absolute value of a number.
acos() Returns the arccosine (in radians) of a number.
asin() Returns the arcsine (in radians) of a number.
atan() Returns the arctangent (in randians) of a number.
atan2() Returns the arctangent of the quotient of its arguments.
ceil() Returns the smallest integer greater then or equal to a number.
cos() Returns the cosine of a number.
exp() Returns EN, where N is the argument, and E is Euler’s constant, the base of the
natural logarithm.
floor() Returns the largest integer less than or equal to a number.
log() Returns the natural logarithm (base E) of a number.
max() Returns the largest of zero or more numbers.
min() Returns the smallest of zero or more numbers.
pow() Returns base to the exponent power, that is, base exponent.
random() Returns a pseudo-random number between 0 and 1.
round() Returns the value of a number rounded to the nearest integer.
sin() Returns the sine of a number.

Developed By. Dr. Munesh Thakre Page 160 of 306


Web Engineering BE CSE SEM-VII

sqrt() Returns the square root of a number.


tan() Returns the tangent of a number.
toSource() Returns the string “Math”.

Date and Time Functions


Here is a list of each method and its description.
Function Description
Date() Returns today’s date and time.
getDate() Returns the day of the month for the specified date according to local time.
getDay() Returns the day of the week for the specified date according to local time.
getHours() Returns the hour on the specified date according to local time.
getMinutes() Returns the minutes on the specified date according to local time.
getMonth() Returns the month on the specified date according to local time.
getSeconds() Returns the seconds in the specified date according to local time.
getTime() Returns the numeric value of the specified date as the number of milliseconds
since January 1, 1970, 00:00:00 UTC.
getYear() Returns the year on the specified date according to local time. Use
getFullYear instead.
setDate() Sets the day of the month for a specified date according to local time.
setFullYear() Sets the full year for a specified date according to local time.
setHours() Sets the hours for a specified date according to local time.
setMinutes() Sets the minutes for a specified date according to local time.
setMonth() Sets the month for a specified date according to local time.
setSeconds() Sets the seconds for a specified date according to local time.
setTime() Sets the Date object to the time represented by several milliseconds since
January 1, 1970, 00:00:00 UTC.
setYear() Sets the year for a specified date according to local time. Use setFullYear
instead.
toDateString() Returns the “date” portion of the Date as a human-readable string.
toLocalDateString() Returns the “date” portion of the Date as a string, using the current local’s
conventions.
toString() Returns a string representing the specified Date object.

Developed By. Dr. Munesh Thakre Page 161 of 306


Web Engineering BE CSE SEM-VII

HTML Document Object Model (DOM)


When a web page is loaded, the browser creates a Document Object Model of the page. Every web
page resides inside a browser window which can be considered as an object.
A document object represents the HTML document that is displayed in that window. The document
object has various properties that refer to other objects which allow access to and modification of
document content.
The way a documents content is accessed and modified is called the Document Object Model, or
DOM. The objects are organized in a hierarchy. This hierarchical structure applies for the
organization of objects in a web document.
 Window Object: Top of the hierarchy. It is the utmost element of the object hierarchy.
 Document Object: Each HTML document that gets loaded into a window becomes a
document object. The document contains the contents of the page.
 Form Object: Everything enclosed in the <form> … </form> tags sets the form object.
 Form Control Elements: The form object contains all the elements defined for that object
such a text fields, buttons, radio buttons, and checkboxes.
The HTML DOM model is constructed as a tree of Object:

Document

Root element:
<html>

Element: Element:
<head> <body>

Element: Attribute: Element: Element:


<title> “href” <a> <h1>

Text: Text: Text:


“My Title” “My Link” “My Header”

With the object model, JavaScript gets all the power it needs to create dynamic HTML.
 JavaScript can change all the HTML elements on the page.
 JavaScript can change all the HTML attributes on the page.
 JavaScript can change all the CSS styles on the page.
 JavaScript can remove existing HTML elements and attributes.
 JavaScript can add new HTML elements and attributes.
 JavaScript can react to all exsiting HTML events on the page.
 JavaScript can create new HTML events on the page.

Developed By. Dr. Munesh Thakre Page 162 of 306


Web Engineering BE CSE SEM-VII

Working with HTML Form and its Elements


HTML stands for HyperText Markup Language. It is used to design web pages using a markup
language. It is a combination of Hypertext and Markup language. HTML uses predefined tags and
elements that tell the browser how to properly display the content on the screen, and form is one of
them. So, in this article, we will learn what is exactly HTML form, what are the elements of form
and how can we use HTML form in our webpage.
What is HTML <form>?
<form> is an HTML element to collect input data containing interactive controls. It provides
facilities to input text, number, values, email, password and control fields such as checkboxes, radio
buttons, submit buttons, etc, or in other words, form is a container that contains input elements like
text, email, number, radio buttons, checkboxes, submit buttons, etc. Forms are generally used when
you want to collect data from the user. For example, a user wants to buy a bag online, so he/she has
to first enter their shipping address in the address form and then add their payment details in the
payment form to place an order.
Forms are created by placing input fields within paragraphs, preformatted text, lists, and tables. This
gives considerable flexibility in designing the layout of forms.
Syntax:
<form>
<!—form elements-->
</form>
Form Elements
These are the following HTML <form> elements:
 <label>: It defines label for <form> elements.
 <input>: It is used to get input data from the form in various types such as text, password, email,
etc by changing its type.
 <button>: It defines a clickable button to control other elements or execute a functionality.
 <select>: It is used to create a drop-down list.
 <textarea>: It is used to get input long text content.
 <fieldset>: It is used to draw a box around other form elements and group the related data.
 <legend>: It defines a caption for fieldset elements.
 <datalist>: It is used to specify pre-defined list options for input controls.
 <output>: It displays the output of performed calculations.

Developed By. Dr. Munesh Thakre Page 163 of 306


Web Engineering BE CSE SEM-VII

 <option>: It is used to define options in a drop-down list.


 <optgroup>: It is used to define group-related options in a drop-down list.

Textbox in HTML Form


In an HTML form, we use the <input> tag by assigning type attribute value to text to input single
line input. To define type attribute, see the below syntax. The default value of the type attribute is
“text”.
Syntax:
<input type= “text” />
Or shorthand for “text” type:
<input />
Password in an HTML Form
We can change the type value text to password to get the input password.
Example: This example shows the type password in html form.
<!DOCTYPE html>
<!-- Program for illustration of form elements-->
<HTML>
<HEAD>
<TITLE>Textbox and Password</TITLE>
</HEAD>
<BODY>
<center>
<h1>Login Form</h1>
<form>
<label>User Name :</label>
<input type="text"><br><br>
<label>Password :</label>
<input type="password"><br><br>
<input type="submit" value="Submit">
</form>
</center>
</BODY>
</HTML>
Output:

Developed By. Dr. Munesh Thakre Page 164 of 306


Web Engineering BE CSE SEM-VII

Radio Button in an HTML Form


To create a radio button, we use the <input> tag followed by radio type to provide users to choose a
limited number of choices.
Syntax:
<input type= “radio” name= “radio_button_name” value= “radio_button_value”/>
This radio button must have shared the same name to be treated as a group. The value attribute
defines the unique value associated with each radio button. The value is not shown to the user but is
the value that is sent to the server on “submit” to identify which radio button that was selected.
Example: In this example, we will create a radio button to choose your gender.
<!DOCTYPE html>
<!-- Program for illustration of form elements-->
<HTML>
<HEAD>
<TITLE> Radio Button </TITLE>
</HEAD>
<BODY>
<center>
<h1>Registration Form</h1>
<form>
<label>Select Gender :</label>
<input type="radio" name="gender">Male
<input type="radio" name="gender">Female<br><br>
<input type="submit" value="Submit">
</form>
</center>
</BODY>
</HTML>
Output

Checkbox in an HTML Form


To create a checkbox in an HTML form, we use the <input> tag followed by the input type
checkbox. It is a square box tick to activate this. It used to choose more options at a time.
Syntax
<input type= “checkbox” name= “select_box_name” value= “select_box_value”/>

Developed By. Dr. Munesh Thakre Page 165 of 306


Web Engineering BE CSE SEM-VII

The “name” and “value” attributes are used to send the checkbox data to the server.
Example: In this example we use checkbox to select language.
<!DOCTYPE html>
<!-- Program for illustration of form elements-->
<HTML>
<HEAD>
<TITLE>
Checkbox
</TITLE>
</HEAD>
<BODY>
<center>
<h1>Registration Form</h1>
<form>
<label>Languages Known :</label>
<input type="checkbox" name="lang" value="English">English
<input type="checkbox" name="lang" value="Hindi">Hindi
<input type="checkbox" name="lang"
value="Marathi">Marathi<br><br>
<input type="submit" value="Submit">
</form>
</center>
</BODY>
</HTML>

Output:

Combobox in an HTML Form


Combobox is used to create a drop-down menu in your form which contains multiple options. So, to
create a Combobox in an HTML form, we use the <select> tag with <option> tag. It is also known as
a drop-down menu.
Syntax
<select name= “select_box_name”>
<option value= “value1”>Option1</option>
<option value= “value2”>Option2</option>
<option value= “value3”>Option3</option>

Developed By. Dr. Munesh Thakre Page 166 of 306


Web Engineering BE CSE SEM-VII

</select>
The “name” and “value” attributes are used to send the Combobox data to the server.
Example: In this example, we will create a dropdown menu to select Nationality.
<!DOCTYPE html>
<!-- Program for illustration of form elements-->
<HTML>
<HEAD>
<TITLE>
Combobox
</TITLE>
</HEAD>
<BODY>
<center>
<h1>Registration Form</h1>
<form>
<label>Select Your Nationality :</label>
<select name="language">
<option value="Indian">Indian</option>
<option value="Nepali">Nepali</option>
<option value="Japanies">Japanies</option>
</select><br><br>
<input type="submit" value="Submit">
</form>
</center>
</BODY>
</HTML>

Output

Submit button in an HTML Form


In the HTML form, submit button is used to submit the details of the form to the form handler. A
form handler is a file on the server with a script that is used to process input data.
Syntax
<botton type= “submit”>Submit</button>
Example: (See example number Prog131.html)

Developed By. Dr. Munesh Thakre Page 167 of 306


Web Engineering BE CSE SEM-VII

Textarea in an HTML Form


In the HTML form, a textarea is used to add comments or reviews, or addresses to the form. In other
words, the textarea is a multi-line text input control. It contains an unlimited number of characters,
the text renders in a fixed-width font, and the size of the textarea is given by the <rows> and <cols>
attributes. To create a textarea in the form, use the <textarea> tag.
Syntax:
<textarea name= “textarea_name”>content</textarea>
The name attribute is used to reference the textarea data after it is sent to a server.
Example:
<!DOCTYPE html>
<!-- Program for illustration of form elements-->
<HTML>
<HEAD>
<TITLE>
TextArea
</TITLE>
</HEAD>
<BODY>
<center>
<h1>Registration Form</h1>
<form>
<label>Address :</label>
<textarea name="addr" rows="5" cols="40"></textarea>
<br><br>
<input type="submit" value="Submit">
</form>
</center>
</BODY>
</HTML>

Output:

Passing Parameter to Function


The JavaScript Function Parameters are the names that are defined in the function definition and real
values passed to the function in the function definition are known as arguments.
Syntax:
function NameOfFunction(param1, param2, param3,…) {
//Statements

Developed By. Dr. Munesh Thakre Page 168 of 306


Web Engineering BE CSE SEM-VII

}
Parameter Rules
 There is no need to specify the data type for parameter in JavaScript function definitions.
 It does not perform type-checking based on the passed-in JavaScript functions.
 It does not check the number of received arguments.
Parameters:
 Name: It is used to specify the name of the function.
 Arguments: It is provided in the argument field of the function.
Example:
This example uses JavaScript function parameters and finds the largest number.
<!DOCTYPE html>
<!-- WAP to read three numbers and find highest of them
using function-->
<HTML>
<HEAD>
<TITLE>
Program to read 3 numbers and find highest
</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
function highest(a,b,c){
if(a>b && a>c)
l=a;
else if(b>c)
l=b;
else
l=c;
return l;
}
var n1,n2,n3,h;
n1 = prompt("Enter First Number :");
n2 = prompt("Enter Second Number :");
n3 = prompt("Enter Third Number :");

h = highest(n1,n2,n3);

document.write("Highest Number is :" + h);


</SCRIPT>
</BODY>
</HTML>

Developed By. Dr. Munesh Thakre Page 169 of 306


Web Engineering BE CSE SEM-VII

Default Parameter
The default parameters are used to initialize the named parameters with default values in the case
when no value of undefined is passed.
Syntax:
function Name(param1, param2=value, param3=value){
//Statements
}
Example:
<!DOCTYPE html>
<!-- Program for illustration of default parameters-->
<HTML>
<HEAD>
<TITLE>
Default Parameters
</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
function interest(p,n=5,r=6.0){ //default arguments
si = p*r*n/100;
return si;
}
document.write("Simple Interest :" + interest(10000,3,5.5));
document.write("<br>Simple Interest :" + interest(20000,2));
document.write("<br>Simple Interest :" + interest(30000));
</SCRIPT>
</BODY>
</HTML>

Arguments Object
The arguments object are inbuilt objects in JavaScript functions. In all non-arrow functions, the
arguments object is a local variable. Analyze the arguments inside the function by using its
arguments object.
Example:
This example uses argument objects as parameters and finds the largest of numbers.
<!DOCTYPE html>
<!-- Program for illustration of argument object-->

Developed By. Dr. Munesh Thakre Page 170 of 306


Web Engineering BE CSE SEM-VII

<HTML>
<HEAD>
<TITLE>
argument object
</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
function GFG(){
let i;
let maximum = arguments[0];
for(i=1;i<arguments.length;i++){

if(arguments[i]>maximum)
maximum=arguments[i];
}
return maximum;
}
document.write("Largest Value of Collection is :" +
GFG(10,12,500,5,440,45));
</SCRIPT>
</BODY>
</HTML>

Arguments Pass by Value


In a function call, the parameters are called arguments. The pass-by-value sends the value of the
variable to the function. It does not send the address of the variable. If the function changes the value
of arguments, then it does not affect the original value.
Example:
This example demonstrates the above-used approach.
<!DOCTYPE html>
<!-- Program for illustration of Pass by Value-->
<HTML>
<HEAD>
<TITLE>
Pass and Call by Value
</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
/*Function Definition*/
function GeeksForGeeks(var1, var2){
document.write("Inside the GeeksForGeeks function");

Developed By. Dr. Munesh Thakre Page 171 of 306


Web Engineering BE CSE SEM-VII

var1 = 100;
var2 = 200;
/*Display the value of a variable inside function*/
document.write("Var1 = " + var1 + "Var2 = " + var2);
}
var1 = 10;
var2 = 20;
/*The value of the variable before the Function Call*/
document.write("Var1 = " + var1 + "Var2 = " + var2);
/*Function Call*/
GeeksForGeeks(var1,var2);
/*The value of the variable after Function call*/
document.write("Var1 = " + var1 + "Var2 = " + var2);
</SCRIPT>
</BODY>
</HTML>

Output:

Objects passed by Reference


Objects Pass by Reference, passing the address of the variable instead of the value as the argument to
call the Function. If we change the value of the variable inside the function then it will affect outside
function variables.
Example:
This example demonstrates the above-used approach.
<!DOCTYPE html>
<!-- Program for illustration of Pass by Reference-->
<HTML>
<HEAD>
<TITLE>
Pass and Call by Reference
</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
/*Function Definition*/
function GeeksForGeeks(varObj){
document.write("<br>Inside the GeeksForGeeks function");
varObj.a = 100;

Developed By. Dr. Munesh Thakre Page 172 of 306


Web Engineering BE CSE SEM-VII

varObj.b = 200;
/*Display the value of a variable inside function*/
document.write("<br>Var1 = " + varObj.a + " Var2 = " +
varObj.b);
}
/*Create an object*/
varObj = {a:10,b:20};
/*The value of the variable before the Function Call*/
document.write("<br>Var1 = " + varObj.a + " Var2 = " + varObj.b);
/*Function Call*/
GeeksForGeeks(varObj);
/*The value of the variable after Function call*/
document.write("<br>Var1 = " + varObj.a + " Var2 = " + varObj.b);
</SCRIPT>
</BODY>
</HTML>
Output:

Returning a Value from Function


The return statement is used to return a particular value from the function to the function caller. The
function will stop executing when the return statement is called. The return statement should be the
last in a function because the code after the return statement will be unreachable.
We can return primitive values (such as Boolean, number, string, etc) and Object types (such as
functions, objects, arrays, etc) by using the return statement.
We can also return multiple values using the return statement. It cannot be done directly. We have to
use an Array of Object to return multiple values from a function.
Syntax:
return expression;
The expression in the above syntax is the value returned to the function caller. It is optional. If the
expression is not specified, the function returns undefined. It is not allowed to use a line terminator
between the return keyword and value. We can understand it by using the following lines. Suppose
we are writing the return statement as follows:
return
x+y;
then, it will transformed into

Developed By. Dr. Munesh Thakre Page 173 of 306


Web Engineering BE CSE SEM-VII

return;
x+y;
There is the automatic insertion of the semicolon after the return statement. The code written after
the return statement (x+y;) will be considered as the unreachable code. We can use parentheses to
prevent this problem. It can be written as:
return{
x+y;
};
Example:
This is a simple example of using return statement. Here, we are returning the result of the product of
two numbers and returning the value to the function caller.
The variable res is the function caller; it is calling the function fun() and passes two integers as the
arguments of the function. The result will be stored in the res variable. In the output, the value 360 is
the product of arguments 12 and 30.
<!DOCTYPE html>
<!-- Program for illustration of Returning Value-->
<HTML>
<HEAD>
<TITLE>
Returning Value
</TITLE>
</HEAD>
<BODY>
<h2>JavaScript Programs</h2>
<h3>Example of the JavaScript return Statement</h3>
<SCRIPT type="text/javascript">
function fun1(x,y){
return x*y;
}
var res = fun1(12,30);
document.write("Result : " + res);
</SCRIPT>
</BODY>
</HTML>

Array
JavaScript Array is a single variable that is used to store elements of different data types. JavaScript
arrays are zero-indexed. The JavaScript Arrays are not associative in nature.

Developed By. Dr. Munesh Thakre Page 174 of 306


Web Engineering BE CSE SEM-VII

Arrays are used when we have a list of items. An array allows you to store several values with the
same name and access them by using their index number.

Declaration of an Array
There are two ways to declare an array.
1. Creating an array using array literal:
2. Creating an array using the JavaScript new keyword

1. Creating an array using array literal:


let arrayName = [value1, value2, ….];
Example:
//Initializing while declaring
let courses = [“HTML”, “CSS”, “JavaScript”, “React”];
document.write(courses);
Output:
HTML, CSS, JavaScript, React
2. Creating an array using the JavaScript new keyword
let arrayName = new Array();
Example:
//Initializing while declaring
let arr1 = new Array(3);
arr1[0] = 10;
arr1[1] = 20;
arr1[2] = 30;
document.write(“Array 1:” + arr1);
Example:
//Create an array having elements 10,20,30,40,50
let arr2 = new Array(10,20,30,40,50);
document.write(“Array 2:” + arr2);
Example:
//Creates an array of 5 undefined elements
let arr3 = new Array(5);
document.write(“Array 3:” + arr3);

Developed By. Dr. Munesh Thakre Page 175 of 306


Web Engineering BE CSE SEM-VII

Example:
//Creates an array with one element
let arr4 = new Array(“1BHK”);
document.write(“Array 4:” + arr4);
Output:
Array 1: [10,20,30]
Array 2: [10, 20, 30, 40, 50]
Array 3: [<5 empty items>]
Array 4: [‘1BHK’]

Acessing Elements of an Array


An element in the array can be accessed using the index number. The index in the arrays start with 0.
const courses = [“HTML”, “CSS”, “JavaScript”];
document.write(courses[0]);
document.write(courses[1]);
document.write(courses[2]);
Output:
HTML
CSS
JavaScript
Change elements from a pre-defined array
We will use an index-based method to change the elements of the array.
const course = [“HTML”, “CSS”, “JavaScript”];
document.write(course);
course[1] = “Angular”;
document.write(course);
Output:
[HTML, CSS, JavaScript]
[HTML, Angular, JavaScript]

Convert an Array to String


We have an in-built method toString() in JavaScript that converts an array to a string.
const course = [“HTML”, “CSS”, “JavaScript”];

Developed By. Dr. Munesh Thakre Page 176 of 306


Web Engineering BE CSE SEM-VII

document.write(course.toString());
Output:
HTML, CSS, JavaScript
Increase and Decrease the length of an array
Length of an array using the JavaScript’s length property.
const courses = [“HTML”, “CSS”, “JavaScript”];
courses.length = 5; //Increase array length to 5
console.log(“Array after Increased length :”, courses);
courses.length = 2; //Decrease array lennth to 2
console.log(“Array after Decrease length :”, courses);
Output:
Array after Increase length : [“HTML”, “CSS”, “JavaScript”, <2 empty items>]
Array after Decrease length : [“HTML”, “CSS”]

Loop through JavaScript Array Elements


We can loop through the elements of a JavaScript array using the for loop:
const courses = [“HTML”, “CSS”, “JavaScript”];
for(let i=0; i<courses.length;i++){
document.write(“<br> ” + courses[i]);
}
Output:
HTML
CSS
JavaScript
This can also be done by using the Array.forEach() function of JavaScript.
const courses = [“HTML”, “CSS”, “JavaScript”];
courses.forEach(myfunc);
function myfun(elements) {
document.write(elements);
}
Adding new elements to JavaScript Array
Using the JavaScript in-built push() method we can add new element to an array.
const courses = [“HTML”, “CSS”, “JavaScript”];

Developed By. Dr. Munesh Thakre Page 177 of 306


Web Engineering BE CSE SEM-VII

document.write(“Original Array :” + courses);


courses.push(“React”);
document.write(“Array after adding an element :” + courses);

Objects
Objects, in JavaScript, are the most important data types and form the building blocks for modern
JavaScript. These objects are quite different from JavaScript’s pritimitive data types (Numer, String,
Boolean, null, undefined and symbol) in the sense that these primitive data types all stores a single
value each (depending on their types).
In JavaScript, an object is a unordered collection of key-value pairs. Each key-value pair is called a
property. The key of a property can be a string. And the value of a property can be any value, e.g. a
string, a number, an array, and even a function. JavaScript provides you with many ways to create an
object. The most commonly used one is to used the object literal notation.
Syntax:
new Object(value)
Object(value)
let object_name = {
key_name : value,

}
Object() can be called with or without new. Both create a new object.
Example:
const o = new Object();
o.foo = 42;
document.write(o);
Output:
foo: 42
Accessing Object Properties
To access a property of an object, you use one of two notations: the dot notation and array-like
notation.
The dot notation(.):
The following illustrates how to use the dot notation to access a property of an object:
objectName.propertyName
For example, to access the fistName property of the person object, you use the following expression:

Developed By. Dr. Munesh Thakre Page 178 of 306


Web Engineering BE CSE SEM-VII

person.firstName;
This example creates a person object and shows the first name and last name to the console.

let person = {
firstName: ‘John’,
lastName: ‘Doe’
};
document.write(person.firstName);
document.write(person.lastName);
Array-like notation ([]):
The following illustrates how to access the value of an object’s property vai the array-like notation:
objectName[‘propertyName’];
For Example:
let person = {
firstName: ‘John’,
lastName: ‘Doe’
};
document.write(person[‘firstName’]);
document.write(person[‘lastName’]);
When a property name contains spaces, you need to place it inside quotes. For example, the
following address object has the ‘building no’ as a property:
let address = {
‘building no’: 3960,
street: ‘North 1st street’,
state: ‘CA’,
country: ‘USA’
};
To access the ‘buiding no’ property, you need to use the array-like notation:
address[‘building no’];
If you use the dot notation, you’ll get an error:
Address.‘building no’;
Creating Object

Developed By. Dr. Munesh Thakre Page 179 of 306


Web Engineering BE CSE SEM-VII

JavaScript is a flexible object-oriented language when it comes to syntax. Here, we will see the
different ways to create objects in JavaScript. Before we proceed it is important to note that
JavaScript is an object-based language based on prototypes, rather than being class-based. Because
of this different basis, it can be less apparent how JavaScript allows you to create hierarchies of
objects and to have an inheritance of properties and their values.
Creating an object with constructor:
One of the easiest ways to instantiate an object is in JavaScript. Constructor is nothing but a function
and with the help of a new keyword, the constructor allows to create a multiple objects of the same
flavor as shown below:
//Simple function
function vehicle(name, maker, engine){
this.name = name;
this.maker = maker;
this.engine = engine;
}
//New keyword to create an object
let car = new vehicle(‘GT’, ‘BMW’, ‘1998cc’);
//Property accessors
document.write(car.name);
document.write(car.maker);
document.write(car.engine);
Output:
GT
BMW
1998cc
A class in OOPs has two major components, certain parameters, and few member functions. In this
method we declare a function similar to a class, there are three parameters, name, maker and engine
(this key is used to differentiate the name, maker and engine of the class from the name, maker and
engine of the arguments that are being supplied.). We then simply create an object obj of the vehicle,
initialize it and call its method.
Using Object Literals:
Literals are smaller and simpler ways to define objects. We simply define the property and values
inside curly braces as shown below:

Developed By. Dr. Munesh Thakre Page 180 of 306


Web Engineering BE CSE SEM-VII

//Creating js objects with object literal

let car = {
name: ‘GT’,
maker: ‘BMW’,
engine: ‘1998cc’
};
//Property accessor
document.write(car.name); //dot notation
document.write(car[‘maker’]); //bracket notation
Output:
GT
BMW
Methods can also be part of the object while creation or can be added later like properties as shown
below:
//Adding methods to the car object
let car = {
name: ‘GT’,
maker: ‘BMW’,
engine: ‘1998cc’,
start: function(){
document.write(‘Starting the engine…’); }
};
car.start();
//Adding method stop() later to the object.
car.stop = function() {
document.write(‘Applying Brake…’);
}
car.stop();
Output:
Starting the engine…
Applying Brake…

Developed By. Dr. Munesh Thakre Page 181 of 306


Web Engineering BE CSE SEM-VII

Array Object
An array in JavaScript is the collection of multiple types of data at a single place in order, and an
array of object in JavaScript is a collection of homogenous data, that stores a sequence of numbered
objects at a single place.
Example:
let myArr = [
{
studentName: ‘Abhishek’,
studentClass: 6,
studentSection: “A”
},
{
studentName: ‘Sachin’,
studentClass: 7,
studentSection: ‘B’
}
];
document.write(myArr[1]);
Output:
{
studentName: ‘Sachin’,
studentClass: 7,
studentSection: ‘B’
}
Above, there is an array of object myArr and we are accessing an object from the array by using
array index myArr[1], also printing the value on the console. As a result, we are printing an object
from an array of objects. this prints all the key-value pairs present at that particular index.

Developed By. Dr. Munesh Thakre Page 182 of 306


Web Engineering BE CSE SEM-VII

Syntax:
Array of objects syntax:
let myArr = [
//Array
{
//object
},
{
}
];
Creating an Array of Objects
To create an array of objects in JavaScript, we have to declare an empty array first and then initialize
it with the objects separated by a comma.
Example:
let mySchoolArr = [
{
schoolName: “children’s school”,
schoolAddress: “random-address”
},
{
numberOfStudents: 500,
numberOfTeachers: 10
}
];
Above, we declare an array of objects where each arrayis separated by a comma and has three
properties in each.
Array Properties
There are three types of properties in an array Object:
Constructor
The constructor properties return a function that creates the Array prototype. This return function is a
native code that is provided by the JavaScript engine.

Developed By. Dr. Munesh Thakre Page 183 of 306


Web Engineering BE CSE SEM-VII

let myArr = [
{
studentName: ‘Abhishek’,
studentClass: 6,
studentSection: “A”
},
{
studentName: ‘Sachin’,
studentClass: 7,
studentSection: ‘B’
}
];
document.write(myArr.constructor);
Output:
function Array() {
[native code]
}
Above, we have an array of objects myArr and we are printing its constructor properties on the
console. As a result, we print the function Array() {[native code]} on the console.
Here, we get the native code as a reference which is a predefined function inside the JavaScript
engine responsible for creating the array prototype.
Length
It returns the length of elements in an array i.e., the number of objects present in the array.
Example:
let myArr = [
{
studentName: ‘Abhishek’,
studentClass: 6,
studentSection: “A”
},
{
studentName: ‘Sachin’,
studentClass: 7,

Developed By. Dr. Munesh Thakre Page 184 of 306


Web Engineering BE CSE SEM-VII

studentSection: ‘B’
}
];
document.write(myArr.length);
Output:
2
Above, we use the length properties on the myArr array of objects and also print it on the console.
As a result, we print 2 on the console.
Prototype
Array prototype property helps to add new methods into the array, for example, adding all values
into an array. It also helps to add properties to the Array Object.
Example:
//Adding add method into the Array Object using Array.prototype property.
let myArr = [1,2,3,4];
Array.prototype.add = function(){
let result = 0;
//This keyword references the array on which add method will get called
for(let i=0; i<this.length;i++){
result += this[i];
}
return result;
}
console.log(myArr.add());
Output:
10
Above, we are additing a user-defined method into the Array Object. To do that, we accessed the
array prototype using dot notation and added the user-defined function add into Array Object like
this Array.prototype.add. Then, assigned an anonymous function to add, which is the definition of
add method.
In the add method definition, we declare a result variable to store the array value count. Here, we are
using this keyword to reference the array on which the add method will get called and loop over the
array. In each iteration, we are accessing the individual array values and adding them to the result
variable, when all values inside the array get added to the result variable, we returned the final result.

Developed By. Dr. Munesh Thakre Page 185 of 306


Web Engineering BE CSE SEM-VII

String Object
A String is a collection of characters or sequence of characters, which is always enclosed with a
single (‘’) or double quote (“”). A JavaScript string stores a series of characters like “C Sharp
Corner”.
Use of string
 It is used to store single characters, and
 It stores an array of characters.
 It is used to manipulate text – search a particular letter and replace text.
Creation of String
There are two ways to creates string.
By string literal
var string name = “string value”;
zero or more characters written inside single or double quotes or backticks. The string indexes are
zero-based, the first character is in position 0 and the second in 1.
By string object using ‘new’ keyword
var string name = new string(“string value”);
In this, a new keyword is used to create an instance of a string. The string object has some
disadvantages, for example, the execution speed is slow. Now, we can see an example of string
creation.
Example:
<!DOCTYPE html>
<!-- Program for illustration of String Object-->
<HTML>
<HEAD>
<TITLE>
String Object
</TITLE>
</HEAD>
<BODY>
<h2>String</h2>
<script>
var name = "Welcome Khushalkumar"; //literal
var dept = "Computer";
document.write(name);
document.write("<br>He belongs to " + dept + " Department.");
</script>
</BODY>
</HTML>

Developed By. Dr. Munesh Thakre Page 186 of 306


Web Engineering BE CSE SEM-VII

String as Object
JavaScript String Object is a universal object that is used to store strings. A string is a combination of
letters, numbers, special characters (single or double quotations) and arithmetic values.
Example:
<!DOCTYPE html>
<!-- Program for illustration of String Object-->
<HTML>
<HEAD>
<TITLE>
String Object
</TITLE>
</HEAD>
<BODY>
<h2>String Object</h2>
<script>
var msg = new String("Welcome to JavaScript");
document.write(msg);
//Comparisons of literal and objects
document.write("<br>");
var s1 = "String"; //literal
var s2 = new String("String"); //object
var s3 = new String("String"); //object
var s4 = "String";
(s1==s2)?document.write("<br>Equal"):document.write("<br>Not Equal");
(s1===s2)?document.write("<br>Equal"):document.write("<br>Not Equal");
(s2===s3)?document.write("<br>Equal"):document.write("<br>Not Equal");
(s2==s3)?document.write("<br>Equal"):document.write("<br>Not Equal");
</script>
</BODY>
</HTML>

Date Object
The Date Object is an inbuilt datatype of JavaScript language. It is used to work with dates and
times. The Date Object is created by using a new keyword, i.e. new Date(). The Date Object can be
used for date and time in terms of millisecond precision within 100 million days before or after
1/1/1970. But using another method we can only get and set the year, month, day, hour, minutes,
second, and millsecond fields using local UTC or GMT. So, we can represent the date and time till
the year 275755 using the Date object.
There are four different ways to declare a date, the basic thing is that the date objects are created by
the new Date() operator.
Syntax:
new Date()
new Date(milliseconds)

Developed By. Dr. Munesh Thakre Page 187 of 306


Web Engineering BE CSE SEM-VII

new Date(dateString)
new Date(year, month, day, hour, minute, second, millisecond)
Example:
<!DOCTYPE html>
<!-- Program for illustration of Date Object-->
<HTML>
<HEAD>
<TITLE>
Date Object
</TITLE>
</HEAD>
<BODY>
<h2>Date Object</h2>
<script>
//dt is a Date object
var dt = new Date();
document.write(dt +"<br>");

var dt1 = new Date(4500);


document.write("Todays Date :" + dt1 + "<br>");

var dt2 = new Date("October 13, 2013 11:13:00");


document.write("Datastring with day :" + dt2 + "<br>");

var dt3 = new Date(2023,10,11,9,30,30,0);


document.write(dt3);
</script>
</BODY>
</HTML>

Math Object
The Math Object includes mathematical constants and functions. It provides many arithmetic and
trigonometric functions. You do not need to create the Math object before using it.
Syntax for using Math Object
var sqrt_value = Math.sqrt(16);
Example:

Window Object
The Window object is at the very top of the object hierarchy. Window object is parent object of all
other objects. It represents an open window in a browser. An object of window is created
automatically by the browser.
Following table shows some of the methods and properties for window object.
Properties of window Object

Developed By. Dr. Munesh Thakre Page 188 of 306


Web Engineering BE CSE SEM-VII

Property Description
document Returns the document object for the window.
location Returns the location object for the window.
name Sets or returns the name of a window.
status Sets the text in the status bar of a window.
closed Returns a Boolean value indicating whether a window has been closed or not.

Methods of Window Object:


Method Description
alert() Displays an alert box with a message and an OK button.
blur() Removes focus from the current window.
close() Closes the current window.
confirm() Displays a dialog box with a message and an OK and a Cancel button.
focus() Set focus to the current window.
open() Opens a new browser window.
print() Prints the content of the current window.
prompt() Displays a dialog box that prompts the visitor for input.
setTimeOut() Calls function or evaluate an expression after specified number of milliseconds.

Example:
The following code opens the sites in multiple new windows.

Example:
The following code displays an alert box after 5 seconds (5000 milliseconds).

Navigator Object
JavaScript Navigator Object is used to fetch information related to the browser (useragent), like the
browser name, browser version, operating system information etc.
JavaScript Navigator object is also a property of the JavaScript Window object and can be accessed
using the read-only property window.navigator for the current browser window.
In JavaScript, the Navigator Object includes some properties and methods which help us to navigate
from one element to another.

Developed By. Dr. Munesh Thakre Page 189 of 306


Web Engineering BE CSE SEM-VII

Navigator Object Properties


The properties of the navigator object are the variables created inside the Navigator Object. We can
access Navigator Object Property as navigator.propertyname where property name is the name of the
property.
Property Name Description
appcodename Specifies the code name of the browser (experimental property can return
incorrent value).
appname Specifies the name of browser (experimental property – can return incorrect
value).
appversion Specifies the version of browser being used.
cookieEnabled Specifies whether cookies are enabled or not in the browser.
platform Contains a string indicating the machine type for which the browser was
complied.
useragent Contains a string representing the value of the user-agent header sent by the
client to the server in the HTTP protocol.
geolocation Returns the object of GeoLocation which can be used to get the location
information of the device.
onLine Specifies whether the browser is online or not.
language Returns a string with the preferred browser language, for example, en-US for
English.
languages Returns a string with all the languages supported by the browser in order of
user preference.

Navigator Object Methods


The Navigator Object doesn’t have many standardized methods, most of the methods available are
experimental.
Method Description
registerProtocolHandler() Allows websites to register themselves as protocol handler so that they
are allowed to open some standard URL schemes like mailto; tel; sms;
etc.
share() Used to utilize the native support of sharing available in the browser.
sendBeacon() Used to send a small data packet from the client to the server.

Developed By. Dr. Munesh Thakre Page 190 of 306


Web Engineering BE CSE SEM-VII

vibrate() If supported, this can be used to make the device vibrate, if not
supported, nothing happens. This is useful in mobile browsers.
Example:

Events
The change in the state of an object is known as an Event. In html, various events represent that
some activity is performed by the user or by the browser. When JavaScript code is include in HTML,
JS react to these events and allow the execution. This process of reacting to 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.
There are different types of Events.
 Mouse Event
 Frame Event
 Form Event
 Keyboard Event
Mouse Event
A mouse event is an event that gets generated when the mouse interacts with html elements that are
registered to the mouseEvent object. There are different events related to mouse event like a mouse
click, mouse over, mouse out, etc. Whenever a mouse event is generated some activity of action is
performed by the browser. The action performed to handle a mouse event is called mouse event
handler.
Types of Mouse Event
 Click: click event occurs when the mouse is clicked on the register element. the name of the
event handler is onclick.
 Mouseup: mouseup event occurs when the button of the mouse is released over an element. The
name of the event handler is onmouseup.
 Mousedown: mousedown event occurs when the button of the mouse is pressed over an element.
The name of the event handler is onmousedown.
 Mousemove: mousemove event occurs when the button of the mouse move over an element. The
name of the event handler is onmousemove.
 Mouseover: mouseover event occurs when the mouse cursor moves onto the element. The name
of the event handler is onmouseover.

Developed By. Dr. Munesh Thakre Page 191 of 306


Web Engineering BE CSE SEM-VII

 Mouseout: mouseout event occurs when the mouse cursors out of an element. The name of the
event handler is onmouseout.
Example:

Form Events
A form event in JavaScript gets triggered when a user loses focus, or in a sense, the user wants to
make modifications to the form control value. Modification of the value includes a selection of any
check box of the form, making modifications on the opened form which has lost its focus or
changing the typed text, etc. All these events, which get defined inside a form and can act as an event
for the user, act as JavaScript Form Events. Overall, when the user changes the form and the events
associated constitutes JavaScript Form Events as successful.
Various Form Events in JavaScript
There are various form events in JavaScript that work concerining the scenarios and events which the
user can create once the focus is apart from the actual focus control view:
onBlur: This is an event that arises when a user leaves an empty input field and does not even try to
create or type any extra text on the form.
Example:
This program illustrates the onblur From Event in JavaScript, where the user leaves the input field
empty and then tries to give output as shown:

Keyboard Events
Whenever a user presses any key on the Keyboard, different events are fired. There are three
keyboard events, namely keydown, keypress, and keyup. Keyboard events belong to
the KeyboardEvent object.
List of keyboard events
Property Description
Onkeydown The event occurs when the user is pressing a key.
Onkeypress The event occurs when the user presses a key.
Onkeyup The event occurs when the user releases a key.
Example:

Developed By. Dr. Munesh Thakre Page 192 of 306


Web Engineering BE CSE SEM-VII

onChange:
This is an event that arises when a user tries to open the form and does not type or enter any text into
the form, and then the user leaves the field empty. Also, the user tries to select the value from a
dropdown list as entitled in the form.
Example:
This program illustrates the onChange Form Event in JavaScript where the user leaves the input field
as empty and then tries to give select one of the field values from the dropdown, and then after
selection, it gets ready for the listed values.

onFocus:
This is a special event that behaves in a way that when a user is willing to highlight or turn the focus
on some event by highlighting the background of the text or the text as an input to it.
Example:
This program illustrates the Onfocus Form Event in JavaScript where the user leaves the input field
as empty and then tries to select and click the button, which is an event performed by the user to
highlight the important text which is written in the highlighted text by the users as shown in the
output of the give program.

onSelect:
This is a form event in JavaScript where the user tries to put some text as input to the text field and
then displays it to perform further action on the form.
Example:
This program illustrates the form event of the selecting text and then submitting it to the final value.

onSubmit:
This is a form event in which the user tries to make some input by putting text on the form event, and
then it selects that file which asks the user to give some text as input which on submitting as a form
event can perform further action like referring to the next page in moving on to the next segment.
Example:
This program illustrates the form of selecting the text and then submitting it to the final value.

onReset:

Developed By. Dr. Munesh Thakre Page 193 of 306


Web Engineering BE CSE SEM-VII

onReset is a form event where the user tries to click on the reset button to make the form event
appear or the control view to be appearing the same as the previous form, which initially the user
was trying to do.
Example:
This program illustrates the onreset form event where the user tries to reset the form.

onKeyDown:
Onkeydown is a form event where the user clicks on the form to perform an event where the user
presses and holds a down key.
Example:
This program illustrates the event where the user presses the keys of onkeydown.

Developed By. Dr. Munesh Thakre Page 194 of 306


Web Engineering BE CSE SEM-VII

Unit – III
What is PHP?
 PHP originally stood for Personal Home Page.
 It was created in 1994 by Rasmus Lerdorf.
 PHP came to means PHP: Hypertext Preprocessor.
 The definition basically means that PHP handles data before it becomes HTML – which
stands for Hypertext Markup Language.
 PHP is “A popular general-purpose scripting language that is especially suited to web
development”.
 PHP can be embedded into HTML means that PHP code can be written within your HTML
code.
 HTML being the language with which all web pages are built.
 Therefore, programming with PHP starts off as only slightly more complicated than handling
code in HTML.
 PHP is a scripting language, as opposed to a compiled language.
 This means that PHP is designed to do something only after an event occurs.

Why use PHP?


 PHP is better, faster, and easier to learn that the alternatives.
 All websites must begin with just HTML, and you can create an entire site using number of
static HTML pages.
 But basic HTML is a limited approach that does not allow for flexibility or dynamic
behavior. Visitors accessing HTML only sites. See simple pages with no level of
customization or dynamic behavior.
 With PHP, you can create exciting and original pages based on whatever factors you want to
consider.
 PHP can also interact with databases and files, handle email, and do many other things that
HTML alone cannot.
 Web developers learned a long time ago that HTML alone won’t produce enticing and lasting
websites.
 Toward this end, server-side technologies such as PHP have become the norm.

Developed By. Dr. Munesh Thakre Page 195 of 306


Web Engineering BE CSE SEM-VII

 These technologies allow developers to create web application that are dynamically
generated, taking into account whichever elements the programmer desires.

Characteristics of PHP
 PHP is much easier to learn and use.
 PHP was written specifically for dynamic web page creation.
 PHP is both free and cross platform.
 PHP is the most popular tool available for developing dynamic websites.

Getting Started with PHP


Basic HTML Syntax
 All web pages are made using HTML.
 Every web browser, be it Google’s Chrome, Mozilla’s Firefox, Microsoft’s Internet Explorer
and Edge, or Apple’s Safari.
 The HTML code :
<H1>Hello, World!</H1>
I just wanted to say <em> Hello</em>.
The output:

To create an HTML page:


 Open your text editor or integrated development environment(IDE).
 Choose File -> New to create a new, blank document.
 Start with the HTML header lines with <HTML> </HTML> tag.
 Create the head section of the page using <HEAD> </HEAD> tag.
 Create the body section using <BODY> </BODY> tag.
 Complete the page with a closing HTML tag.
 Choose File -> Save As, in the dialog box that appears, choose Text Only (or ASCII) for the
format, if you’re given the option.
 Navigate the location where you wish to save the script.
 Save the file as welcome.html.

Developed By. Dr. Munesh Thakre Page 196 of 306


Web Engineering BE CSE SEM-VII

 Test the page by viewing it in your browser.

Basic PHP Syntax


 To create a PHP page, you’ll start exactly as you would, if you were creating an HTML
document from scratch.
 Web browsers are client applications that understand HTML.
 PHP is used on the server to generate HTML that’s run in a browser.
 There are three main differences between a standard HTML page and a PHP script.
1. First, PHP scripts should be saved with the .php file extension (for example, index.php).
2. Second, you place PHP code with <?php and ?> tags, normally within the context of
some HTML:
….
<body><h1> This is HTML.</h1>
<?php PHP code! ?>
<p> More HTML</p>
….
3. The PHP tags indicate the parts of the page to be run through the PHP processor on the
server. This leads to the third major difference: PHP scripts must be run on a PHP-
enabled web server. This means that PHP scripts must always be run through a URL.

Adding Comments to Scripts


Comments are integral to programming, not because they do anything but because they help you
remember why you did something. The computer ignores these comments when it processes the
script. Furthermore, PHP comments are never sent to the browser, remaining your secret. PHP
supports three ways of adding comments. You can create a single-line comment by putting either //
or # at the beginning of the line you want ignored:
//This is a comment.
You can also use // or # to begin a comment at the end of a PHP line, like so:
print “Hello”; // Just a greeting.
Although it’s largely a stylistic issue. // is much more commonly used in PHP than #. You can create
a multiline comment using /*to begin the comment and */ to conclude it:
To add comments to a script
1. Open the hello2.php created earlier in your text editor or IDE.

Developed By. Dr. Munesh Thakre Page 197 of 306


Web Engineering BE CSE SEM-VII

2. After the initial PHP tag, add some comments to your script:
/* Filename : hello3.php */
3. In front of the print statement, type //.
4. After the closing PHP tag add an HTML comment:
<!--This is an HTML comment. -->
5. Save the script as hello3.php, place it on your PHP enabled server, and run the page in your
web browser.
6. View the source of the page to see the HTML comment.

Variables
What are Variables?
 A variable is a container for data.
 Once data has been stored in a variable, that data can be altered, printed to the browser, saved
to a database, emailed, and so forth.
 Variable in PHP are, by their nature flexible.
 You can put data into a variable, retrieve that data from it, put new data in it, and continue
this cycle as many times as necessary.
 But variables in PHP are largely temporary.
 Most only exist that is, they only have a value for the duration of the script’s execution on the
server.
 Once the execution of the script completes, those variables cease to exist.
 Furthermore, after they are taken to a new page that may have an entirely separate set of
variables.

Variable Syntax
PHP has some predefined variable however you can create your own variables, once you understand
the proper syntax. To create appropriate variable names, you must follow these rules:
 All variable names must be preceded by a dollar sign ($).
 Following the dollar sign, the variable name must begin wih either a letter (A-Z, a-z) or an
underscore (_). A number cannot immediately follow the dollar sign.
 The rest of the variable name can contain any combination of letters, underscores, and
numbers.

Developed By. Dr. Munesh Thakre Page 198 of 306


Web Engineering BE CSE SEM-VII

 You may not use spaces within the name of variable.


 Each variable must have a unique name.
 Variable names are case-sensitive! Consequently, $variable and $Variable are two different
constructs, and it would be a bad idea to use two variables with such similar names.

Types of Variables
There are three types of variables:
1. Numbers
 PHP breaks numbers into two types: integers and floating-point.
 The first type of numbers – integers – is also known as whole numbers. They can positive or
negative but include neither fractions nor decimals.
 Numbers that use a decimal point are floating point numbers, also known as float.
 You use floating point number to refer to fractions, because they only way to express a fraction
in PHP is to convert it to its decimal equivalent.
2. Strings
 A string is any number of characters enclosed within a pair of either single (‘) or double (“)
quotation marks.
 String can contain any combination of characters that exist: letters, numbers, symbols, and
spaces.
 Strings can also contain variables.
 When PHP hits the second quotation mark in the example, it assumes the string ends there; the
continuing text causes an error. To use quotation mark within a string you escape the quotation
mark by putting a backslash (\) before it.
 The backslash tells PHP to treat each escaped quotation mark as part of the value of the string,
rather than using it as the string’s opening or closing indicators.
3. Arrays
 Arrays use keys to create and retrieve the values they store.
 The resulting structure of list of key-value pairs-is similar to a two-column spreadsheet.
 Unlike arrays in other programming languages, the array structure in PHP is so flexible that it
can use either numbers or strings for both the keys and the values.
 The array doesn’t even need to be consistent in this respect.

Developed By. Dr. Munesh Thakre Page 199 of 306


Web Engineering BE CSE SEM-VII

 PHP supports two kinds of arrays, based on the format of the keys. If the array uses numbers
for the keys, it’s known as an indexed array. If it uses strings for the keys, it’s an associative
array. In either case, the values in the array can be of any variable type.

Variable Values
To assign a value to a variable, regardless of the variable type, you use the equals sign(=). Therefore,
the equals sign is known as the assignment operator, because it assigns the value on the right to the
variable on the left. For example:
$number = 1;
$fnumber = 1.2;
$string = “Hello”;
Each of these lines represents a complete statement. So each concludes with a semicolon.
To print the value of a variable, use the print function:
print $number;
print $fnumber;
print $string;
If you want to print a variable’s value within a context, you can place the variable’s name in the
printed string, as long as you use double quotation marks:
print “Number is $number”;
print “String is $string”;
Using print in this way works for the scalar variable types – number and strings. For complex
variable types – arrays and objects – you cannot just use print.
print “_SERVER is $_SERVER”;

To assign values to and access variables


1. Create a new PHP script in your text editor or IDE, to be names variables.php.
2. Create the initial HTML tages:
<!doctype html>
<html lang= “en”>
<head>
<meta charset= “utf-8”>
<title>Variables</title>
</head>
<body>
3. Begin the PHP code:
<?php

Developed By. Dr. Munesh Thakre Page 200 of 306


Web Engineering BE CSE SEM-VII

4. Define some number and string variables:


$street = “100 Main Street”;
$city = “State College”;
$state = “PA”;
$zip = 16801;
5. Print out the values of the variables within some context:
print “<p> The address is : <br> $street<br>$city $state $zip</p>”;
6. Complete the PHP section and the HTML page:
?>
</body>
</html>
7. Save the file as variables.php, upload it to your sever and test it in your browser.
Variables.php
<!doctype html>
<html lang= “en”>
<head>
<meta charset= “utf-8”>
<title>Variables Demo</title>
</head>
<body>
<?php
$street = “100 Main Street”;
$city = “State College”;
$state = “PA”;
$zip = 16801;
print “<p> The address is : <br> $street<br>$city $state $zip</p>”;
?>
</body>
</html>
Understanding Quotation Marks
PHP, like most programming languages, allows you to use both double (“) and single (‘) quotation
marks – but they give vastly different results. It’s critical that you comprehend the distinction, so
they next example will run tests using both type just to emphasize the different behaviours.
The rule to remember is: items within single quotation marks are treated literally; items within
double quotation marks are extrapolated. This means that within double quotation marks, a
variable’s name is replaced with its value, but the same is not true for single quotation makrs.
This rule applies anywhere in PHP you might use quotation marks, including uses of the print
function and the assignment of values to string variables. An example is the best ways to
demonstrate this critical concept.
<!doctype html>

Developed By. Dr. Munesh Thakre Page 201 of 306


Web Engineering BE CSE SEM-VII

<html lang=”en”>
<head>
<meta charset= “utf-8”>
<title>Variables</title>
</head>
<body>
<?php
//Single or double quotation marks won’t matter here
$first_name = ‘Larry’;
$last_name = “Ullman”;
//Single or double quotation marks does matter here
$name1 = ‘$first_name $last_name’;
$name2 = “$first_name $last_name”;
//single or double quotation marks does matter here
print “<h1>Double Quotes</h1>
<p1>name1 is $name1<br>
name2 is $name2</p>;
printf ‘<h1>$Single Quates</h1>
<p1>name1 is $name1<br>
name2 is $name2</p>;
?>
</body>
</html>
To use quotation marks
1. Begin a new PHP script in your text editor or IDE, to be named quotes.php.
2. Create the initial HTML tags.
3. Begin the PHP code.
4. Create two string variables.
5. Create two different name variables, using the existing first_name and last_name variables.
6. Print out the variables using both types of quotation marks.
7. Complete the PHP section and the HTML page.
8. Save the file as quotes.php, upload it to your server and test it in your browser.

HTML Forms and PHP


Forms are fundamental unit of websites, enabling such features as registration and login systems,
search capability, and online shopping. Even the simplest site will find logical reasons to incorporate
HTML forms. And with PHP, it’s stunningly simple to receive and handle data generated by them.

Creating a Simple Form

Developed By. Dr. Munesh Thakre Page 202 of 306


Web Engineering BE CSE SEM-VII

For the HTML form the following example you’ll create a feedback page that takes the user’s
salutation, name, email address, response, and comments. The code that generates form goes
between opening and closing form tags:
<form>
Form elements
</form>
The form tages dictate where a form begins and ends. Every element of the form must be entered
between these two tags. The opening from tag should also contain an action attribute. It indicates
the page to which the form data should be submitted. This value is one of the most important
considerations when you’re creating a form.
<form action = “somepage.php”>
To create HTML form
1. Begin a new document in your text editor or IDE to be named feedback.html.
2. Add the opening form tag.
3. Add a select menu plus a text input for the person’s name.
4. Add a text input for the user’s email address.
5. Add radio buttons for a response.
6. Add a textarea to record the comments.
7. Add the submit button.
8. Close the form.
9. Complete the page.
10. Save the page as feedback.html and view it in your browser.
Feedback.html
<html>
<head>
<meta charset=”utf-8”>
<title>Feedback Form</title>
</head>
<body>
<!--- feedback.html --->
<div><p>Please Complete this form to submit your feedback:</p>
<form action=”handle_form.php”>
<p>Name : <select name=”title” required>
<option value = “Mr.”>Mr. </option>
<option value = “Mrs.”>Mrs.</option>
<option value = “Ms.”>Ms.</option>
</select> <input type= “text” name= “name” size= “20” required>
</p>

Developed By. Dr. Munesh Thakre Page 203 of 306


Web Engineering BE CSE SEM-VII

<p>
Response : This is …
<input type = “radio” name = “response” value = “excellent” required> excellent
<input type = “radio” name = “response” value= “okay”> okay
<input type = “radio” name = “response” value = “boring” > boring
</p>
<p>
Comments: <textarea name = “comments” rows= “3” cols= “30” required > </textarea> </p>
<input type= “submit” name= “submit” value= “Send My Feedback”>
</form>
</div>
</body>
</html>
Choosing a Form Data in PHP
The experienced HTML developer will notice that the feedback form just created is missing one
thing. The initial form tag has no method attribute. The method attribute tells the server how to
transmit the data from the form to the handling script.
You have two choice with method : GET and POST. With respect to forms, the difference between
using GET and POST is squarely in how the information is passed from the form to the processing
script. The GET method sends all the gathered information along as part of the URL. The POST
method transmits the information invisibly to the user. For example, upon submitting a form, if you
use the GET method, the resulting URL will be something like
http://example.com/page.php?var=value&age=20&...
Following the name of the script, page.php, is a question mark, followed by one name=value pair
for each piece of data submitted.
When using the POST method, the end user will only see. http://example.com/page.php.
When deciding which method to use, keep in mind these four factors:
 With the GET method, a limited amount of information can be passed.
 The GET method sends the data to the handling script publicly.
 A page generated by a form that used the GET method can be bookmarked, but one based on
POST can’t be.
 Users will be prompted if they attempt to reload a page accessed via POST but will not be
prompted for pages accessed via GET.

To add a method to a form


1. Open feedback.html in your text editor or IDE, if it is not already open.

Developed By. Dr. Munesh Thakre Page 204 of 306


Web Engineering BE CSE SEM-VII

2. Within the initial form tag, add method= “post”.


3. Save the script and reload it in your browser.
4. View the source of the page to make sure all the required elements are present and have the
correct attributes.
Example: Addition a method attribute with a value of post completes the form.
<html lang = “en”>
<head>
<meta charset= “utf-8”>
<title> Feedback Form </title>
</head>
<body>
<!---script : feedback form --->
<div> <p>Please Complete this form to submit your feedback:</p>
<form action=”handle_form.php”>
<p>Name :
<select name=”title” required>
<option value = “Mr.”>Mr. </option>
<option value = “Mrs.”>Mrs.</option>
<option value = “Ms.”>Ms.</option>
</select>
<input type= “text” name= “name” size= “20” required>
</p>
<p>Email Address :
<input type= “email” name = “email” size= “20” required>
</p>
<p> Response : This is …
<input type = “radio” name = “response” value = “excellent”
required> excellent
<input type = “radio” name = “response” value= “okay”> okay
<input type = “radio” name = “response” value = “boring” >
boring
</p>
<p>Comments:
<textarea name = “comments” rows= “3” cols= “30” required >
</textarea> </p>
<input type= “submit” name= “submit” value= “Send My Feedback”>
</form>
</div>
</body>
</html>

Receiving Form Data in PHP


Developed By. Dr. Munesh Thakre Page 205 of 306
Web Engineering BE CSE SEM-VII

 Now you need to write script that will receive and process the submitted form data.
 For above example the PHP script will simply repeated what the user entered into the form.
 To access the submitted form data, you need to refer to a particular predefined variable.
 When it comes to handling form data, the specific variable the PHP script would refer to is
either $_GET or $_POST.
 If an HTML form uses the GET method, the submiited form data will be found in $_GET.
 When an HTML form uses the POST method, the submitted form data will be found in
$_POST.
 $_GET and $_POST, besides being predefined variables are arrays, a special variable type
($_SERVER is also an array).
 This means that both $_GET and $_POST may contain numerous values, making the
printing of those values more challenging.
Example: Form data submitted to the script is displayed by referencing the associated $_POST variable
<html lang= “en”>
<head>
<title>Your Feedback</title>
</head>
<body>
<?php //Script handle_form.php
//It will receive: title, name, email, respose, comments, and submit in $_POST
//Create shorthand versions of the variables:
$title = $_POST[‘title’];
$name = $_POST[‘name’];
$response = $_POST[‘response’];
$comment = $_POST[‘comment’];
//Print the received data:
print “<p>Thank you, $title $name, for your comments. </p>
<p>You stated that you found this example to be ‘$response’ and added: <br>$comments</p>”;
?>
</body>
</html>
To handling an HTML form:
1. Begin a new document in your text editor of IDE, to be named handle_form.php.
2. Add the opening PHP tag and any comments.
3. Assign the received data to new variables.
4. Print out the user information.
5. Close the PHP section, and complete the HTML page.
6. Save the script as handle_form.php.

Developed By. Dr. Munesh Thakre Page 206 of 306


Web Engineering BE CSE SEM-VII

7. Upload the script to the server, making sure it’s saved in the same directory as
feedback.html.
8. Load feedback.html in your browser through a URL.
9. Fill out and then submit the form.

Displaying Errors
To have PHP display errors, you can do one of the following:
 Turn display_errors back on the PHP as a whole.
 Turn display_errors back on for an individual script.
While developing a site, the first option is by far preferred. However, it’s a possibility only for those
with administrative control over the server. But anyone can use the second option by including this
line in a script:
ini_set(‘display_errors’,1);
The ini_set() function allows a script to temporarily override a setting in PHP’s configuration file.
To display errors in a script
1. Open handle_form.php in your text editor or IDE, if it is not already open.
2. As the first line of PHP code, enter the following: ini_set(‘display_error’,1);
3. Save the file as handle_form.php.
4. Upload the file to your web server, and test it in your browser.
<html lang= “en”>
<head>
<title>Your Feedback</title>
</head>
<body>
<?php //handle_form.php
ini_set(‘display_errors’,1); //let me learn from my mistakes
//This page receives the data from feedback.html
//It will receive: title, name, email, response, comments, and submit in $_POST
//Create shorthand version of the variables.
$title = $_POST[‘title’];
$name = $_POST[‘name’];
$response = $_POST[‘response’];
$comments = $_POST[‘comment’];
//Print the received data :
print “<p>Thank you, $title $name, for your comments.</p>
<p> You stated that you found this example to be ‘$response’ and
added:<br>$comments</p>”;
?>
</body>

Developed By. Dr. Munesh Thakre Page 207 of 306


Web Engineering BE CSE SEM-VII

</html>

Error Reporting
 PHP has more than a dozen different levels of errors, and you can define your own.
 You can set what errors PHP reports on in two ways.
 First, you can adjust the error_reporting level in PHP’s configuration file. If you are
running your own PHP server, you’ll probably want to adjust that global setting while
developing your scripts.
 The second option is to use the error_reporting() function in a script. The function takes
either a number or one or more constants – nonquoted strings with predetermined meanings –
to adjust the levels.

PHP Error Levels


Type Description Example
Notice Nonfatal error that may or may not Referring to a variable that has no value.
be indivative of a problem
Warning Nonfatal error that is most likely Misusing a function.
problematic.
Parse error Fatal error caused by a syntactical Omission of a semicolon or an imbalance of
mistake. quotation marks, braces, or parentheses.
Error A general fatal error. Memory allocation problem.
Error Reporting Constants
E_ERROR, E_WARNING, E_PARSE, E_NOTICE, E_STRICT, E_DEPRECATED
To adjust error reporting in a script
1. Open handle_form.php your text editor or IDE, if it is not open already.
2. After the ini_set() line, add the following : error_reporting(E_ALL);
3. Save the file as handle_form.php.
4. Place the file in the proper directory for your PHP enabled server, and test it in your browser
by submitting the form.
<html lang= “en”>
<head>
<title>Your Feedback</title>
</head>
<body>
<?php //handle_form.php

Developed By. Dr. Munesh Thakre Page 208 of 306


Web Engineering BE CSE SEM-VII

ini_set(‘display_errors’,1); //let me learn from my mistakes


error_reporting(E_ALL); //show all possible problem.
//This page receives the data from feedback.html
//It will receive: title, name, email, response, comments, and submit in$_POST
//Create shorthand version of the variables.
$title = $_POST[‘title’];
$name = $_POST[‘name’];
$response = $_POST[‘response’];
$comments = $_POST[‘comment’];
//Print the received data :
print “<p>Thank you, $title $name, for your comments.</p>
<p> You stated that you found this example to be ‘$response’ and
added:<br>$comments</p>”;
?>
</body>
</html>

Using Numbers
Creating the Form
 Most of the PHP example will perform various calculation based on an e-commerce premise.
 A form will take price, quantity, discount amount, tax rate, and shipping cost and PHP script
that handles the form will return a toal cost.
 That cost will also be broken down by the number of payments the user wants to make in
order to generate a monthly cost value.
 To start, let’s create an HTML page that allows the user to enter the values.
To create the HTML form
1. Begin a new HTML document in your text editor or IDE, to be named calculator.html.
2. Create the initial form tag: <form action= “handle_calc.php” method= “post”>.
3. Create the inputs for the price, quantity, discount and tax.
4. Add a field in which the user can select a shipping method.
5. Complete the HTML form.
6. Complete the HTML page.
7. Save the script as calculator.html and view it in your browser.
Calculator.html
<html>
<head>
<title>Product Cost Calculator</title>

Developed By. Dr. Munesh Thakre Page 209 of 306


Web Engineering BE CSE SEM-VII

</head>
<body><!---Script Calculator.html -->
<div> <p> Fill out this form to calculate the total cost :</p>
<form action = “handle_calc.php” method= “post”>
<p>Price : <input type = “text” name= “price” size= “5”></p>
<p>Quantity : <input type = “number” name= “quantity” size= “5”
min= “1” value= “1”></p>
<p>Discount : <input type = “text” name= “discount” size= “5”></p>
<p>Tax : <input type = “text” name= “tax” size= “5”>(%)</p>
<p>Shipping method: <select name= “shipping”>
<option value= “5.00”>Slow and steady</option>
<option value= “8.95”>Put a move on it.</option>
<option value= “19.36”>I need it yesterday!</option>
</select></p>
<p>Number of payment to make: <input type= “number” name=
“payment” size= “5” min= “1” value= “1”</p>
<input type= “submit” name= “submit” value= “Calculate!”>
</form>
</div>
</body>
</html>

Performing Arithmetic
Like in grade school, basic mathematics involves the principles of addition, subtraction,
multiplication, and division. These are performed in PHP using the most obvious operators:
 Addition
 Subtraction
 Multiplication
 Division
To create your sales cost calculator
1. Create a new document in your text editor or IDE, to be named handle_calc.php.
2. Insert the PHP tag and address error handling, if desired.
3. Assign the $_POST elements to local variables.
4. Begin calculating the total cost.
5. Calculate the tax rate and the new total.
6. Calculate the monthly payment.
7. Print the results.
8. Close the PHP section.

Developed By. Dr. Munesh Thakre Page 210 of 306


Web Engineering BE CSE SEM-VII

9. Save the script as handle_calc.php and place it in the proper directory for your PHP enabled
server.
10. Test the script in your browser by filling out and submitting the form.
Handle_calc.php
<html lang= “en”>
<head>
<title>Product Cost Calculator</title>
<style type= “text/css”>
.number{font-weight: bold;}
</style>
</head>
<body>
<?php //handle_calc.php
/*This script takes values from calculator.html and performs total cost and
monthly payment calculations. */
//Get the values from the $_POST array:
$price = $_POST[‘price’];
$quantity = $_POST[‘quantity’];
$discount = $_POST[‘discount’];
$tax = $_POST[‘tax’];
$shipping = $_POST[‘shipping’];
$payments = $_POST[‘payments’];

//Calculate the total:


$total = $price * $quantity;
$total = $total + $shipping;
$total = $total - $discount;

//Determine the tax rate:


$taxrate = $tax/100;
$taxrate = $taxrate + 1;

//Factor in the tax rate:


$total = $total * taxrate;

//Calculation the monthly payments:


$monthly = $total/$payments;
//Print out the results:
print “<p>You have selected to purchase:<br>
<span class= \ “number\”>$quantity</span> widget(s) at <br>
$<span class=\ “number\”>$price</span>price each plush a <br>
$<span class=\ “number\”>$shipping</span>shipping cost and a <br>

Developed By. Dr. Munesh Thakre Page 211 of 306


Web Engineering BE CSE SEM-VII

$<span class=\ “number\”>$tax</span>percent tax rate. <br>


After your $<span class=\ “number\”>$discount</span>discount, the
total cost is $<span class=\ “number\”>$total</span>. <br> Divided
over <span class=\ “number\”>$payment</span>monthly payments,
that would be $<span class=\ “number\”>$monthly</span>each.<br>
?>
</body>
</html>

Formatting Numbers
 Although the calculator is on its way to being practical, it still has one legitimate problem:
you can’t ask someone to make a monthly payment of $10.12183333! to create more usable
numbers, you need to format them.
 Two functions are appropriate for this purpose. The first round(). Rounds a value to specified
number of decimal places. The function’s first argument is the number to be rounded. This
can be either a number or a variable that has a numeric value.
 The second argument is optional; it represents the number of decimal places to which to
round. If omitted, the number will be rounded to the nearest integer.
 For example:
round(4.30); //4
round(4.289,2); //4.29
$num = 239.26985;
round($num); //239
 The other function you can use in this situation is number_format(). It works like round() in
that it takes a number and an optional decimal specifier. This function has the added benefit
of formatting the number with commas, the way it would commonly be written:
number_format(428.4959,2); //428.50
number_format(428,2); //428.00
number_format(12345687); //1,234,5687

To format numbers
1. Open handle_calc.php in your text editor or IDE, if it is not already open.
2. After all the calculations but before the print statement, add the following:
$total = number_format($total,2);
$monthly = number_format($monthly,2);
3. Save the file, place it in the same directory as calculator.html and test it in your browser.

Handle_calc.php

Developed By. Dr. Munesh Thakre Page 212 of 306


Web Engineering BE CSE SEM-VII

<html lang= “en”>


<head>
<title>Product Cost Calculator</title>
<style type= “text/css”>
.number{font-weight: bold;}
</style>
</head>
<body>
<?php //handle_calc.php
/*This script takes values from calculator.html and performs total cost and
monthly payment calculations. */
//Get the values from the $_POST array:
$price = $_POST[‘price’];
$quantity = $_POST[‘quantity’];
$discount = $_POST[‘discount’];
$tax = $_POST[‘tax’];
$shipping = $_POST[‘shipping’];
$payments = $_POST[‘payments’];

//Calculate the total:


$total = $price * $quantity;
$total = $total + $shipping;
$total = $total - $discount;

//Determine the tax rate:


$taxrate = $tax/100;
$taxrate = $taxrate + 1;

//Factor in the tax rate:


$total = $total * taxrate;

//Calculation the monthly payments:


$monthly = $total/$payments;

//Apply the proper formatting:


$total = number_format($total,2);
$monthly = number_format($monthly,2);
//Print out the results:
print “<p>You have selected to purchase:<br>
<span class= \ “number\”>$quantity</span> widget(s) at <br>
$<span class=\ “number\”>$price</span>price each plush a <br>
$<span class=\ “number\”>$shipping</span>shipping cost and a <br>
$<span class=\ “number\”>$tax</span>percent tax rate. <br>

Developed By. Dr. Munesh Thakre Page 213 of 306


Web Engineering BE CSE SEM-VII

After your $<span class=\ “number\”>$discount</span>discount, the


total cost is $<span class=\ “number\”>$total</span>. <br> Divided
over <span class=\ “number\”>$payment</span>monthly payments,
that would be $<span class=\ “number\”>$monthly</span>each.<br>
?>
</body>
</html>

Understanding Precedence
 Precedence refers to the order in which a series of calculations are executed.
 For example, what is the value of the following variable?
$number = 10-4/2;
 Is $number worth 3(10 minus 4 equals 6, divided by 2 equals 3) or 8(4 divided by 2 equals
2, subtract from 10 equals 8)?
 The answer here is 8, because division takes precedence over subtraction.
To manage precedence
1. Open handle_calc.php in your text editor or IDE, if it is not already open.
2. Replace the three lines that initially calculate the order total.
3. Change the two lines that calculate and add in the tax to this.
4. Save the script, place it in the same directory as calculation.html and test it in your browser.
Handle_calc.php
<html lang= “en”>
<head>
<title>Product Cost Calculator</title>
<style type= “text/css”>
.number{font-weight: bold;}
</style>
</head>
<body>
<?php //handle_calc.php
/*This script takes values from calculator.html and performs total cost and
monthly payment calculations. */
//Get the values from the $_POST array:
$price = $_POST[‘price’];
$quantity = $_POST[‘quantity’];
$discount = $_POST[‘discount’];
$tax = $_POST[‘tax’];
$shipping = $_POST[‘shipping’];
$payments = $_POST[‘payments’];

Developed By. Dr. Munesh Thakre Page 214 of 306


Web Engineering BE CSE SEM-VII

//Calculate the total:


$total = (($price * $quantity) + $shipping) - $discount;

//Determine the tax rate:


$taxrate = ($tax/100) + 1;

//Factor in the tax rate:


$total = $total * taxrate;

//Calculation the monthly payments:


$monthly = $total/$payments;

//Apply the proper formatting:


$total = number_format($total,2);
$monthly = number_format($monthly,2);

//Print out the results:


print “<p>You have selected to purchase:<br>
<span class= \ “number\”>$quantity</span> widget(s) at <br>
$<span class=\ “number\”>$price</span>price each plush a <br>
$<span class=\ “number\”>$shipping</span>shipping cost and a <br>
$<span class=\ “number\”>$tax</span>percent tax rate. <br>
After your $<span class=\ “number\”>$discount</span>discount, the
total cost is $<span class=\ “number\”>$total</span>. <br> Divided
over <span class=\ “number\”>$payment</span>monthly payments,
that would be $<span class=\ “number\”>$monthly</span>each.<br>
?>
</body>
</html>

Incrementing and Decrementing a Number


PHP, like most programming languages, includes shortcuts that let you avoid ugly constructs such
as:
$tax = $tax + 1;
When you need to increase the value of a variable by 1(known as an increamental adjustment) or
decrease the value of a variable by 1(a decremental adjustment). You can use ++ and --, respectively:
$var = 20; //20
$var++; //21
$var++; //22
$var--; //21

Developed By. Dr. Munesh Thakre Page 215 of 306


Web Engineering BE CSE SEM-VII

Solely for the sake of testing this concept, you’ll rewrite the handle_calc.php script one last time.
To increment the value of a variable
1. Open handle_calc.php in your text editor or IDE, if it is not already open.
2. Change the tax rate calculation from:
$taxrate = $tax/100;
$taxrate++;
3. Save the script, place it in the same directory as calculation.html, and test it in your browser.
Handle_calc.php
<html lang= “en”>
<head>
<title>Product Cost Calculator</title>
<style type= “text/css”>
.number{font-weight: bold;}
</style>
</head>
<body>
<?php //handle_calc.php
/*This script takes values from calculator.html and performs total cost and
monthly payment calculations. */
//Get the values from the $_POST array:
$price = $_POST[‘price’];
$quantity = $_POST[‘quantity’];
$discount = $_POST[‘discount’];
$tax = $_POST[‘tax’];
$shipping = $_POST[‘shipping’];
$payments = $_POST[‘payments’];
//Calculate the total:
$total = (($price * $quantity) + $shipping) - $discount;
//Determine the tax rate:
$taxrate = $tax/100;
$taxrate++;
//Factor in the tax rate:
$total = $total * taxrate;
//Calculation the monthly payments:
$monthly = $total/$payments;
//Apply the proper formatting:
$total = number_format($total,2);
$monthly = number_format($monthly,2);
//Print out the results:
print “<p>You have selected to purchase:<br>
<span class= \ “number\”>$quantity</span> widget(s) at <br>

Developed By. Dr. Munesh Thakre Page 216 of 306


Web Engineering BE CSE SEM-VII

$<span class=\ “number\”>$price</span>price each plush a <br>


$<span class=\ “number\”>$shipping</span>shipping cost and a <br>
$<span class=\ “number\”>$tax</span>percent tax rate. <br>
After your <span class=\ “number\”>$discount</span>discount, the
total cost is <span class=\ “number\”>$total</span>. <br> Divided
over <span class=\ “number\”>$payment</span>monthly payments,
that would be <span class=\ “number\”>$monthly</span>each.<br>
?>
</body>
</html>
Creating Random Numbers
We know that mt_rand(), a random number generator. All it does is output a random number:
$n = mt_rand(); //11
$n = mt_rand(); // 87
The mt_rand() function can also take minimum and maximum parameters, if you prefer to limit the
generated number to a specific range:
$n = mt_rand(0,10);
These values are inclusive, so in this case 0 and 10 are feasible returned values.
As an example of generating random number, let’s create a simple “Lucky Number” script.
To generate random numbers
1. Begin a number document in your text editor or IDE, to be named random.php.
2. Include the PHP tag and address error management, if you need to.
3. Create three random numbers:
$n1=mt_rand(1,99);
$n2=mt_rand(1,99);
$n3=mt_rand(1,99);
4. Print out the numbers:
print “Lucky Numbers are :</br>”;
print “$n1</br>”;
print “$n2</br>”;
print “$n3</br>”;
5. Close the PHP code and the HTML page:
6. Save the file as random.php place it in the proper directory for your PHP enabled server, and
test it in your browser. Refresh the page to see different numbers.
Random.php
<html>
<head>
<title>Lucky Number</title>
</head>
<body>
<?php //random.php

Developed By. Dr. Munesh Thakre Page 217 of 306


Web Engineering BE CSE SEM-VII

//This script generates 3 random number //Create three random numbers


$n1=mt_rand(1,99);
$n2=mt_rand(1,99);
$n3=mt_rand(1,99);
//Print out the numbers
print “Your Lucky Number are</br>”;
print “$n1</br>”;
print “$n2</br>”;
print “$n3</br>”;
?>
</body>
</html>

Using String
 A second category of variables used by PHP is string - a collection of characters enclosed
within either single or double quotation marks.
 The values of a string variable may be single letter, a word, a sentence, a paragraph, HTML
code, or even a jumble of nonsensical letters, numbers, and symbols.
 Strings may be the most common variable type used in PHP.

Creating the HTML Form


HTML forms and PHP let’s begin by creating an HTML form that sends different values – in the
form of string variables – to a PHP script. The theoretical example being used is an online bulletin
board or forum where users can post a message, their email address, and their first and last names.
To create the HTML form:
1. Begin a new HTML document in your text editor or IDE, to be named (posting.html).
2. Create the initial form tag.
3. Add inputs for the first name, last name, and email address.
4. Add an input for the posting.
5. Create a submit button, and close the form.
6. Complete the HTML page.
7. Save the file as posting.html, place it in the appropriate directory on you PHP-enabled
server, and view it in your browser.
Posting.html
<html lang= “en”>
<head>
<title>Forum Posting</title>
</head>

Developed By. Dr. Munesh Thakre Page 218 of 306


Web Engineering BE CSE SEM-VII

<body>
<div><p>Please complete this form to submit your posting :</p>
<form action= “handle_post.php” method = “post”>
<p>First Name :<input type= “text” name= “first_name” size= “20”> </p>
<p>Last Name :<input type= “text” name= “last_name” size= “20”></p>
<p>Email Address :<input type= “email” name= “email” size= “30”></p>
<p>Posting: <textarea name= “posting” row= “9” cols= “30”></textarea></p>
<input type= “Submit” name= “submit” value= “Send My Posting”>
</form>
</body>
</html>
Concatenating Strings
Concatenation is an unwieldy term but a useful concept. It refers to the appending of one item onto
another. Specifically, in programming, you concatenate strings. The period (.) is the operator for
performing this action, and it’s used like so:
$s1= ‘Hello,’;
$s2 = ‘world!’;
$greeting = $s1.$s2;
The result of this concatenation is that the $greeting variable has a value of Hello, World!
Because of the way PHP deals with variables, the same effect could be accomplished using
$greeting = “$s1$s2”
This code works because PHP replaces variables within double quotation makrs with their value.
However, the formal method of using the period to concatenate strings is more commonly used and
is recommended.
Another way of performing concatenation involves the concatenation assignment operator.
$greeting = ‘Hello,’;
$greeting .= ‘World!’;
This second line roughly means “assign to $greeting is current value plus the concatenation of
world!” The end result is $greeting having the value Hello, World! once again.
The posting.html script sends several string variables to the handle_post.php page. Of those
variables, the first and last names could logically be concatenated.
To use concatenation
1. Begin a new document in your text editor or IDE, to be named handle_post.php.
2. Create the initial PHP tag, and address error management, if necessary.
3. Assign the form data to local variables.
4. Create a new $name variable using concatenation.

Developed By. Dr. Munesh Thakre Page 219 of 306


Web Engineering BE CSE SEM-VII

5. Print out the message to the user.


6. Close the PHP section and complete the HTML page.
7. Save your script as handle_post.php place it in the same directory as posting.html.
Handle_post.php
<html lang= “en”>
<head>
<title>Forum Posting</title>
</head>
<body>
<?php //handle_post.php
/*This script receives five values from posting.html first_name, last_name,
email, posting and submit*/
//Get the value from the $_POST array:
$first_name = $_POST[‘first_name’];
$last_name = $_POST[‘last_name’];
$posting = $_POST[‘posting’];
//create a full name variable
$name = $first_name. ‘’.$last_name;
//Print a message:
print “<div>Thank you, $name, for your posting:<p>$posting</p> </div>”;
?>
</body>
</html>

Handling Newlines
A common question beginning PHP developers have involved newlines in strings. The textarea
form element allows a user to enter text over multiple lines by pressing Return/Enter. Each use of
Return/Enter equates to a newline in the resulting string. These newlines work within a textarea but
have no effect on a rendered PHP page.
To create the equivalent of newlines in a rendered web page, you use the break tag: <br>.
Fortunately, PHP has the nl2br() function, which automatically converts newlines into break tags;
$var = nl2br($var);
Let’s apply this function to handle_post.php so that the user’s posting retains its formatting.
To convert newlines to breaks:
1. Open handle_post.php.
2. Apply the nl2br() function when assigning a value to the $posting variable.
3. Save the file, place it in the same directory as posting.html and test again in your browser.

Developed By. Dr. Munesh Thakre Page 220 of 306


Web Engineering BE CSE SEM-VII

HTML and PHP


PHP is a server-side technology that’s frequently used to send data to to the browser. This data can
be in the form of plain text, HTML code, or, more commonly, both.
In this section, primary example, data is entered in an HTML form and then printed back to the
browser using PHP. A potential problem is that the user can enter HTML characters in the form,
which can affect the resulting page’s formatting or worse, cause security problems.
You can use a few PHP functions to manipulate HTML tags within PHP string variables:
 htmlspecialchars() converts certain HTML tags into their entity versions.
 htmlentities() turns all HTML tags into their entity versions.
 strip_tags() removes all HTML and PHP tags.
The first two functions turn an HTML tag into an entity version like &lt;span&gt;. The entity
version appears in the output but isn’t rendered. You might use either of these if you wanted to
display code without enacting it. The third function, strip_tags(), removes HTML and PHP tags
entirely.
To address HTML in PHP
1. Open handle_post.php.
2. Before the print line, add the following script:
$html_post = htmlentities.($_POST[‘posting’]);
$strip_post = strip_tags.($_POST[‘posting’]);
3. Alter the print statement.
4. Save the file, place it in the same directory as posting.html.
Handle_post.php
<html lang= “en”>
<head>
<title>Forum Posting</title>
</head>
<body>
<?php //handle_post.php
/*This script receives five values from posting.html first_name, last_name,
email, posting and submit*/
//Get the value from the $_POST array:
$first_name = $_POST[‘first_name’];
$last_name = $_POST[‘last_name’];
$posting = n12br($_POST[‘posting’]);
//create a full name variable
$name = $first_name. ‘’.$last_name;

Developed By. Dr. Munesh Thakre Page 221 of 306


Web Engineering BE CSE SEM-VII

//Ajust for HTML tags:


$html_post = htmlentities($_POST[‘posting’]);
$strip_post = $strip_tags($_POST[‘posting’]);
//Print a message:
print “<div>Thank you, $name, for your posting:
<p>Original: $posting</p>
<p>Entity: $html_post</p>
<p>Stripped: $strip_post</p></div>”;
?>
</body>
</html>

Comparing Strings
To compare two strings, you can always use the equality operator. Otherwise, you can use the
strcmp() function. It indicates how two strings compare by returning a whole number: 0 if they are
the same, and a positive or negative number if one is “greater” than the other. PHP also has a case-
insensitive companion, strcasecmp().
To see if a substring is contained within another string, you’ll use these functions:
 strstr() returns the haystack from the first occurrence of a needle to the end.
 strpos() searches through a haystack and returns the numeric location of a particular need.
Both of these functions also have a case insensitive alternative: stristr() and stripos(), respectively.
Each of these functions is normally used in a conditional to test whether the substring was found.

Finding Substrings
PHP has a few function you can use to pull apart string, search through them, and perform
comparisons. Although these functions are normally used with conditionals. The strtok() function
creates a substring, referred to as a token, from a larger string by using a predetermined separator.
For example, if you have users enter their full name in one field, you can pull out their first name
with this code:
$first = strtok($_POST[‘name’], ‘’);
That line tells PHP to extract everthing from the beginning of $_POST[‘name’] until it finds a blank
space.
If you have users enter their full name in the format Surname, First, you can find their surname by
writing $last = strtok($_POST[‘name’], ‘’);

Developed By. Dr. Munesh Thakre Page 222 of 306


Web Engineering BE CSE SEM-VII

A second way to pull out sections of a string is by referring to the indexed position of the characters
within the string. The indexed position of a string is the numerical location of a character, counting
from the beginning. However, PHP – like most programming languages – begins all indexes with the
number 0.
You can use the substr() function to create a substring based on the index position of the substring’s
characters:
$sub = substr($string, 0,10);
The first argument is the master string from which the substring will be divided. Second, indicate
where the substring begins, as its indexed position. Third, from that starting point, state how many
characters the substring should contain. If the master string does not have that many characters in it,
the resulting substring will end with the end of the master string. This argument is optional; if
omitted, the substring will also go until the end of the master string.
You can also use negative numbers to cound backward from the end of the string:
$string = ‘aardvard’;
$sub = substr($string, -3,3);
Handle_post.php
<html lang= “en”>
<head>
<title>Forum Posting</title>
</head>
<body>
<?php //handle_post.php
/*This script receives five values from posting.html first_name, last_name,
email, posting and submit*/
//Get the value from the $_POST array:
$first_name = $_POST[‘first_name’];
$last_name = $_POST[‘last_name’];
$posting = n12br($_POST[‘posting’]);
//Create a full name variable
$name = $first_name. ‘’.$last_name;
//Get a word count:
$word = str_word_count($posting);
//Get a snipped of the posting
$posting = substr($posting,0,50);
//Print a message:
print “<div>Thank you, $name, for your posting:
<p> $posting…</p>
<p>($words words)</p></div>”;
?>

Developed By. Dr. Munesh Thakre Page 223 of 306


Web Engineering BE CSE SEM-VII

</body>
</html>
To create substrings
1. Open handle_post.php.
2. Before the print statement, add the following:
$word = str_word_count($posting);
3. On the next line, add
$posting = substr($posting,0,50);
4. Update the print statement to read
print “<div>Thank you, $name, for your posting: <p> $posting…</p>
<p>($words words)</p></div>”;
5. Save the file, place it in the proper directory of you PHP-enabled browser.
Adjusting String Case
A handful of PHP functions are used to change the case of a string’s letters:
 ucfirst() capitalizes the first letter of the string.
 ucwords() capitalizes the first letter of words in a string.
 strtoupper() makes an entire string uppercase.
 strtolower() makes an entire string lowercase.

Replacing Parts of a String


Instead of just finding substrings within a string, you might find that you need to replace substrings
with new values. You can do so using the str_ireplace() function:
$string = str_ireplace($needle, $replacement, $haystack);
This function replace every occurance of $needle found in $haystack with $replacement. For
example:
$me = ‘Vijay D. Chouhan’;
$me = str_ireplace(‘D’, ‘Dinanath’,$me);
The $me variable now has a value of Vijay Dinanth Chouhan.
That function performs a case-insensitive search. To be more restrictive, you can perform a case-
sensitive search using str_replace().
To use str_ireplace() and trim()
1. Open handle_post.php.
2. Apply trim() to the form data:
$first_name = trim($_POST[‘first_name’]);
$last_name = trim($_POST[‘last_name’]);
$posting = trim($_POST[‘posting’]);

Developed By. Dr. Munesh Thakre Page 224 of 306


Web Engineering BE CSE SEM-VII

3. Before the print statement, add


$posting = str_ireplace(‘backward’, ‘xxxxx’, $posting);
4. Update the print statement so that it no longer uses the ellipses:
print “<div>Thank you, $name, for your posting:
<p>$posting</p>
<p>($words words)</p></div>”;
5. Save the file, place it in the proper directory of your PHP-enabled server and test again in
your browser.

Control Structure
Control structures – conditionals and loops – are a staple of programming languages. PHP has two
conditionals – if and switch. Conditionals allow you to establish a test and then perform actions
based on the results. This functionality provides the ability to make websites even more dynamic.
If conditionals require introduction of two last categories of operators: comparison and logical.
You’ll commonly use these operators in your conditionals, along with the Boolean concepts of
TRUE and FALSE.

Creating the HTML Form


The form is a simple registration page that requires the following information.
 Email address
 Password
 Confirmation of the Password
 Year of birth (to verify age)
 Favorite color (for customization purposes)
 Agreement to the site’s terms (a common requirement)
To create HTML Form
1. Begin a new HTML document in your text editor or IDE, to be named register.html.
2. Create the initial form tag.
3. Create inputs for the email address and passwords.
4. Create an input for the user’s birth year.
5. Create a drop-down menu for the user’s favorite color.
6. Create a checkbox for the user to agree to the site’s terms.
7. Add a submit button and close the form.
8. Complete the HTML page.

Developed By. Dr. Munesh Thakre Page 225 of 306


Web Engineering BE CSE SEM-VII

9. Save the file as register.html, place it in the proper directory for you PHP enabled server,
and load the page in your browser.
Register.html
<html lang = “en”>
<head>
<meta charset= “utf-8”>
<title>Registration Form</title>
</head>
<body>
<!—script register.html -->
<div><p>Please complete this form to register:</p>
<form action = “handle_reg.php” method= “post”>
<p>Email Address : <input type= “text” name= “email” size= “30”></p>
<p>Password : <input type= “password” name= “password” size= “20”></p>
<p>Confirm Password:<input type=“password” name=“confirm” size=“20”></p>
<p>YearYouWereBorn:<input type=“text” name=“year” value=“YYYY” size=“4”></p>
<p>Favorite Color:
<select name= “color”>
<option value= “”>Pick One</option>
<option value= “red”>Red</option>
<option value= “yellow”>Yellow</option>
<option value= “green”>Green</option>
<option value= “blue”>Blue</option>
</select></p>
<p><input type= “checkbox” name= “terms” value= “Yes”> I agree to the
terms (Whatever they may be). </p>
<input type= “submit” name= “submit” value= “Register”>
</form>
</body>
</html>

The if Conditional
The basic programming conditional is the standard if. The syntax for this kind of conditional is
simple:
if(condition)
{
Statement(s);
}
The condition must go within parentheses: then the statement(s) are placed within braces. The
statements are commands to be executed – for example, printing a string or adding two numbers

Developed By. Dr. Munesh Thakre Page 226 of 306


Web Engineering BE CSE SEM-VII

together. Each separate statement must have its own semicolon indicating the end of the line, but
there’s no limit on the number of statements that can be associated with a conditional.
To create an if conditional:
1. Begin a new document in your text editor of IDE, tobe named handle_reg.php.
2. Begin the PHP section and address error management, if necessary.
3. Create a flag variable:
$okay = true;
4. Print a message if everything is all right.
5. Complete the PHP section and the HTML page.
6. Save the file as handle_reg.php, place it in the proper directory for you PHP enabled server,
and test both in your browser.
Handle_reg.php
<html lang= “en”>
<head>
<title>Registration</title>
</head>
<body><h1>Registration Results</h1>
<?php
/*This script receives seven values from register.html: email,
password, confirm, year, terms, color, submit */
//Address error management, if you want
//Flag variable to track success:
$okay = true;
//If there were no errors, print a success message:
if($okay){
print “<p>You have been successfully registered (but not really).</p>”; }
?>
</body>
</html>

Validation Functions
PHP has dozens of functions commonly used to validate form data. Of these functions, three of the
most important ones are used.
First up is the empty() function, which checks to see if a given variable has an “empty” value. A
variable is considered to have an empty value if the variable has no value, has a value of 0, or has a
value of FALSE. In any of these cases, the function returns TRUE; otherwise, it returns FALSE:
$var1 = 0;
$var2 = ‘something’;

Developed By. Dr. Munesh Thakre Page 227 of 306


Web Engineering BE CSE SEM-VII

empty($var1);
Next is the isset() function, which is almost the opposite of empty(), albeit with a slight difference.
The isset() function return TRUE if a variable has any value. If the variable does not have a value,
isset() returns FALSE.
$var1=0;
$var2= “something”;
$var3= “”;
isset($var); //FALSE, no defined value
isset($var1); //TRUE
isset($var2); //TRUE
isset($var3); //TRUE
Finally, the is_numeric() function returns TRUE if the submitted variable has a valid numerical
value and FALSE otherwise. Integers, decimals, and even strings can all pass the is_numeric() test:
$var1=2309;
$var2= “80.23”;
$var3= “Bears”;
is_numeric($var1); //TRUE
is_numeric($var2); //TRUE
is_numeric($var3); //FALSE
An interesting thing to note is that using is_numeric() on a variable that doesn’t exist not only
returns FALSE, but also generates a warning. For this reason, you’ll often see isset() used along with
other validation functions like is_numeric().
Handle_reg.php
<html lang= “en”>
<head>
<meta charset = “utf-8”>
<title>Registration</title>
<style type= “text/css” media= “screen”>
.error { color:red; }
</style>
</head>
<body>
<h1>Registration Results</h1>
<?php
/*This script receives seven values from register.html: email,
password, confirm, year, terms, color, submit */
//Address error management, if you want
//Flag variable to track success:
$okay = true;
//Validate the email address:
if(empty($_POST[‘email’]))
{

Developed By. Dr. Munesh Thakre Page 228 of 306


Web Engineering BE CSE SEM-VII

print “<p class= “error”>Please entery your email address.</p>”;


$okay=false;
}
//Validate the password:
if(empty($_POST[‘password’]))
{
print “<p class= “error”>Please enter your password.</p>”;
$okay=false;
}
//If there were no errors, print a success message:
if($okay){
print “<p>You have been successfully registered (but not really).</p>”; }
?>
</body>
</html>
To validate form data:
1. Open handle_reg.php.
2. Within the document’s head, define a CSS class.
3. Validate the email address.
4. Repeate the validation for the password.
5. Save the file as handle_reg.php, place it in the same directory as register.html both the form
and the script your browser.
6. Resubmit the form in different states of completeness to test the result more.

Using else
This control structure allows you to execute one or more statements when a condition is TRUE and
execute one or more other statements when the condition is FALSE.
if(condition)
{
Statement(s)
}
else
{
Other_statements(s);
}
The important thing to remember when using this construct is that unless the condition is explicitly
met, the else statement will be executed. In other words, the statements after the else constitute the
default action, whereas the statements after the if condition are the exception to the rule.
To use else
Developed By. Dr. Munesh Thakre Page 229 of 306
Web Engineering BE CSE SEM-VII

1. Open handle_reg.php.
2. After the password validation but before the $okay conditional, begin a new conditional.
if(is_numeric($_POST[‘year’])){
3. Create a new variable:
$age = 2016 - $_POST[‘year’];
4. Add an else clause:
} else {
5. After the final print statement but within the same $okay conditional, also print out the value
of $age.
6. Save you script, place it in the same directory as register.html and test it in your browser
again.

Handle_reg.php
<html lang= “en”>
<head>
<title>Registration</title>
<style type= “text/css” media= “screen”>
.error { color:red; }
</style>
</head>
<body><h1>Registration Results</h1>
<?php
/*This script receives seven values from register.html: email,
password, confirm, year, terms, color, submit */
//Address error management, if you want
//Flag variable to track success:
$okay = true;
//Validate the email address:
if(empty($_POST[‘email’]))
{
print “<p class= “error”>Please entery your email address.</p>”;
$okay=false;
}
//Validate the password:
if(empty($_POST[‘password’]))
{
print “<p class= “error”>Please enter your password.</p>”;
$okay=false;
}
//Validate the birth year:

Developed By. Dr. Munesh Thakre Page 230 of 306


Web Engineering BE CSE SEM-VII

if(is_numeric($_POST[‘year’]))
{
$age = 2016 - $_POST[‘year’]; //calculate age this year.
}
else
{
print ‘<p class= “error”>Please enter the year you were born as four digits.</p>’;
$okay = false;
}
//If there were no errors, print a success message:
if($okay){
print “<p>You have been successfully registered (but not really).</p>”;
print “<p>You will turn $age this year.</p>”;}
?>
</body>
</html>
More Operators
PHP’s operators along with the variable types that use them. These operators include arithmetic for
numbers: addition(+), subtraction(-), multiplication(*), and division(/), along with the increament
(++) and decrement(--) shortcuts for increasing or decresing the value of number by 1.
Then there is the assignment operator(=), which is used to set the value of a variable, regardless of
type.
When it comes to creating conditionals, the comparison and logical operators are the most important.
Comparison
The line
$var=5;
Doesn’t state that $var is equal to 5 but that it is assigned the value of 5. This is an important
distinction.
When you’re writing conditionals, you’ll often want to see if a variable is equal to a specific value –
to match usernames or passwords, perhaps, which you can’t do with the equals sign alone. Instead
for comparisons, use the equality operator(==).
$var=5;
if($var==5)
{
….
}
To use comparison operators
1. Open handle_reg.php in you text editor or IDE, if it is not already open.

Developed By. Dr. Munesh Thakre Page 231 of 306


Web Engineering BE CSE SEM-VII

2. After the password validation, check that the two passwords match.
3. After the year validation, report an error if the year is greater than or equal to 2016.
4. Save your script, place it in the same directory as register.html and test it in you browser
again.
Handle_reg.php
<html lang= “en”>
<head>
<meta charset = “utf-8”>
<title>Registration</title>
<style type= “text/css” media= “screen”>
.error { color:red; }
</style>
</head>
<body><h1>Registration Results</h1>
<?php
/*This script receives seven values from register.html: email,
password, confirm, year, terms, color, submit */
//Address error management, if you want
//Flag variable to track success:
$okay = true;
//Validate the email address:
if(empty($_POST[‘email’]))
{
print “<p class= “error”>Please entery your email address.</p>”;
$okay=false;
}
//Validate the password:
if(empty($_POST[‘password’]))
{
print “<p class= “error”>Please enter your password.</p>”;
$okay=false;
}
//Check the two password for equality:
if($_POST[‘password’] != $_POST[‘confirm’])
{
print ‘<p class= “error”> Your confirmed password does not match the
original password.</p>’;
$okay = false;
}
//Validate the birth year:
if(is_numeric($_POST[‘year’])){
$age = 2016 - $_POST[‘year’]; //calculate age this year. }

Developed By. Dr. Munesh Thakre Page 232 of 306


Web Engineering BE CSE SEM-VII

else {
print ‘<p class= “error”>Please enter the year you were born as four
digits.</p>’;
$okay = false; }
//Check that they were born before this year
if($_POST[‘year’] >= 2016) {
print ‘<p class= “error”>Either you entered your birth year wrong or
you come from the future!</p>’;
$okay=false; }
//If there were no errors, print a success message:
if($okay) {
print “<p>You have been successfully registered (but not really).</p>”;
print “<p>You will turn $age this year.</p>”;
}
?>
</body>
</html>
Using else if
Similar to the if-else conditional is if-else if. This conditional acts like a running if statement and can
be expanded to whatever complexity you require:
if(condition1)
{
Statement(s);
}
else if(condition2)
{
Other_statement(s);
}
else
{
Other_other_statement(s);
}
Understand that this structure means, for example, that other_statement(s) are only executed if
condition1 is FALSE but condition2 is TRUE. If both conditions are FALSE, the
other_other_statement(s) are executed.
To use elseif
1. Open handle_reg.php.
2. Before the $okay conditional, begin a new conditional.
3. Add an elseif clause for the second color.
4. Add elseif clauses for the other two colors.

Developed By. Dr. Munesh Thakre Page 233 of 306


Web Engineering BE CSE SEM-VII

5. Add an else clause.


6. Within the $okay conditional, print the user’s favorite color type.
7. Save the script, place it in the same directory as register.html and test it in your browser
again.
Handle_reg.php
<html lang= “en”>
<head>
<meta charset = “utf-8”>
<title>Registration</title>
<style type= “text/css” media= “screen”>
.error { color:red; }
</style>
</head>
<body>
<h1>Registration Results</h1>
<?php
/*This script receives seven values from register.html: email,
password, confirm, year, terms, color, submit */
//Address error management, if you want
//Flag variable to track success:
$okay = true;
//Validate the email address:
if(empty($_POST[‘email’]))
{
print “<p class= “error”>Please entery your email address.</p>”;
$okay=false;
}
//Validate the password:
if(empty($_POST[‘password’]))
{
print “<p class= “error”>Please enter your password.</p>”;
$okay=false;
}
//Check the two password for equality:
if($_POST[‘password’] != $_POST[‘confirm’])
{
print ‘<p class= “error”> Your confirmed password does not match the
original password.</p>’;
$okay = false;
}
//Validate the birth year:
if(is_numeric($_POST[‘year’])) {

Developed By. Dr. Munesh Thakre Page 234 of 306


Web Engineering BE CSE SEM-VII

$age = 2016 - $_POST[‘year’]; //calculate age this year. }


else {
print ‘<p class= “error”>Please enter the year you were born as four
digits.</p>’;
$okay = false; }
//Check that they were born before this year
if($_POST[‘year’] >= 2016) {
print ‘<p class= “error”>Either you entered your birth year wrong or
you come from the future!</p>’;
$okay=false; }
//If there were no errors, print a success message:
if($okay) {
print “<p>You have been successfully registered (but not really).</p>”;
print “<p>You will turn $age this year.</p>”;
}
?>
</body>
</html>

The switch Conditional


Once you get to the point where you have longer if-elseif-else conditionals, you may find that you
can save programming time and clarify your code by using a switch conditional instead. The switch
conditional takes only one possible condition, normally just a variable:
switch($var)
{
case value1:
statement(s)1;
break;
case value2:
statement(s)2;
break;
default:
statement(s)3;
break;
}
You must understand how a switch conditional works in order to use it properly. After the keyword
switch, a variable is identified within parentheses. PHP will then look at each case in order, trying to
identify a matching value. Note that, as with any other use of strings and numbers in PHP, numeric
values would not be quoted; string values should be. After the case value section, a colon prefaces
the associated statements, which are normally indented beginning on the following line.

Developed By. Dr. Munesh Thakre Page 235 of 306


Web Engineering BE CSE SEM-VII

Once PHP finds a case that matches the value of the conditional variable, it executes the subsequent
statements. here’s the tricky part: Once PHP has found a matching case, it will continue going
through the switch until it either comes to the end of the switch conditional or hits a break
statement, at which point it exits the switch construct. Thus, it’s imperative that you close every case
even the default case, for consistency’s sake with a break.
To use a switch conditional
1. Open handle_reg.php in your text editor or IDE, if it is not already open.
2. Delete the extended colors conditional.
3. Begin the switch.
4. Create the first case.
5. Add a case for the second color.
6. Add cases for remaining colors.
7. Add a default case and complete the switch.
8. Save your script, place it in the same directory as regiseter.html and test it in your browser
again.
Handle_reg.php
<html lang= “en”>
<head>
<title>Registration</title>
<style type= “text/css” media= “screen”>
.error { color:red; } </style>
</head>
<body><h1>Registration Results</h1>
<?php
/*This script receives seven values from register.html: email,
password, confirm, year, terms, color, submit */
//Address error management, if you want
//Flag variable to track success:
$okay = true;
//Validate the email address:
if(empty($_POST[‘email’]))
{
print “<p class= “error”>Please entery your email address.</p>”;
$okay=false;
}
//Validate the password:
if(empty($_POST[‘password’]))
{

Developed By. Dr. Munesh Thakre Page 236 of 306


Web Engineering BE CSE SEM-VII

print “<p class= “error”>Please enter your password.</p>”;


$okay=false;
}
//Check the two password for equality:
if($_POST[‘password’] != $_POST[‘confirm’])
{
print ‘<p class= “error”> Your confirmed password does not match the
original password.</p>’;
$okay = false;
}
//Validate the birth year:
if(is_numeric($_POST[‘year’]) AND (strlen($_POST[‘year’]) ==4)
{
//Check that they were born before 2016
if($_POST[‘year’] < 2016)
{
$age = 2016 - $_POST[‘year’]; //calculate age this year.
}
else {
print ‘<p class= “error”>Either you entered your birth year
wrong or you come from the future!</p>’;
$okay = false;
}
}
else
{
print ‘<p class= “error”>Please enter the year you were born as four
digits.</p>’;
$okay = false;
}
//Validate the terms:
if(isset($_POST[‘terms’])) {
print ‘<p class= “error”> You must accept the terms.</p>’;
$okay = false; }
//Validate the color:
switch($_POST[‘color’])
{
case ‘red’:
$color_type = ‘primary’;
break;
case ‘yellow’:
$color_type = ‘primary’;
break;

Developed By. Dr. Munesh Thakre Page 237 of 306


Web Engineering BE CSE SEM-VII

case ‘green’:
$color_type = ‘secondary’;
break;
case ‘blue’:
$color_type = ‘primary’;
break;
default:
print ‘<p class = “error”>Please select your favorite
color.</p>’;
$okay=false;
break;
}
//If there were no errors, print a success message:
if($okay) {
print ‘<p> You have been Successfully registered (but not really).<p>’;
print “<p> You will turn $age this year.</p>”;
print “<p>Your favorite color is a $color_type color.<p>”;
}
?>
</body>
</html>

Break, Exit, Die, and Continue


PHP includes many language constructs – tools that aren’t functions but still do something in your
scripts. For example, print is a language construct. Another example is break, which is
demonstrated in the switch. A break exits the current structure, be it a switch, an if-else conditional,
or a loop.
Similar to this is continue, which terminates the current iteration of a loop. Any remaining
statements within the loop aren’t executed, but the loop’s condition is checked again to see if the
loop should be entered.
exit and die are more potent versions of break. Instead of exiting the current structure, these two
language constructs terminate the execution of the PHP script. Therefore, all PHP code after a use of
exit or die is never executed. For that matter, any HTML after these constructs is never sent to the
browser.

The for Loop


Loops are used to execute a section of code repeatedly. You may want to print something a certain
number of times, or you may want to do something with each value in an array. For either of these
cases, and many more, you can use a loop.

Developed By. Dr. Munesh Thakre Page 238 of 306


Web Engineering BE CSE SEM-VII

PHP supports three kinds of loops: for, while and foreach. The while loop is similar to for, but it’s
used most frequently when retrieving values from a database or reading from a text file. The foreach
loop is related to using arrays.
The for loop is designed to perform one or more statements for a determined number of iterations.
You normally use a dummy variable in the loop for this purpose:
for(initial expression; condition; closing expression)
{
Statement(s);
}
The initial expression is executed once: the first time the loop is called. Then the condition is used to
determine whether to execute the statements. The closing expression is executed each time the
condition is found to be TRUE, but only after the statements are executed.
To write a for loop
1. Open registration.html in your text editor or IDE, if it is not already open.
2. Remove the existing birth year prompt and input.
3. Where the birth year prompt was, after the password confirmation and before the color
option, add a prompt and a list of months.
4. Begin a select menu for the day of the month the user was born.
5. Create a new PHP section.
6. Create a for loop to print out 31 days as select menu options.
7. Close the PHP section, and the select element.
8. Save the file as register.php.
9. Place the file in the proper directory for your PHP enabled server.
10. If desired, view the HTML source code to see the PHP generated options.
Register.php
<html lang = “en”>
<head>
<meta charset= “utf-8”>
<title>Registration Form</title>
</head>
<body>
<div><p>Please complete this form the register:</p>
<form action = “handle_reg.php” method = “post”>
<p>Email Address: <input type= “text” name= “email” size= “30”></p>
<p>Password: <input type= “password” name= “password” size= “20”></p>
<p>Password: <input type= “password” name= “confirm” size= “20”></p>
<p>Date of Birth:

Developed By. Dr. Munesh Thakre Page 239 of 306


Web Engineering BE CSE SEM-VII

<select name= “month”>


<option value = “”>Month</option>
<option value= “1”>January</option>
<option value= “2”>February</option>
<option value= “3”>March</option>
<option value= “4”>April</option>
<option value= “5”>May</option>
<option value= “6”>Jun</option>
<option value= “7”>July</option>
<option value= “8”>Augest</option>
<option value= “9”>September/option>
<option value= “10”>October</option>
<option value= “11”>November</option>
<option value= “12”>December</option>
</select>
<select name= “day”>
<option value= “”>Day</option>
<?php //print out 31 days
for($i=1;$i<=31;$i++)
{
print “<option value=\ “$i\”>$i</option>\n”;
}
?>
</select>
<input type= “text” name= “year” value= “YYYY” size= “4”></p>
<p> Favorite Color:
<select name= “color”>
<option value= “”>Pick One</option>
<option value= “red”>Red</option>
<option value= “yellow”>Yellow</option>
<option value= “green”>Green</option>
<option value= “blue”>Blue</option>
</select></p>
<p><input type= “checkbox” name= “terms” value= “Yes”>I agree to
the terms (whatever they may be).</p>
<input type= “submit” name= “submit” value= “Register”>
</form>
</div>
</body>
<html>

The while loop

Developed By. Dr. Munesh Thakre Page 240 of 306


Web Engineering BE CSE SEM-VII

The second of the three types of loops that exist in PHP – the while loop – is designed to continue
working as long as the condition you establish is TRUE. Like the for loop, it checks the value of the
condition before each iteration. Once the condition becomes FALSE, the while loop is exited:
while(condition)
{
Statement(s);
}
The main difference between for and while is that while doesn’t include a system for setting initial
conditions or for executing closing expressions.
You also have the option of using the do..while loop, which guarantees that the statements are
executed at least once.
do
{
Statement(s);
}while(condition);

Using Arrays
Arrays are significantly different from numbers or strings, and you can’t make the most of
programming in PHP without understanding them.
Because of their unique nature, this section will cover arrays more deliberately and slowly than the
other variable types.

What is an Array
Arrays constitute a complicated but very useful notion. Whereas numbers and strings are scalar
variables – meaning they always have only a single value – an array is a collection of multiple values
assembled into one overriding variable. An array can consist of numbers and/or strings and/or other
arrays, which allows this one variable to hold exponentially more information than a simple string or
number can. For example, if you wanted to create a grocery list using strings, your code would look
something like this:
$item1 = ‘apples’;
$item2 = ‘bananas’;
$item3 = ‘oranges’;

Developed By. Dr. Munesh Thakre Page 241 of 306


Web Engineering BE CSE SEM-VII

For each added item, you’d need to create a new string. This approach is cumbersome, and it makes
it difficult to refer back to the entire list or any specific value. You can greatly simplify matters by
placing your entire list into one array.
As an array, your list can be added to, sorted, searched, and so forth. With this context in mind, let’s
look into the syntax of arrays.
Syntactical rules for arrays
The other variable types you’ve dealt with – numbers and strings – have a variable name and a
corresponding value. arrays also have a name, derived using the same conventions:
 They begin with a dollar sign.
 They continue with a letter or underscore.
 They finish with any combination of letters, numbers, or the underscore.
But arrays differ in that they contain multiple elements. An element consists of an index or key the
two words can be used interchangeably and a value.
An array’s index is used as a reference point to the values. An array can use either numbers or strings
as its keys, or both, depending on how you set it up.
Generally, when you use an array it looks the same as any other variable, except that you include a
key in brackets([], sometimes referred to as square brackets) to reference particular values. Whereas
$items refers to the array as a whole, $item[1] points to a specific element in the array.

Creating an Array
The formal method of creating an array is to use the array() function. Its syntax is
$list = array(‘apples’, ‘bananas’, ‘orange’);
Arrays automatically begin their indexing at 0, unless otherwise specified. In that example – which
doesn’t specify an index for the elements – the first item, apples, is automatically indexed at 0, the
second item at 1, and the third at 2.
If you desire, you can assign the index when using array().
$list = array(1=> ‘apples’, 2=> ‘bananas’, 3=> ‘orange’);
Because PHP is very liberal when it comes to blank spaces in your code, you can make this structure
easier to read by writing it over multiple lines:
$list = array(
1 => ‘apples’,
2 => ‘bannas’,
3 => ‘orange’
);

Developed By. Dr. Munesh Thakre Page 242 of 306


Web Engineering BE CSE SEM-VII

Create array using the short array syntax. Simply use brackets instead of a call to array():
$list = [‘apples’, ‘bananas’, ‘orange’];
Naturally, you can se the indexes with this syntax as well:
$list = [
1 => ‘apples’,
2 => ‘bannas’,
3 => ‘orange’
];
Finally, the index value you specify doesn’t have to be a number – you can use strings instead. As an
example, you could create an array that records the soup of the day for each day of the week, as in
the following script. This example will also demonstrate how you can, and cannot, print out an array.
To create an array
1. Begin a new document in your text editor or IDE, to be named soups1.php.
2. Being the PHP section of the script, and address error handling, if necessary.
3. Create an array.
4. Attempt to print the array.
5. Use the print_r() function to print out the array differently.
6. Close the PHP and the HTML section.
7. Save your document as soups1.php, place it in the proper directory for your PHP-enabled
server, and test it in you browser.
Soups1.php
<html lang = “en”>
<head>
<meta charset= “utf-8”>
<title>No Soup for You!</title>
</head>
<body>
<h1>Mmm….Soups</h1>
<?php
//This script creates and prints out an array
//Address error management, if you want
//Create the array
$soups = [
‘Monday’ => ‘Clam Chowder’,
‘Tuesday’ => ‘White Chicken Chili’,
‘Wednesday’ => ‘Vegetarian’
];
//Try to print the array

Developed By. Dr. Munesh Thakre Page 243 of 306


Web Engineering BE CSE SEM-VII

print “<p>$soups</p>”;
//Print the contents of the array
print_r($soups);
?>
</body>
</html>

Adding Items to an Array


In, PHP once an array exists, you can add extra elements to the array with the assignment operator,
in a way similar to how you assign a value to a string or a number. When doing so, you can specify
the key of the added element or not specify it, but in either case, you must refer to the array with
brackets.
Here’s a definition of the $list array:
$list = [
1 => ‘apples’,
2 => ‘bannas’,
3 => ‘orange’
];
To add two items to that, you’d write
$list[] = ‘pears’;
$list[] = ‘tomatoes’;
If you don’t specify the key, each element is appended to the existing array, indexed with the next
sequential number. Now pears is located 4 and tomatoes at 5.
If you do specify the index, the value is assigned at that location. Any existing value already indexed
at that point is overwritten, like so:
$list[3] = ‘pears’;
$list[4] = ‘tomatoes’;
Now, the value of the element in the fourth position of the array is tomatoes, and no element of $list
is equal to oranges. With this in mind, unless you intend to overwrite any existing data, you’ll be
better off not naming a specific key when adding values to you arrays. however, if the array uses
strings for indices, you’ll probably want to specific keys so that you don’t end up with an unusual
combination of string keys and numeric keys.

Deleting Arrays and Array Elements


You won’t frequently need to delete an individual item from an array, but it’s possible to do using
the unset() function. This function eliminates a variable and frees up to memory it used. When
applied to an array element, that element is deleted:

Developed By. Dr. Munesh Thakre Page 244 of 306


Web Engineering BE CSE SEM-VII

unset($array[4]);
unset($array[‘key’]);
Removing a single element will not re-index the array, however, the code removes one element, no
element is now indexed at 4, and every other element continue to be indexed where they were.
If you apply unset() to an entire array or any other variable type, the whole variable is deleted:
unset($array);
unset($string);
You can also reset an array using the array() function or short array syntax:
$array = array();
$array =[];
This has the effect of initializing the variable: making it exist and defining its type without assigning
a value.
To add elements to an array
1. Open soups1.php in you text editor or IDE, if it is not already open.
2. After the array is initialized on lines 14 through 18, add the following to be named
soups2.php.
3. Add three more elements to the array.
4. Recount how many elements are in the array, and print out this value.
5. Delete this line.
6. Save your script as soups2.php, place it in the proper directory for your PHP-enabled server,
and test it in your browser.
Soups2.php
<html lang = “en”>
<head>
<title>No Soup for You!</title>
</head>
<body>
<h1>Mmm….Soups</h1>
<?php
//This script creates and prints out an array
//Address error management, if you want
//Create the array
$soups = [
‘Monday’ => ‘Clam Chowder’,
‘Tuesday’ => ‘White Chicken Chili’,
‘Wednesday’ => ‘Vegetarian’
];

Developed By. Dr. Munesh Thakre Page 245 of 306


Web Engineering BE CSE SEM-VII

//Count and print the current number of elements


$count1 = count($soups);
print “<p>The soups array originally had $count1 elements.</p>”;
//Add three items to the array
$soups[‘Thursday’] = ‘Chiken Noodle’;
$soups[‘Friday’] = ‘Tomato’;
$soups[‘Saturday’] = ‘Cream of Broccoli’;
//Count and print the number of elements again
$count2 = count($soups);
print “<p>After adding 3 more soups, the array now has $count2
elements.</p>”;
//Print the contents of the array
print_r($soups);
?>
</body>
</html>

Merging Arrays
PHP has a function that allows you to append one array onto another. Think of it as concatenation for
arrays. The function array_merge(), work like so:
$new_array = array_merge($array1,$array2);
You could also write the soups2.php page using this function:
$soups2 = [
‘Thursday’ => ‘Chiken Noodle’,
‘Friday’ => ‘Tomato’,
‘Saturday’ => ‘Cream of Broccoli’
];
$soups = array_merge($soups, $soups2);
You could even accomplish this result with the plus sign:
$soups = $soups + $soups2;
Or
$soups += $soups2;
A difference between using array_merge() and the plus sign is that array_merge() will re-index the
arrays in the new array, whereas the plus sign maintains the existing indexes. Also, with array
addition, only elements in the second array indexed at new positions are added in. Any element in
the second array indexed at the same position as an element in the first array will be ignored.

Accessing Array Elements


Regardless of how you establish an array, there’s only one way to retrieve a specific element (or
value) from it, and that is to refer to its index:

Developed By. Dr. Munesh Thakre Page 246 of 306


Web Engineering BE CSE SEM-VII

print = “The first item is $array[0]”;


If the array uses strings for indexes, you must quote the index, which results in a problematic syntax
when you’re trying to print an individual array element.
print “<p>Monday’s soup is {$soups[‘Monday’]}.</p>”;
Ironically, the feature that makes arrays so useful – being able to store multiple values in one
variable – also gives it a limitation that the other variable types don’t have.
The fastest and easiest way to access all the values of an array is to use a foreach loop. This
construct loops through every element of an array:
foreach($array as $key => $value)
{
print “<p>Key is $key. Valueis $value</p>”;
}
With each iteration of the loop, the current array element’s key will be assigned to the $key variable
and te value to $value. Note that you can use any variable name here: $k and $v are likely choices,
too.
To print out the values of any array
1. Begin a new document in your text editor or IDE.
2. Start the PHP section of the page, and address error management, if needed.
3. Create the $soups array.
4. Create a foreach loop to print out each day’s soup.
5. Close the PHP section and the HTML page.
6. Save the page as soups3.php, place it in the proper directory for your PHP-enabled server,
and test it in you browser.
Soups3.php
<html lang = “en”>
<head>
<title>No Soup for You!</title>
</head>
<body><h1>Mmm….Soups</h1>
<?php
//This script creates and prints out an array
//Address error management, if you want
//Create the array
$soups = [
‘Monday’ => ‘Clam Chowder’,
‘Tuesday’ => ‘White Chicken Chili’,
‘Wednesday’ => ‘Vegetarian’

Developed By. Dr. Munesh Thakre Page 247 of 306


Web Engineering BE CSE SEM-VII

‘Thursday’ => ‘Chiken Noodle’,


‘Friday’ => ‘Tomato’,
‘Saturday’ => ‘Cream of Broccoli’
];
//Print each key and value
foreach($soups as $day => $soup)
{
print “<p>$day : $soup</p>\n”;
}
?>
</body>
</html>

Creating Multidimensional Arrays


Multidimensional arrays are both simple and complicated at the same time. The structure and
concept may be somewhat difficult to grasp, but creating and accessing multidimensional arrays in
PHP is surprisingly easy.
You use a multidimensional array to create an array containing more information than a standard
array. You accomplish this by using other arrays for values instead of just strings and numbers. For
example:
$fruits = [‘apples’, ‘bananas’, ‘oranges’];
$meats = [‘steaks’, ‘hamburgers’, ‘pork chops’];
$groceries = [
‘fruits’ => $fruits,
‘meats’ => $meats,
‘other’ => ‘peanuts’,
‘cash’ => 30.00
];
This array, $groceries, now consists of one string(peanuts), one floating-point number(30.00), and
two arrays($fruits and $meats).
Pointing to an element in an array within an array can seem tricky. The key is to continue adding
indexes in brackets as necessary, working from the outer array inward.
To use multidimensional arrays
1. Begin a new document in your text editor or IDE, to be named books.php.
2. Create the initial PHP tags, and address error management, if necessary.
3. Create the first array.
4. Create the next two array,
5. Create the main, multidimensional array.

Developed By. Dr. Munesh Thakre Page 248 of 306


Web Engineering BE CSE SEM-VII

6. Print out the name.


7. Print out two more examples.
8. Run the $books array through a foreach loop to see the result.
9. Close the PHP section and complete the HTML page.
10. Save the file as books.php, place it in the proper directory for your PHP enabled server, and
test it in your browser.
Books.php
<html lang= “en”>
<head>
<meta charset= “utf-8”>
<title>Larry Ullman’s Book and Chapters</title>
</head>
<body>
<h1>Some of Larry Ullman’s Books</h1>
<?php
//This script creates and prints out a multidimensional array
//Address error management, if you want
//Create the first array
$phpvqs = [1 => ‘Getting Started with PHP’, ‘Variables’, ‘HTML Forms and
PHP’, ‘Using Numbers’];
//Create the second array
$phpadv = [1 => ‘Advanced PHP Techniques’, ‘Developing Web
Applications’, ‘Advanced Database Concepts’, ‘Basic Object-Oriented
Programming’];
//Create the third array
$phpmysql = [1 => ‘Introduction to PHP’, ‘Programming with PHP’,
‘Creating Dynamic Web Sites’, ‘Introduction to MySQL’];

//Create the Multidimensional array


$books = [
‘PHP VQS’ => $phpvqs,
‘PHP Advanced VQP’ => $phpadv,
‘PHP and MySQL VQP’ => $phpmysql
];
//Print out some values
print “<p>The third chapter of my first book is<i>{$books[‘PHP VQS’]
[3]</i>.</p>”;
print “< p>The first chapter of my second book is <i>{$books[‘PHP
Advanced VQP’][1]</i>.</p>”;
print “<p>The fourth chapter of my fourth book is<i>{$books[‘PHP and
MySQL VQP’][4]</i>.</p>”;

Developed By. Dr. Munesh Thakre Page 249 of 306


Web Engineering BE CSE SEM-VII

//See what happens with foreach:


foreach($books as $book)
{
foreach($book as $key => $value)
{
print “<p>$key : $value</p>\n”;
}
}
?>
</body>
</html>

Sorting Arrays
PHP supports a variety of ways to sort an array. Sort refers to an alphabetical sort if the values being
sorted are strings, or a numerical sort if the value being sorted are numbers. When sorting an array,
you must keep in mind that an array consists of pairs of keys and values. Thus, an array can be sorted
based on the keys or the values. This is further complicated by the fact that you can sort the values
and keep the corresponding keys aligned, or you can sort the values and have them be assigned new
keys.
To sort the values without regard to the keys, use sort(). To sort these values in reverse order, use
rsort(). The syntax for every sorting function is:
function_name($array);
So, sort() and rsort() are used as follows:
sort($array);
rsort($array);
To sort the values while maintaining the correlation between each values and its key, use asort(). To
sort the values in reverse while maintaining the key correlation, use arsort().
To sort by the keys while maintaining the correlation between the key and its value, use ksort().
Conversely, krsort() sorts the keys in reverse.
Finally, shuffle() randomly reorganizes the order of an array. Like sort() and rsort(), shuffle() drops
the existing keys in the process.
To sort an array
1. Being a new document in your text editor or IDE, to be named sort.php.
2. Begin the PHP section, an address error handling, if desired.
3. Create the array.
4. Print caption, and then print each element of the array using a foreach loop.

Developed By. Dr. Munesh Thakre Page 250 of 306


Web Engineering BE CSE SEM-VII

5. Sort the array in reverse order by value to determine who has the highest grade.
6. Print the array again using another loop.
7. Sort the array by key to put the array in alphabetical order by student name.
8. Print a caption and the array one last time.
9. Complete the script with the standard PHP and HTML tags.
10. Save your script as sort.php, place it in the proper directory for your PHP-enabled server,
and test it in your browser.
Sort.php
<html lang = “en”>
<head>
<meta charset = “utf-8”>
<title>My Little Gradebook</title>
</head>
<body>
<?php
//This script creates, sorts, and print out an array
//Address error management, if you want
//Create the array
$grades = [
‘Richard’ => 95,
‘Sherwood’ => 82,
‘Toni’ => 98,
‘Franz’ => 87,
‘Melissa’ => 75,
‘Roddy’ => 85
];
//Print the original array
print ‘<p>Originally the array looks like this:<br>”;
foreach($grades as $student => $grade)
{
print “$student: $grade<br>”;
}
print ‘<p>’;
//Sort by value in revseorder, then print again
arsort($grades);
print ‘<p>After sorting the array by value using arsort(), the array
looks like this:</p>’;
foreach($grades as $student => $grade)
{
print “$student: $grade<br>”;
}

Developed By. Dr. Munesh Thakre Page 251 of 306


Web Engineering BE CSE SEM-VII

print ‘<p>’;
//Sort by key, then print again
ksort($grades);
print ‘<p>After sorting the array by key using ksort(), the array
looks like this:</p>’;
foreach($grades as $student => $grade)
{
print “$student: $grade<br>”;
}
print ‘<p>’;
?>
</body>
</html>

Creating Web Applications


Creating Templates
 Every example thus far has been a one-page script that handles an HTML form, sorts arrays,
performs calculations, and so on.
 As you begin to develop multiple page website, it quickly becomes impractical to repeat
common elements on multiple pages.
 On more sophisticated websites, many features, such as the HTML design, will be used by
every, or almost every, page within the site.
 You can put these elements into each page, but when you need to make a change, you’ll be
required to make that change over and over again.
 You can save time by creating templates that separate out the repeating content from the page
specific materials.
 For example, a website may have navigation, copyright, and other features that repeat across
multiple pages.
 When you first start doing dynamic web development, creating and using templates can be
daunting.
 The key is to start with a basic prototype, as if you were creating a static web page, and then
divide that prototype into reusable parts.
To create the layout model
1. Begin a new HTML document in your text editor or IDE, to be named template.html.

Developed By. Dr. Munesh Thakre Page 252 of 306


Web Engineering BE CSE SEM-VII

2. Add the CSS code.


3. Chose the HTML head, and begin the body.
4. Create the page’s header.
5. Begin, and mark, the start of the page specific content.
6. Create the page’s content.
7. Mark the end of the changeable content.
8. Add the footer.
9. Finish the HTML page.
10. Save the file as template.html, and test it in your browser.

Template.html
<html>
<head>
<meta charset= “utf-8”>
<meta http-equiv= “X-UA-Complatble” content = “IE=edge, chrome=1”>
<meta name= “viewport” content= “width=device-width, initial-scale=1.0”>
<meta name= “HandleidFriendly” content= “True”>
<title> Raise High the Roof Beam!</title>
<link rel=“stylesheet” type=“text/css” media= “screen” href= “css/concise.min.css”/>
<link rel= “stylesheet” type= “text/css” media= “screen” href= “css/masthead.css”/>
</head>
<body>
<header container class= “siteHeader”>
<div row>
<h1 column=4 class= “logo”><a href= “index.php”>Raise High the
Roof Beam!</a></h1>
<nav column= “8” class= “nav”>
<ul>
<li><a href= “books.php”>Books</a></li>
<li><a href= “#”>Stories</a></li>
<li><a href= “#”>Quotes</a></li>
<li><a href= “login.php”>Login</a></li>
<li><a href= “register.php”>Register</a></li>
</ul>
</nav>
</div>
</header>
<main container class= “siteContent”>
<!—BEGIN CHANGEABLE CONTENT. -->

Developed By. Dr. Munesh Thakre Page 253 of 306


Web Engineering BE CSE SEM-VII

<h2>Welcome to a J.D. Salinger Fan Club</h2>


<p>Lorem ipsum dolar sit amet, consectetur adipisicing elit, sed to eiusmod
tempor incididunt ut labore et dolore magna aligqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in
voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
sint occaecat cupidatat non provident, sunt in culpa qui official
deserunt mollit anim id est laborum.
</p> <!—END CHANGEABLE CONTENT -->
</main>
<footer container class= “siteFooter”>
<p>Design uses <a href= “http://concisecss.com/”>Concise CSS Framework</a></p>
</footer>
</body>
</html>
To create the header file
1. Open template.html in you text editor or IDE, if it isn’t already open.
2. Select everything from the initial HTML code to the <!—BEGIN CHANGEABLE
CONTENT --> HTML comment.
3. Copy this code.
4. Create a new, blank document in your text editor or IDE, to be named header.html.
5. Paste the copied text into the document.
6. Save the file as header.html.
Header.html
<html>
<head>
<meta charset= “utf-8”>
<title> Raise High the Roof Beam!</title>
</head>
<body>
<header container class= “siteHeader”>
<div row>
<h1 column=4 class= “logo”><a href= “index.php”>Raise High the
Roof Beam!</a></h1>
<nav column= “8” class= “nav”>
<ul>
<li><a href= “books.php”>Books</a></li>
<li><a href= “#”>Stories</a></li>
<li><a href= “#”>Quotes</a></li>
<li><a href= “login.php”>Login</a></li>
<li><a href= “register.php”>Register</a></li>

Developed By. Dr. Munesh Thakre Page 254 of 306


Web Engineering BE CSE SEM-VII

</ul>
</nav>
</div>
</header>
<main container class= “siteContent”>
<!—BEGIN CHANGEABLE CONTENT. -->
<!-- Script:header.html -->
<!-- Script : footer.html -->
<!—END CHANGEABLE CONTENT -->
</main>
<footer container class= “siteFooter”>
<p>Design uses <a href= “http://concisecss.com/”>Concise CSS Framework</a></p>
</footer>
</body>
</html>
To create the footer file
1. Open template.html in your text editor or IDE, if it isn’t already open.
2. Select everything from the <!—END CHANGEABLE CONTENT -->HTML comment to the
end of script.
3. Copy this code.
4. Create a new, blank document in your text editor, to be named footer.html.
5. Paste the coped text into the document.
6. Save the file as footer.html.
Using External Files
As the preceding section stated, you can save development time by creating separate pages for
particular elements and then incorporating them into the main PHP pages using specific functions.
Two of these functions are include() and require():
include(‘file.php’);
require(‘file.html’);
Both functions work the same way, with one relatively key differences: if an include() function fails,
the PHP script generates a warning but continues to run. Conversely, if require() fails, it terminates
the execution of the script.
Both include() and require() incorporate the referenced file into the main file. The result is the same
as if the included code were part of the parent file in the first place.
Understanding this basic idea is key to making the most of external files: including a file makes it as
if that file’s contents were in the parent script to begin with. This means that any code within the

Developed By. Dr. Munesh Thakre Page 255 of 306


Web Engineering BE CSE SEM-VII

included file not within PHP tags is treated as HTML. And this is true regardless of what extension
the included file has, because it’s the extension of the including file that counts.
There are many reasons to use included files. You could put your own defined functions into a
common file. You might also want to place your database access information into a configuration
file. First, however, let’s include the template files created in the preceding section of the chapter in
order to make pages abide by a consistent design.
To use external files
1. Create a new document in your text editor or IDE, to be named index.php.
2. Start with the initial PHP tags, and add any comments.
3. Address error management, if necessary.
4. Include the header file.
5. Close the PHP section, and create the page specific content.
6. Create another PHP section, and include the footer file.
7. Save the file as index.php.
8. Create a folder named templates within the main web document directory on your PHP-
enabled computer or server.
9. Place header.html and footer.html in the templates directory you just created.
10. Place index.php in the same directory as the templates folder.
11. Create a folder named css within the main web document directory on your PHP-enabled
computer or server.
12. Place the concise.min.css and masthead.css scripts, available as part of the book’s
downloadable code, in the css directory.
13. Run index.php in your browser.
14. View the page’s source code in your browser.
Index.php
<?php
//This is the home page for this site. It uses templates to create the layout.
//Include the header:
include(‘templates/header.html’);
//Leave the PHP section to display lot of HTML
?>
<h2>Welcom to a J.D. Salinger Fan Club!</h2>
<p>Lorem ipsum dolar sit amet, consectetur adipisicing elit, sed to eiusmod tempor incididunt ut
labore et dolore magna aligqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint

Developed By. Dr. Munesh Thakre Page 256 of 306


Web Engineering BE CSE SEM-VII

occaecat cupidatat non provident, sunt in culpa qui official deserunt mollit anim id est
laborum.
</p>
<?php
include(‘templates/footer.html’);
//include the footer
?>
Using Constants
Many of PHP’s data types have already been discussed, primarily: numbers, strings, and arrays.
Constants are another data type, but unlike variables, their values cannot change.
Whereas variables are assigned values via the assignment operator(=), constants are assigned values
using the define() function:
define(‘CONSTANT_NAME’, value);
Notice that as a rule of thumb constants are named using all capital letters, although doing so isn’t
required. Most important, constants don’t use the initial dollar sign as variables do, because constants
are not variables. Here are two constants:
define(‘PI’, 3.14);
define(‘CURRENCY’, ‘euros’);
As with any value, quotes those that are strings, not those that are numbers. Referring to constants is
generally straightforward:
print CURRENCY;
number_format(PI,1);
But using constants within quotation marks is more complicated. You can’t print constants within
single or double quotation marks, like this:
print “The cost is 468 CURRENCY”;
print ‘The cost is 468 CURRENCY’;
Instead, concatenation or multiple print statements are required:
print ‘The cost is 468’, CURRENCY;
or
print ‘The cost is 468’;
print CURRENCY;
To use constants
1. Create a new PHP document in your text editor or IDE, to be named books.php.
2. Define the page title as a constant.
3. Include the header file.

Developed By. Dr. Munesh Thakre Page 257 of 306


Web Engineering BE CSE SEM-VII

4. Close the PHP section, and create the HTML.


5. Create a new PHP section that includes the footer file.
6. Save the file as books.php.
To print out a constant
1. Open header.html in your text editor or IDE.
2. Delete the Raise High the Roof Beam! Text that appears between the title tags.
3. In the place of the deleted text.
<?php //print the page title.
if (defined(‘TITLE’)) //Is the title defined?
{
print TITLE;
}
else //The title is not defined
{
print ‘Raise High the Roof Beam! A. J.D. Salinger Fan Club’;
}
?>
4. Save the file as header.html.
5. Upload books.php and header.html to your PHP-enabled server. The new PHP-script,
books.php, should go in the same directory as index.php; header.html should replace the
previous version, in the same directory – templates – as footer.html.
6. Run books.php in your browser.
7. View index.php in your browser.
8. If you want, add the constant definition line to index.php to change its title.
Books.php
<?php
//This page lists J.D. Salinger’s bibliography.
//Set the page title and include the header file.
define(‘TITLE’, ‘Books by J.D. Salinger’);
include(‘templates/header.html’);
//Leave the PHP section to display lots of HTML
?>
<h2>J.D. Salinger’s Books</h2>
<ul>
<li>The Catcher in the Rye</li>
<li>Nine Stories</li>
<li>Franny and Zooey</li>
<li>Raise High the Roof Beam, Carpenters and Seymour: An Introduction</li>
</ul>
<?php

Developed By. Dr. Munesh Thakre Page 258 of 306


Web Engineering BE CSE SEM-VII

include(‘templates/footer.html’);
?>
Header.html
<html>
<head>
<meta charset= “utf-8”>
<meta http-equiv= “X-UA-Complatble” content = “IE=edge, chrome=1”>
<meta name= “viewport” content= “width=device-width, initial-scale=1.0”>
<meta name= “HandleidFriendly” content= “True”>
<title>
<?php //print the page title.
if (defined(‘TITLE’)) //Is the title defined?
{
print TITLE;
}
else //The title is not defined
{
print ‘Raise High the Roof Beam! A. J.D. Salinger Fan Club’;
}
?>
</title>
<link rel=“stylesheet” type=“text/css” media= “screen” href= “css/concise.min.css”/>
<link rel= “stylesheet” type= “text/css” media= “screen” href= “css/masthead.cs”/>
</head>
<body>
<header container class= “siteHeader”>
<div row>
<h1 column=4 class= “logo”><a href= “index.php”>Raise High the
Roof Beam!</a></h1>
<nav column= “8” class= “nav”>
<ul>
<li><a href= “books.php”>Books</a></li>
<li><a href= “#”>Stories</a></li>
<li><a href= “#”>Quotes</a></li>
<li><a href= “login.php”>Login</a></li>
<li><a href= “register.php”>Register</a></li>
</ul>
</nav>
</div>
</header>
<main container class= “siteContent”>
<!—BEGIN CHANGEABLE CONTENT. -->
<!-- Script:header.html -->

Developed By. Dr. Munesh Thakre Page 259 of 306


Web Engineering BE CSE SEM-VII

<!-- Script : footer.html -->


<!—END CHANGEABLE CONTENT -->
</main>
<footer container class= “siteFooter”>
<p>Design uses <a href= “http://concisecss.com/”>Concise CSS Framework</a></p>
<p class= “float-right”>
<?php //Print the current date and time… set the timezone
date_default_timezone_set(‘America/New_York’);
//Now print the date and time:
print date(‘g:I a l F j’);
?>
</p>
</footer>
</body>
</html>

Working with the Date and Time


PHP has a few functions for working with the date and time, the most important of which is date().
The only thing the date() function does is return date and time information in a format based on the
arguments it’s fed, but you’d be surprised how useful that can be. The basic usage of the date()
function is just:
date(‘formatting’);
A long list of possible options is available for formatting. These parameters can also be combined –
for example, date(‘l F j Y’); returns Friday January 26, 2018.
Character Meaning Example
Y Year as 4 digits 2018
y Year as 2 digits 18
L Is it a leap year? 1(for yes)
n Month as 1 or 2 digit 2
m Month as 2 digits 02
F Month February
M Month as 3 letters Feb
j Day of the month as 1 or 2 8
d Day of month as 2 digits 08
l Day of the week Monday
D Day of week as 3 letters Mon
w Day of week as a single digit 0(Sunday)
z Day of this year 0 to 365 26
t Number of days in month 31

Developed By. Dr. Munesh Thakre Page 260 of 306


Web Engineering BE CSE SEM-VII

S English ordinal suffix for a day, as 2 characters 26th


g Hour: 12-hour format as 1 or 2 digits 6
G Hour: 24-hour format as 1 or 2 digits 18
h Hour: 12-hour format as 2 digits 06
H Hour: 24-hour format as 2 digits 18
i Minutes 45
s Seconds 18
u Microseconds 1234
a am or pm am
A AM or PM PM
U Seconds since the epoch 104823008
e Time zone UTC
I Is it daylight savings? 1(for yes)
O Difference from GMT +0600
To use date()
1. Open footer.html in your text editor or IDE.
2. After the Concise CSS Framework mention, add the following <p><?php.
3. Establish the time zone.
4. Use the date() function to print out the current date and time.
5. Close the PHP section, and finish the HTML code.
6. Save the file as footer.html, place it in the templates directory of your PHP enabled server,
and test it in your browser.

Handling HTML Forms with PHP


All the examples we have seen so far have used two separate scripts for handing HTML forms: one
that displayed the form and another that received and processed the form’s data. There’s certainly
nothing wrong with this method, but coding the entire process in one script has its advantages. To
make a page both display and handle a form, use a conditional statement:
if(/*form has been submitted*/)
{
//handle the form
}
else
{
//display the form
}
There are many ways to determine if a form has been submitted. One option is to check whether any
of the form’s variables are set:
if(isset($_POST[‘something’])){…

Developed By. Dr. Munesh Thakre Page 261 of 306


Web Engineering BE CSE SEM-VII

However, if the user submitted the form without completing it, that variable may not be set. A more
reliable solution is to add a hidden input to a form so that it can be checked:
<input type= “hidden” name= “submitted” value= “true”>
Again, the only purpose of this hidden input is to reliably indicate that the form has been submitted,
even if the user did nothing to complete the form.
To use one page to display and handle a form
1. Begin a new PHP document in your text editor or IDE, to be named login.php.
2. Define the page title as a constant and include the header file.
3. Add some introductory text.
4. Begin the conditional to check whether the form has been submitted.
5. Create a nested pair of conditional to process the form data.
6. Complete the main conditional.
7. Require the footer file, and complete the PHP page.
8. Save the file as login.php, place it in the same directory as index.php and test it in you
browser.
Login.php
<?php
//This page lets people log into the site
//Set the page title and include the header file.
define(‘TITLE’, ‘Login’);
include(‘templates/header.html’);
//print some introductory text
print ‘<h2>Login Form</h2>
<p>Users who are logged in can take advantage of certain features like this, that, and
the other thing.</p>’;
//Check if the form has been submitted :
if($_SERVER[‘REQUEST_METHOD’] == ‘POST’)
{
//Handle the form
if((!empty($_POST[‘email’])) && (!empty($_POST[‘password’])))
{
if((strlower($_POST[‘email’]) == ‘me@example.com’) && ($_POST[‘password’]==‘testpass’))
{ //correct
print ‘<p class= “text – success”>You are logged in!<br> Now you can
blah, blah, blah … </p>’;
}
else
{ //Incorrect

Developed By. Dr. Munesh Thakre Page 262 of 306


Web Engineering BE CSE SEM-VII

print ‘<p class= “text – error”> The submitted email address and
password do not match those on file!<br> Go back and try again.</p>’;
}
}
else
{ //Forgot a field
print ‘<p class= “text – error”>Please make sure you enter both an email
address and a password!<br>Go back and try again.</p>’;
}
}
else
{ //Display the form
print ‘<form action= “login.php” method= “post” class= “form – inline”>
<p><label for= “email”>Email Address:</label><input type= “email” name=
“email” size= “20”></p>
<p><label for= “password”>Password : </label><input type= “password”
name= “password” size= “20”></p>
<p><input type= “submit” name= “submit” value= “log In!” class= “button— pill”></p>
</form>’;
}
include(‘template/footer.html’); //Need the footer
?>

Cookies and Sessions


What is Cookies?
Prior to the existence of cookies, traversing a website was a trip without a history. Although the
browser tracks the pages you visit, allowing you to use the Back button to return to previously visited
pages and indicating visited links in a different color, the server does not follow what individual user
see and do. This is still true for sites that don’t use cookies, as well as for users who have disabled
cookies in their web browsers.
 Allow local data to be set(recommended).
 Keep local data only until you quit your browser.
 Block sites from setting any data.
 Block third-party cookies and site data.
Most browsers let users set the cookie handling preferences. In Internet Explorer 11, you will find
this in the Advanced Privacy Settings area.
Debugging cookies

Developed By. Dr. Munesh Thakre Page 263 of 306


Web Engineering BE CSE SEM-VII

When you begin working with cookies in PHP, you’ll need to know how to debug your cookies
related scripts when difficulties arise. Three areas might cause you problems:
 Sending the cookie with PHP.
 Receiving the cookies in your browser.
 Accessing a cookie in a PHP script.

Creating Cookies
An important thing to understand about cookies is that they must be sent from the server to the client
prior to any other information. This means a script should send cookies before any print statement,
before including an external file that contains HTML, and so forth.
Should the server attempt to send a cookie after the web browser has already received HTML – even
an extraneous white space –an error message will result and the cookies won’t be sent. This is by far
the most common cookie-related error.
Cookies are sent using the setcookie() function:
setcookie(name,value);
setcookie(‘CookieName’, ‘This is the cookie value’);
You can continue to send more cookies to the browser with subsequent uses of the setcookie()
function, although you’re limited by the browser as to how many cookies can be sent from the same
site:
setcookie(‘name2’, ‘some value’);
setcookie(‘name3’, ‘another value’);
There’s no universal, hard limit as to how many cookies a browser will accept from one site, but you
should keep the number to a minimum.
Finally, when creating cookies, you can-as you’ll see in this example – use a variable for the name or
value attribute of your cookies:
setcookies($cookie_name, $cookie_value);
To send cookies:
1. Create a new PHP document in your text editor or IDE, to be named customize.php.
2. Check whether the form has been submitted.
3. Create the cookies:
setcookie(‘font_size’, $_POST[‘font_size’]);
setcookie(‘font_color’, $_POST[‘font_color’]);

Developed By. Dr. Munesh Thakre Page 264 of 306


Web Engineering BE CSE SEM-VII

These two lines create two separate cookies. One is named font_size and the other
font_color. Their values will be based on the selected values from the HTML form, which
are stored in the $_POST[‘font_size’] and $_POST[‘font_color’] variables.
4. Create a message and complete the conditional and the PHP section:
$msg = ‘<p> Your settings have been entered! Now see them <a href=
“view_settings.php”> in action</a>.</p>’;
When the form has been submitted, the cookies will be sent and the $msg variable will be
assigned a string value. This variable will be used later in the script to print a message.
5. Create the HTML head and opening body tag.
6. Create another PHP section to report on the cookies being sent:
<?php
if(isset($msg))
{
print $msg;
}
?>
7. Being the HTML form.
8. Complete the HTML form.
9. Complete the HTML page.
10. Save the file as customize.php, and place it in the proper directory for your PHP enabled
server.
11. Make sure you’ve set your browser to prompt for each cookie, if possible.
12. Run the script in your browser.
Customize.php
<?php
//Handle the form if it has been submitted
if(isset($_POST[‘font_size’], $_POST[‘font_color’]))
{
//send the cookies
setcookies(‘font_size’, $_POST[‘font_size’]);
setcookies(‘font_color’, $_POST[‘font_color’]);
//Message to be printed later:
$msg = ‘<p> Your settings have been entered! Now see them <a href=
“view_seeting.php”> in action</a>.</p>’;
}
?>
<!doctype html>
<html lang= “en”>
<head>

Developed By. Dr. Munesh Thakre Page 265 of 306


Web Engineering BE CSE SEM-VII

<meta charset= “utf-8”>


<title>Customize Your Settings </title>
</head>
<body>
<?php
//if the cookies were sent, print a message
if(isset($msg))
{
print $msg;
}
?>
<p>Use this form to set your preferences:</p>
<form action= “customize.php” method= “post”>
<select name= “font_size”>
<option value= “”>Font Size</option>
<option value= “xx-small”>xx-small</option>
<option value= “x-small”>x-small</option>
<option value= “small”>small</option>
<option value= “medium”>medium</option>
<option value= “large”>large</option>
<option value= “x-large”>x-large</option>
<option value= “xx-large”>xx-large</option>
</select>
<select name= “font_color”>
<option value= “”>Font Color</option>
<option value= “999”>Gray</option>
<option value= “oco”>Green</option>
<option value= “oof”>Blue</option>
<option value= “coo”>Red</option>
<option value= “ooo”>Black</option>
</select>
<input type= “submit” name= “submit” value= “Set My Preferences”>
</form>
</body>
</html>
View_settting.php
<!doctype html>
<html lang= “en”>
<head>
<meta charset= “utf-8”>
<title>View Your Setting</title>
<style type= “text/css”>
body

Developed By. Dr. Munesh Thakre Page 266 of 306


Web Engineering BE CSE SEM-VII

{
<?php
//check for a font_size value
if(isset($_COOKIE[‘font_size’]))
{
print “\t\tfont_size:”.htmlentities($_COOKIE[‘font_size’]).“;\n”;
}
else
{
print(“\t\tfont_size: medium:”;
}
//check for a font_color value
if(isset($_COOKIE[‘font_color’]))
{
print “\t\tcolor: #”.htmlentities($_COOKIE[‘font_color’]).“;\n”;
}
else
{
print “\t\tcolor: #000;”;
}
?>
}
</style>
</head>
<body>
<p><a href= “customize.php”>Customize Your Settings</a></p>
<p><a href= “reset.php”>Reset Your Settings</a></p>
<p>yadda yadda yadda yadda yadda
yadda yadda yadda yadda yadda
yadda yadda yadda yadda yadda
yadda yadda yadda yadda yadda
yadda yadda yadda yadda yadda
</p>
</body>
</html>

Reading from Cookies


Just as form data is stored in the $_POST array and values passed to a script in the URL are stored in
the $_GET array, the setcookie() function places cookie data in the $_COOKIE array. To retrieve a
value from a cookie, you only need to refer to the cookie name as the index of this array. For
example, to retrieve the value of the cookie established with the line:
setcookie(‘user’, ‘trout’);

Developed By. Dr. Munesh Thakre Page 267 of 306


Web Engineering BE CSE SEM-VII

you would use the variable


$_COOKIE[‘user’].
Unless you change the cookie’s parameters, the cookie will automatically be accessible to every
other page in your web application. You should understand, however, that a cookie is never
accessible to a script immediately after it’s been sent. You can’t do this:
setcookie(‘user’, ‘trout’);
print $_COOKIE[‘user’]; //No value
The reason for this is the order in which cookies are read and sent.
To see how simple it is to access cookie values, let’s write a script that uses the preferences set in
customize.php to specify the page’s text size and color. The script relies on CSS to achieve this
effect.
To retrieve cookie data with PHP
1. Begin a new PHP document in your text editor or IDE, to be named view_setting.php.
2. Start the CSS section.
3. Open a section PHP code.
4. Use the font size cookie value, if it exists.
5. Repeat this process for the font color cookie.
6. Close the PHP section, complete the CSS code, and finish the HTML head.
7. Start the HTML body, and create links to two other pages.
8. Add some text.
9. Complete the HTML page.
10. Save the file as view_settings.php. place it in the same directory as customize.php, and test
it in your browser by clicking the link on customize.php.
11. View the source of the page to see the resulting CSS code.
12. Use the customize page to change your settings and return to this script.

Adding Parameters to a Cookie


Although passing just the name and value arguments to the setcookie() function will suffice for most
of your cookie uses, you ought to be aware of the other arguments available. The function can take
up to five more parameters, each of which limits the operation of the cookie.
setcookie(name, value, expiration, path, domain, secure, httponly);
The expiration argument is used to set a specific length of time for a cookie to exist. If it isn’t
specified, the cookie will continue to be functional until the user closes the browser. Normally, you

Developed By. Dr. Munesh Thakre Page 268 of 306


Web Engineering BE CSE SEM-VII

set the expiration time by adding a particular number of minutes or hours to the current time. You
can find the current time in PHP by using the time() function. Therefore, this line of code sets the
expiration time of the cookie to be one hour from the current movement.
setcookie(name, value, time()+36000);
Because theexpiration time will be calculated as the value of time() plus 36000, that argument isn’t
put in quotes.
The path and domain arguments are used to limit a cookie to a specific folder in a website – the path
– or to a specific domain. Using the path option, you could limit a cookie to exist only while a user
is in a specific subfolder of the domain:
setcookie(name, value, time()+3600, ‘/subfolder/’);
Cookies are already specific to a domain, so the domain argument might be used to limit a cookie to
a subdomain, such as forum.example.com:
setcookie(name, value, time()+3600, ‘ ’, ‘forum.example.com’);
The secure value dictates that a cookie should only be sent over a secure HTTPS connection. A
value of 1 indicates that a secure connection must be used, whereas 0 indicates that a secure
connection isn’t necessary. You could ensure a secure cookie transmission for e-commerce sites:
setcookies(‘cart’, ‘82ABC3012’, time()+3600, ‘’, ‘shop.example.com’,1);
To set a cookie’s expiration date
1. Open customize.php in your text editor of IDE.
2. Change the two setcookie() lines to read as follows:
setcookie(‘font_size’,$_POST[‘font_size’], time()+10000000, ‘/’, ‘’, 0);
3. Save the file, place it in the proper directory for your PHP enabled server, and test it again in
your PHP enabled server, and test it again in your browser.
Customize.php
<?php
//Handle the form if it has been submitted
if(isset($_POST[‘font_size’], $_POST[‘font_color’]))
{
//send the cookies
setcookies(‘font_size’, $_POST[‘font_size’], time()+10000000, ‘/’);
setcookies(‘font_color’, $_POST[‘font_color’], time()+10000000, ‘/’);
//Message to be printed later:
$msg = ‘<p> Your settings have been entered! Now see them <a href=
“view_seeting.php”> in action</a>.</p>’;
}
?>

Developed By. Dr. Munesh Thakre Page 269 of 306


Web Engineering BE CSE SEM-VII

<!doctype html>
<html lang= “en”>
<head>
<meta charset= “utf-8”>
<title>Customize Your Settings </title>
</head>
<body>
<?php
//if the cookies were sent, print a message
if(isset($msg))
{
print $msg;
}
?>
<p>Use this form to set your preferences:</p>
<form action= “customize.php” method= “post”>
<select name= “font_size”>
<option value= “”>Font Size</option>
<option value= “xx-small”>xx-small</option>
<option value= “x-small”>x-small</option>
<option value= “small”>small</option>
<option value= “medium”>medium</option>
<option value= “large”>large</option>
<option value= “x-large”>x-large</option>
<option value= “xx-large”>xx-large</option>
</select>
<select name= “font_color”>
<option value= “”>Font Color</option>
<option value= “999”>Gray</option>
<option value= “oco”>Green</option>
<option value= “oof”>Blue</option>
<option value= “coo”>Red</option>
<option value= “ooo”>Black</option>
</select>
<input type= “submit” name= “submit” value= “Set My Preferences”>
</form>
</body>
</html>

Deleting a Cookies
The final thing to know about cookies is how to delete them. Although a cookie automatically
expires when the user’s browser is closed or when the expiration date/time is met, sometimes you’ll

Developed By. Dr. Munesh Thakre Page 270 of 306


Web Engineering BE CSE SEM-VII

want to manually delete the cookies as well. For example, websites that have registered users and
login capabilities delete any created cookies when the user logs out.
The setcookies() function can take up to seven arguments, but only one is required the name. If you
send a cookie that consists of a name without a value, it will have the same effect as deleting the
existing cookie of the same name. For example, to create the cookie username, you use this line:
setcookie(‘username’, ‘Larry’);
To delete the username cookie, you code
setcookie(‘username’, ‘’);
or
setcookie(‘username’, FALSE);
As an added precaution, you can also set an expiration date that’s in the past.
setcookie(‘username’, FALSE, time()-6000);
The only caveat when it comes to deleting a cookie is that you must use the same argument values
that were used to set the cookie in the first place, aside from the value and expiration. For example, if
you set a cookie while providing a domain value, you must also provide that value when deleting the
cookie:
setcookie(‘user’, ‘larry’, time()+3600, ‘’, ‘forums.example.com’);
setcookie(‘user’, ‘’, time()-600, ‘’, ‘forums.example.com’);
To demonstrate this feature, let’s add a reset page to the web application. This PHP script will
destroy the sent cookies so that the user’s preferences are forgotten.
1. Begin a new PHP script in your test editor or IDE, to be named reset.php.
2. Delete the existing cookies by sending blank cookies. Then complete the PHP code.
3. Create te HTMLhead.
4. Add the page’s body.
5. Complete the HTML.
6. Save the page as reset.php, place it in the proper directory for you PHP enabled server, and
test it in your browser.
Reset.php
<?php
//Delete the cookies
setcookie(‘font_size’, ‘’, time()-600, ‘/’);
setcookie(‘font_color’, ‘’, time()-600, ‘/’);
?>
<!doctype html>
<html laug= “en”>

Developed By. Dr. Munesh Thakre Page 271 of 306


Web Engineering BE CSE SEM-VII

<head>
<meta charset= “utf-8”>
<title>Reset Your Settings </title>
</head>
<body>
<p>Your settings have been reset! Feel free to <a href= “view_setting.php”>
customize</a>them again.</p>
</body>
</html>

What Are Sessions?


A session, like a cookie, provides a way for you to track data for a user over a series of pages. The
difference between the two – and this is significant – is that a cookie stores the data on the client,
whereas the session data is stored on the server. Because of this difference, sessions have numerous
benefits over cookies:
 Sessions are generally more secure, because the data isn’t transmitted back and forth between
the client and server repeatedly.
 Sessions allow you to store more information that you can in a cookie.
 Sessions can be made to work even if the user doesn’t accept cookies in their browser.
 You can more easily store other types of data in sessions, such as arrays and Booleans.
When you start a seesion, PHP generates a random session ID. Each user’s session will have its own
session ID, corresponding to the name of the text file on the server that stores the user’s session data.
So that every PHP script on a site can associate the same session data with a particular user, the
session ID must be tracked as well. By default, this session ID is sent to the browser as a cookie.
Subsequent PHP pages will use this cookie to retrieve the session ID and access the session
information.

Creating a Session
Creating, accessing, or deleting a session begins with the session_start() function. This function will
attempt to send a cookie the first time a session is started, so it absolutely must be called prior to any
HTML or white space being sent to the browser. Therefore, on pages that use sessions, you should
call the session_start() function as one of the very first lines in you script:
<?php
session_start();
The first time a session is started, a random session ID is generated and a cookie is sent to the web
browser with a name of PHP SESSID and the value like mo7puk861tm60tbm4b8coh0og2.

Developed By. Dr. Munesh Thakre Page 272 of 306


Web Engineering BE CSE SEM-VII

Once the session has been started, you can record data to it by assigning values to the $_SESSION
array:
$_SESSION[‘first_name’ ] ‘Krishna’;
$_SESSION[‘age’] = 90;
Unlike with other arrays you might use in PHP, you should always treat this array as an associative
array. In other words, you should explicitly use strings for the keys, such as first_name and age.
Each time a value is assigned to the $_SESSION array, PHP writes that data to a temporary file
stored on the server.
To create a session
1. Open login.php in your text editor or IDE.
2. Before the ob_end_clean() line, add the following:
session_start();
$_SESSION[‘email’] = $_POST[‘email’];
$_SESSION[‘loggedin’] = time();
3. Save the file as login.php, and place it in the appropriate directory on you PHP enabled
computer.
4. Load the form in your browser to ensure that it has no errors.
Login.php
<?php
//This page lets people log into the site
//Set the page title and include the header file.
define(‘TITLE’, ‘Login’);
include(‘templates/header.html’);
//print some introductory text
print ‘<h2>Login Form</h2>
<p>Users who are logged in can take advantage of certain features like this, that, and
the other thing.</p>’;
//Check if the form has been submitted :
if($_SERVER([‘REQUEST_METHOD’] == ‘POST’)
{
//Handle the form
if((!empty($_POST[‘email’])) && (!empty($_POST[‘password’])))
{
if((strlower($_POST[‘email’]) == ‘me@example.com’) &&
($_POST[‘password’] == ‘testpass’))
{
//correct
//Do session stuff;
session_start();

Developed By. Dr. Munesh Thakre Page 273 of 306


Web Engineering BE CSE SEM-VII

$_SESSION[‘email’] = $_POST[‘email’];
$_SESSION[‘loggedin’] = time();
//Redirect the user to the welcome page
ob_end_clean(); //Destroy the buffer!
header(‘Location: welcome.php’);
exit();
}
else
{ //Incorrect
print ‘<p class= “text – error”> The submitted email address and
password do not match those on file!<br> Go back and try again.</p>’;
}
}
else
{ //Forgot a field
print ‘<p class= “text – error”>Please make sure you enter both an email
address and a password!<br>Go back and try again.</p>’;
}
}
else
{ //Display the form
print ‘<form action= “login.php” method= “post” class= “form – inline”>
<p><label for= “email”>Email Address:</label><input type= “email” name=
“email” size= “20”></p>
<p><label for= “password”>Password : </label><input type= “password”
name= “password” size= “20”></p>
<p><input type= “submit” name= “submit” value= “log In!” class= “button—
pill”></p>
</form>’;
}
include(‘template/footer.html’); //Need the footer
?>

Accessing Session Variables


Now that you’ve stored values in a session, you need to know how to access them. The first step is to
invoke the session_start() function. This is necessary on every page that will make use of session,
whether it’s creating a new session or accessing an existing one.
From there it’s simply a matter of referencing the $_SESSION variable as you would any other
array. With this in mind, you’ll write another welcome page that accesses the stored email and
loggedin values.

Developed By. Dr. Munesh Thakre Page 274 of 306


Web Engineering BE CSE SEM-VII

To access session variables


1. Create a new PHP document in your text editor of IDE, to be named welcome.php.
2. Begin the session.
3. Define a page title, and include the HTML header.
4. Greet the user by email address.
5. Show how long the user has been logged in.
6. Complete the content.
7. Include the HTML footer, and complete the HTML page.
8. Save the file as welcome.php, place it in the proper directory for your PHP enabled server,
and test it with login.php script in your browser.
Welcome.php
<?php
//This is the welcome page. The user is redirected here after they successfully log in.
//Need the session
session_start();
//set the page title and include the header file
define(‘TITLE’, ‘Welcome to the J.D. Salinger Fan Club!’);
include(‘templates/header.html’);
//Print a greeting
print ‘<h2>Welcome to a J.D. Salinger Fan Club</h2>’;
print ‘<p>Hello, ’.$_SESSION[‘email’]. ‘!</p>’;
//print how long they’ve been logged in
date_default_timezone_set(‘America/New_York’);
print ‘<p>You have been logged in since:’.date(‘g:i a’, $_SESSION[‘loggedin’]). ‘.</p>’;
//Make a logout link
print ‘<p><a href= “logout.php”>Logout</a></p>’;
include(‘template/footer.html’); //Need for footer
?>

Deleting a Session
It’s important to know how to delete a session, just as It’s important to know how to delete a cookie:
Eventually you’ll want to get rid of the data you’ve stored. Session data exists in two places – in an
array during the execution of the script and in a text file – so you’ll need to delete both. But first you
must begin with the session_start() function, as always:
session_start();
Then, you clear the session variables by resetting the $_SESSION array:
$_SESSION = []; //or = array();
Finally, remove the session data from the server. To do this, use:
session_destroy();

Developed By. Dr. Munesh Thakre Page 275 of 306


Web Engineering BE CSE SEM-VII

With that in mind, let’s write logout.php, which will delete the session, effectively logging out the
user.
To delete a session
1. Start a new PHP script in your text editor or IDE, to be named logout.php.
2. Begin the session.
3. Reset the session array.
4. Destroy the session data on the server.
5. Include the HTML header, and complete this PHP section.
6. Make the page content.
7. Include the HTML footer.
8. Save the file as logout.php, place it in the proper directory for your PHP enabled server, and
test it in your browser by clicking the link in welcome.php.
Logout.php
<?php //This is the logout page, it destroys the session information //Need the session
session_start();
//Reset the session array
$_SESSION=[];
//Destroy the session data on the server
session_destroy();
//Define a page title and include the header
define(‘TITLE’, ‘Logout’);
include(‘template/header.html’);
?>
<h2>Welcome to the J.D. Salinger Fan Club!</h2>
<p>You are now logged out..</p>
<p>Thank you for using this site, We hope that you liked it.<br>
Blah, blah, blah…. Blah, blah, blah….</p>
<?php include(‘template/footer.html’);
?>
Creating Functions
PHP User Defined Functions. Besides the built-in PHP functions, we can create our
own functions. A function is a block of statements that can be used repeatedly in a program.
A function will not execute immediately when a page loads. A function will be executed by a call to
the function.
PHP functions are similar to other programming languages. A function is a piece of code which
takes one more input in the form of parameter and does some processing and returns a value.

Developed By. Dr. Munesh Thakre Page 276 of 306


Web Engineering BE CSE SEM-VII

You already have seen many functions like fopen() and fread() etc. They are built-in functions but
PHP gives you option to create your own functions as well.
There are two parts which should be clear to you −
 Creating a PHP Function
 Calling a PHP Function
In fact you hardly need to create your own PHP function because there are already more than 1000
of built-in library functions created for different area and you just need to call them according to
your requirement.

Creating and Using Simple Function


As you program, you’ll discover that you use certain sections of code frequently, either within a
single script or over the course of several scripts. Placing these routines into a self defined function
can save you time and make your programming easier, especially as your websites become more
complex. Once you create a function, the actions of that function, take place each time the function is
called, just as print sends text to the browser with each use.
The syntax for creating a user-defined function is:
function function_name()
{
statement(s);
}
For example:
function whatever()
{
print ‘whatever’;
}
You can use roughly the same naming conversions for functions as you do for variables, just without
the initial dollar sign. Second to that is the suggestion that you create meaningful function names,
just as you ought to write representative variable names. For example, create_header would be a
better function name than function1. Remember not to use spaces in the name, though-doing so
constitutes two separate words for the function name, which will result in error messages. The
underscore is a logical replacement for the space. Unlike variables, function names in PHP are not
case-sensitive, but you should still stick with a consistent naming scheme.
Any valid PHP code can go within the statement(s) area of the function, including calls to other
functions. Functions do not have a limit on the number of statements they can contain, but make
sure you end each statement with a semicolon, just as you would within the rest of the PHP script.
Functions can also contain any combination of control structures: conditional and loops.

Developed By. Dr. Munesh Thakre Page 277 of 306


Web Engineering BE CSE SEM-VII

The exact formatting of a function isn’t important as long as the requisite elements are there. These
elements include the word function, the function’s name, the opening and closing parentheses, the
opening and closing braces, and the statement(s). It’s conventional to indent a function’s statement(s)
from the function keyword line, for clarity’s sake, as you would with a loop or conditional. In any
case, select a format style that you like – which is both syntactically correct and logically sound –
and stick to it.
You call the function by refereing to it just as you do any built-in function. The line of code:
whatever();
will cause the statement part of the previously defined function – the print command to be executed.
To create and call a basic function
1. Start a new PHP document in your text editor or IDE, to be named menus.php.
2. Begin the PHP section.
3. Start defining a function:
function make_date_menus() {
4. Create the month pull down menu:
5. Create the day pull down menu.
6. Create the year pull down menu.
7. Close the function.
8. Make the form tags, and call the function.
9. Complete the PHP and HTML.
10. Save the file as menus.php, place it in the proper directory for your PHP enabled server, and
run it in your browser.
11. If you want, check out the HTML source of the page to see what was dynamically generated.
Menus.php
<!doctype html>
<html>
<head>
<meta charset= “utf-8”>
<title>Date Menus</title>
</head>
<body>
<?php
//This script define and calls a function
//This function makes three pull down menus for the months, days, and years
function make_date_menus()
{

Developed By. Dr. Munesh Thakre Page 278 of 306


Web Engineering BE CSE SEM-VII

//Array to store the months


$month = [1 => ‘January’, ‘February’, ‘March’, ‘April’, ‘May’, ‘June’,
‘July’, ‘August’, ‘September’, ‘October’, ‘November’, ‘December’];
//Make the month pull down menu
print ‘<select name= “month”>;
foreach($month as $key => $value)
{
print “\n<option value=\” $key\ “>$value</option>”;
}
print ‘</select>’;
//Make the day pull down menu
print ‘<select name= “day”>;
for($day=1; $day <=31; $day++)
{
print “\n<option value=\” $day\ “>$day</option>”;
}
print ‘</select>’;
//Make the year pull down menu
print ‘<select name= “Year”>’;
$start_year = date(‘Y’);
for($y = $start_year; $y<= ($start_year+10); $y++)
{
print “\n<option value=\” $y\ “>$y</option>”;
}
print ‘</select>’;
}
//Make the form
print ‘<form action= “” method= “post”>’;
make_date_menus();
print ‘</form>’;
?>
</body>
</html>

Creating and Calling Functions That Take Arguments


Although being able to create a simple function is useful, writing one that takes input and does
something with that input is even better. The input passed to a function is known as an argument.
This is a concept you’ve seen before: The sort() function takes an array as an argument, which the
function then sorts.

Developed By. Dr. Munesh Thakre Page 279 of 306


Web Engineering BE CSE SEM-VII

The syntax for writing functions that takes arguments is as follows:


function function_name($arg1, $arg2, …)
{
statement(s);
}
The function is defined with parameters: variables that are assigned the values sent to the function
when you call it. The variables are defined using the same naming rules as any other variable in PHP.
function make_full_name($first, $last)
{
print $first . ‘ ’.$last;
}
Functions that take input are called much like those that don’t – you just need to remember to pass
along the necessary values. You can do this either by passing variables:
make_full_name($fn,$ln);
or by sending literal values, as in
make_full_name(‘Larry’, ‘Ullman’);
or some combination thereof:
make_full_name(‘Larry’, $ln);
To create and call a function that takes an argument
1. Start a new PHP document in your text editor or IDE, to be named sticky1.php.
2. Begin the PHP section.
3. Start defining a function.
4. Print an opening paragraph and a label tag.
5. Begin the text input.
6. If applicable, add the input’s preset value.
7. Complete the input, the label, the paragraph, and the function.
8. Make the form tags, and call the function.
9. Create two more inputs.
10. Complete the form.
11. Complete the PHP and HTML.
12. Save the file as sticky1.php, place it in the proper directory for your PHP enabled server, and
run it in your browser.
Sticky1.php
<!doctype html>
<html>
<head>
<meta charset= “utf-8”>
<title>Sticky Text Inputs</title>
</head>

Developed By. Dr. Munesh Thakre Page 280 of 306


Web Engineering BE CSE SEM-VII

<body>
<?php
//This script define and calls a function that creates a sticky text input.
//This function makes a sticky text input
//This function requires two arguments be passed to it.
function make_text_input($name, $label)
{
//Begin a paragraph and a label
print ‘<p><label>’. $label. ‘: ’;
//Begin the input
print ‘<input type= “text” name= “ ‘ .$name.’ ” size= “20” ’;
//Add the value
if(isset($_POST[$NAME]))
{
print ‘Value = “ ‘. htmlspecialchars($_POST[$name]). ’ ” ’;
}
//Complete the input, the label and the paragraph
print ‘<p></label></p>’;
}
//Make the form
print ‘<form action= “ ” method= “post”>’;
//Create some text inputs
make_text_input(‘first name’, ‘First Name’);
make_text_input(‘last name’, ‘Last Name’);
make_text_input(‘email’, ‘Email Address’);
print ‘<input type= “submit” name= “submit” value= “Register!”></form>’;
?>
</body>
</html>

Setting Default Argument Values


PHP allows functions to have default argument values: Just assign a value to the parameter in the
function definition:
function greeting($who = ‘world’) {
print “<p>Hello, $who!</p>”’
}
Such a function will use the preset value unless it receives a value that then over writes the default.
In other words, by setting a default value for an argument, you render that particular argument
optional when calling the function. You’d set an arguments default value if you wanted to assume a
certain value if you wanted to assume a certain value but still allow for other possibilities.

Developed By. Dr. Munesh Thakre Page 281 of 306


Web Engineering BE CSE SEM-VII

greeting();
greeting(‘Zoe’);
The parameters with default values must always be written after the other parameters. This is
because PHP directly assigns values to parameters in the order they’re received from the call line.
Thus, it isn’t possible to omit a value for the first argument but include one for the second. For
example, suppose you have
function calculate_total($qty, $price=20.00, $tax=0.06) {…
if you call the function with the line
calculate_total(3,0.07);
with the intention of setting $qty to 3, leaving $price is set to 0.07, and $tax remain at 0.06, which
isn’t the desired outcome. The proper way to achieve that effect would be to code.
calculate_total(3,20.00,0.07);
To write a function that uses default values
1. Open sticky1.php in you text editor or IDE, if it isn’t open already.
2. Add a third argument with a default value to the make_text_input() function.
3. Change the creation of the input so that it uses the $size variable.
4. Change the function calls to vary the sizes.
5. Save the script as sticky2.php, place it in the proper directory of you PHP enabled server,
and test it in your browser.
Sticky2.php
<!doctype html>
<html>
<head>
<meta charset= “utf-8”>
<title>Sticky Text Inputs</title>
</head>
<body>
<?php
//This script define and calls a function that creates a sticky text input.
//This function makes a sticky text input
//This function requires two arguments be passed to it.
//A third argument is optional (it has a default value).
function make_text_input($name, $label, $size=20)
{
//Begin a paragraph and a label
print ‘<p><label>’. $label. ‘: ’;
//Begin the input

Developed By. Dr. Munesh Thakre Page 282 of 306


Web Engineering BE CSE SEM-VII

print ‘<input type= “text” name= “ ‘ .$name.’ ” size= ‘ “. $size.’” ’;


//Add the value
if(isset($_POST[$NAME]))
{
print ‘Value = “ ‘. htmlspecialchars($_POST[$name]). ’ ” ’;
}
//Complete the input, the label and the paragraph
print ‘<p></label></p>’;
}
//Make the form
print ‘<form action= “ ” method= “post”>’;
//Create some text inputs
make_text_input(‘first name’, ‘First Name’);
make_text_input(‘last name’, ‘Last Name’,30);
make_text_input(‘email’, ‘Email Address’,50);
print ‘<input type= “submit” name= “submit” value= “Register!”></form>’;
?>
</body>
</html>

Creating and Using Functions That Return A Value


Functions do more than take arguments; they can also return values. Doing so requires just two more
steps. First, you use the return statement within the function. Second, you use the output somehow
when you call the function. Commonly, you’ll assign the returned value to a variable, but you can
also, for example, directly print the output. Here is the basic format for a function that takes two
arguments and returns a value:
function make_full_name($first, $last) {
$name = $first. ‘ ’ .$last;
return $name;
}
This function could be used like so:
$full_name = make_full_name($fn,$ln);
There the returned value of the function is assigned to a variable. Here it’s printed immediately:
print make_full_name($fn, $ln);
To create and use the function that returns a value
1. Create a new PHP document in your text editor or IDE, to be named calculator1.php.
2. Begin the PHP code.
3. Define the function.
4. Begin the conditional to see if the form was submitted.

Developed By. Dr. Munesh Thakre Page 283 of 306


Web Engineering BE CSE SEM-VII

5. Validate the form data, and use the function.


6. Completes the conditionals.
7. Display the HTML form.
8. Complete the HTML page.
9. Save the page as calculator1.php, place it in the proper directory for you PHP enabled
server, and test it in you browser.
Calculator1.php
<!doctype html>
<html>
<head>
<meta charset= “utf-8”>
<title>Cost Calculator</title>
</head>
<body>
<?php
//This script displays and handles an HTML form.
//It uses a function to calculate a total from a quantity and price.
//This function performs the calculations.
function calculate_total($quantity,$price)
{
$total = $quantity * $price; //Calculation
$total = number_format($total,2); //Formating
return $total;
}
//Check for a form submission.
if($_SERVER[‘REQUEST_METHOD’]== ‘POST’)
{
//check for values
if(is_numeric($_POST[‘quantity’] AND is_numeric($_POST[‘price’]))
{
//Call the function and print the results
$total = calculate_total($_POST[‘quantity’], $_POST[‘price’]);
print “<p>Your total comes to $<span style=\” font-weight:
bold;\“>$total</span>.</p>”;
}
else
{
//Inappropriate value entered
print ‘<p style= “color: red;”>Please enter a valid quantity and
price!</p>’;
}
}

Developed By. Dr. Munesh Thakre Page 284 of 306


Web Engineering BE CSE SEM-VII

?>
<form action= “” method= “post”>
<p>Quantity: <input type= “text” name= “quantity” size= “3”></p>
<p>Price: <input type= “text” name= “price” size= “5”</p>
<input type= “submit” name= “submit” value= “Calculate!”>
</form>
</body>
</html>

Understanding Variable Scope


The concept of variable scope wasn’t introduced in earliear chapters because without an
understanding of functions, scope makes little sense. Now that you are acquainted with functions,
this section revisits the topic of variables and discusses in some detail just how variables and
function work together.
As you saw in the second section of this chapter, “Creating and Calling Functions That Take
Arugments” you can send variables to a function by passing them as arguments. However, you can
also reference an external variable from within a function using the global statement. This is possible
because of variable scope.
By default, the variables you write in a script exist for the life of that lone script. Conversely,
environment variables, such as $_SERVER[‘PHP_SELF’], exist throughout every PHP script on
the server.
Functions, though, create a new level of scope. Function variables – the function’s parameters as
well as any variables defined within the function – exist only within that function and aren’t
accessible outside of it. Put another way, function variables are local variables with local scope.
Likewise, a variable from outside a function is not available within the function, by default.
The syntax of the global statement is simply
function function_name($args) {
global $variable;
statement(s);
}
There is another issue regarding functions and variables: Because of variable scope, a local variable
within a function is a different entity – perhaps with a different value – than a variable outside of the
function, even if the two variables use the exact same name. Let’s look at this more explicitly.
function foo($param) {
//Do whatever.
}
$var=1;

Developed By. Dr. Munesh Thakre Page 285 of 306


Web Engineering BE CSE SEM-VII

foo($var);
When the function is called, the value of $var will be assigned $param, so their values are the same
but their names are different and they are different variables. Now if the name of the parameter in the
function is also $var
function bar($var) {
//Do whatever.
}
$var=1;
bar($var);
then the $var variable within the function is assigned the same value as the original $var outside of
the function – but they’re still two separate variables. The one has a scope within the function, and
the other has a scope outside of it. This means that you can use the same name for variables in the
function as exist outside of the function without conflict.
To use the global statement
1. Open calculator1.php in your text editor or IDE, if it is not already open.
2. Before the function definition, add the following:
$tax = 8.75;
3. Within the function definition, add a global statement:
global $tax;
4. Before the $total in the function is formatted, recalculate the value using the tax rate.
5. After the main print line so that it prints the tax rate as well.
6. Save the script, place it in the proper directory for your PHP enabled server, and test it in
your browser.
Calculator1.php
<!doctype html>
<html>
<head>
<meta charset= “utf-8”>
<title>Cost Calculator</title>
</head>
<body>
<?php
//This script displays and handles an HTML form.
//It uses a function to calculate a total from a quantity and price.
//Define a tax rate
$tax = 8.75
//This function performs the calculations.
function calculate_total($quantity,$price)

Developed By. Dr. Munesh Thakre Page 286 of 306


Web Engineering BE CSE SEM-VII

{
$global $tax;
$total = $quantity * $price; //Calculation
$taxrate = ($tax/100)+1;
$total = $total * $taxrate; //Add the tax
$total = number_format($total,2); //Formating
return $total;
}
//Check for a form submission.
if(isset[$_POST[‘submitted’]))
{
//check for values
if(is_numeric($_POST[‘quantity’] AND is_numeric($_POST[‘price’]))
{
//Call the function and print the results
$total = calculate_total($_POST[‘quantity’], $_POST[‘price’]);
print “<p>Your total comes to $<span style=\” font-weight:
bold;\“>$total</span>, including the $tax percent tax rate.</p>”;
}
else
{
//Inappropriate value entered
print ‘<p style= “color: red;”>Please enter a valid quantity and
price!</p>’;
}
}
?>
<form action= “” method= “post”>
<p>Quantity: <input type= “text” name= “quantity” size= “3”></p>
<p>Price: <input type= “text” name= “price” size= “5”</p>
<input type= “submit” name= “submit” value= “Calculate!”>
<input type= “hidden” name= “submitted” value= “true”>
</form>
</body>
</html>

Developed By. Dr. Munesh Thakre Page 287 of 306


Web Engineering BE CSE SEM-VII

Introduction to Databases
The internet wouldn’t be what it is today if not for the existence of databases. In fact, PHP probably
wouldn’t be as popular or as useful if not for its built-in support for numerous types of databases. In
this section use MySQL as the example of database management system(DBMS). Although MySQL
which is available for most platforms – may not be as powerful as the highest-end commercial
database servers, it has enough speed and functionality for most purposes. And its price-free for most
uses-makes it the common choice for web development.

Introduction to SQL
A database is a collection of tables (made up of columns and rows) that stores information. Most
databases are created, updated, and read using SQL (Structured Query Language). SQL has
surprisingly few command (like ALTER, CREATE, DELETE, DROP, INSERT, SELECT, and
UPDATE), which is both a blessing and a curse.
SQL was designed to be written a lot like the English language, which makes it very user friendly.
But SQL is still extremely capable, even if it takes some thought to create more elaborate SQL
statements with only the handful of available terms.
For people new to PHP, confusion can stem from PHP’s relationship to HTML. When you
incorporate a database, the relationships can become even fuzzier. The process is quite simple: PHP
is used to send SQL statement to the database application, where they are executed. The result of the
execution – the creation of a table, the insertion of a record, the retrieval of some records, or even an
error – is then returned by a database to the PHP script.
With that in mind, PHP’s mysqli_query() function will be the most used tool. It sends an SQL
command to MySQL:
$result = mysqli_query(database connection, SQL command);
When a PHP script that interacts with a MySQL database does not perform as expected, the first step
is to determine if the problem is in the query itself. To take this step, you can start by printing out the
query being executed, using code such as the following:
print $query;
Assuming that $query represents the complete SQL command, often containing the values of PHP
variables, this one simple line will reveal to you the actual SQL statement being run.
Next, you would take the printed query and exeute it using another application. The two most
common options are:
 The MySQL client, a command-line tool for interacting with MySQL.

Developed By. Dr. Munesh Thakre Page 288 of 306


Web Engineering BE CSE SEM-VII

 phpMyAdmin, a PHP-based MySQL interface.


MySQL Support in PHP
Support for the MySQL database server has to be built into PHP in order for you to use PHP’s
MySQL-specific functions. For most PHP installations, this should already be the case. You can
confirm support for MySQL by calling the phpinfo() function, which reveals details of your
installation.
Enabling support for MySQL takes a little effort, but it can be done if you have administrative level
control over your server.

Connecting to MySQL
When you worked with text files, “Files and Directories”, you saw some functions, such as fwrite()
and fgets(), require that you first create a file pointer using fopen(). This pointer you use a similar
process when working with databases. First, you have to establish a connection to the database server
– in this case, MySQL. This connection is then used as the access point for any future commands.
The syntax for connecting to a database is:
$dbc = mysqli_connect(hostname, username, password, database_name);
The database connection-assigned to $dbc in this example-is normally established using at least four
arguments: the host, which is almost always localhost, the username; the password for that username
and the database name.
If you’re using a database through a hosting company, the company will most likely provide you
with all of these values.
One you’re finished working with a database, you can close the connection, just as you’d close on
open file:
mysqli_close($dbc);
The PHP script will automatically close the database connection when the script terminates, but it’s
considered good form to formally close the connection once it’s no longer needed.
To connect to a MySQL database
1. Begin a new PHP document in your text editor or IDE, to be named mysqli_connect.php.
2. Start the section of PHP code.
3. Connect to MySQL, and report on the results.
4. Complete the PHP code and the HTML page.
5. Save the file as mysqli_connect.php, place it in the proper directory of your PHP-enabled
computer, and test it in your browser.

Developed By. Dr. Munesh Thakre Page 289 of 306


Web Engineering BE CSE SEM-VII

Mysqli_connect.php
<!doctype html>
<html lang= “en”>
<head>
<title>Connect to MySQL</title>
</head>
<body>
<?php
/*This script connect to the MySQL database*/
//Attempt to connect to MySQL and print out messages
if($abc = mysqli_connect(‘localhost’, ‘username’, ‘password’, ‘myblog’))
{
print ‘<p>Successfully connected to the database!</p>’;
mysqli_close($abc); //close the connection
}
else
{
print ‘<p style= “color: red;”>Could not connect to the
database.</p>’;
}
?>
</body>
</html>

MySQL Error Handling


MySQL would be best to discuss some error-handling techniques up front. Common errors you’ll
encounter are:
 Failure to connect to MySQL.
 Inability to run a query.
 No results returned by a query.
 Data not inserted into a table.
Experience will teach you why these errors normally occurs, but immediately seeing what the
problem is when running your scripts can save you much debugging time. To have your scripts give
informative reports about errors that occur, use the mysqli_error() function. This function return a
textual version of the error that the MySQL server returned. It needs to be provided with the database
connection:
print mysqli_error($dbc);

Developed By. Dr. Munesh Thakre Page 290 of 306


Web Engineering BE CSE SEM-VII

Connection errors are slightly different, however. To report upon those, invoke
mysqli_connect_error(). This function does not take any arguments:
print mysql_connect_error();
Along with these functions, you may want to use some PHP tools for handling errors. For beginners,
you can start with the error suppression operator. When use preceding a function name, it suppresses
any error messages or warnings the function might invoke:
@function_name();
To use error handling
1. Open mysqli_connect.php in your text editor or IDE.
2. Suppress any PHP error created by the mysqli_connect() function by changing the if
conditional.
3. Add the mysqli_error() function to print statement in the else section.
4. Save the file, and test it again in your browser.
Mysqli_connect2.php
<html lang= “en”>
<head><title>Connect to MySQL</title></head>
<body>
<?php
/*This script connect to the MySQL database*/
//Attempt to connect to MySQL and print out messages
if($abc = mysqli_connect(‘localhost’, ‘username’, ‘password’, ‘myblog’))
{
print ‘<p>Successfully connected to the database!</p>’;
mysqli_close($abc); //close the connection
}
else {
print ‘<p style= “color: red;”>Could not connect to the
database.<br>’.mysqli_connect_error(). ‘.</p>’;
}
?>
</body>
</html>

Creating a Table

Developed By. Dr. Munesh Thakre Page 291 of 306


Web Engineering BE CSE SEM-VII

Once you’ve created and selected initial database, you can begin creating individual tables in it. A
database can consist of multiple tables, but in the simple example you’ll create one table in which all
the data will be stored.
To create a table in the database, you’ll use SQL-the language that databases understand. Because
SQL is a lot like spoken English, the proper query to create a new table records like this:
CREATE TABLE tablename(column1 definition, column2 definition, etc.);
For each column, separated by commas, you first indicate the column name and then the column
types are TEXT, VARCHAR(a variable number of characters), DATETIME, and INT(integer).
Because it’s highly recommended that you create a column that acts as the primary key(a column
used to refer to each row), a simple CREATE statement could be:
CREATE TABLE my_table(id INT PRIMARY KEY, information TEXT);
A table’s primary key is a special column of unique values that is used to refer to the table’s row.
The database makes an index of this column in order to more quickly navigate through the table. A
table can have only one primary key, which you normally set up as an automatically increamented
column of integers. The first two has a key of 1, the second has a key of 2, and so forth. Referring
back to the key always retrieves the values for that row.
Finally, it’s a good idea to establish the default character set when creating a table(or a database).
This is accomplished by adding CHARACTER SET name at the end of the table creation statement:
CREATE TABLE my_table(id INT PRIMARY KEY, information TEXT) CHARACTER SET
utf8;
To Create a New Table
1. Begin a new PHP document in your text editor or IDE, to be named create_table.php.
2. Begin a secion of PHP code.
3. Connect to the MySQL database.
4. Define the query for creating the table.
5. Execute the query.
6. Close the database connection, and complete the $dbc conditional.
7. Complete the PHP code and the HTML page.
8. Save the script as create_table.php, place it in the proper directory for your PHP-enabled
server, and test it in your browser.
Create_table.php
<html lang= “en”>
<head>
<title>Create a Table</title>

Developed By. Dr. Munesh Thakre Page 292 of 306


Web Engineering BE CSE SEM-VII

</head>
<body>
<?php
/*This script connect to the MySQL server, selects the database, and creates a
table*/
//Connect and select
if($dbc = @mysqli_connect(‘localhost’, ‘username’, ‘password’, ‘myblog’))
{
//Define the query
$query = ‘CREATE TABLE entries(id INT UNSIGNED NOT NULL
AUTO_INCREMENT PRIMARY KEY, title VARCHAR(100) NOT
NULL, entry TEXT NOT NULL, date_entered DATETIME NOT
NULL) CHARACTER SET utf8’;
//Execute the query
if(@mysqli_query($dbc, $query))
{
print ‘<p>The table has been created!</p>’;
}
else
{
print ‘<p style= “color: red;”>Could not create the table
because :<br>’.mysqli_error($dbc). ‘.</p><p>The query being
run was: ‘.$query. ‘</p>’;
}
mysqli_close($dbc);//close the connection
}
else
{ //connection failure.
print ‘<p style= “color: red;”>Could not connect to the
database:<br>’.mysqli_connect_error(). ‘.</p>’;
}
?>
</body>
</html>
Inserting Data into a Database
As mentioned, this database will be used as a simple blog, an online journal. Blog entries –
consisting of a title and text – will be added to the database using one page.
The last script created the table, which consists of four columns: id, title, entry, and date_entered.
The process of adding information to a table is similar to creating the table itself in terms of which
PHP functions you use, but the SQL query is different. to insert records, use the INSERT SQL
command with either of the following syntaxes:

Developed By. Dr. Munesh Thakre Page 293 of 306


Web Engineering BE CSE SEM-VII

INSERT INTO tablename VALUES(value1, value2, value3, etc.)


INSERT INTO tablename(column1_name, column2_name) VALUES(value1, value2);
The query begins with INSERT INTO tablename. Then you can either specify which columns
you’re inserting values for or not name the columns explicitly. The former is more specific and is
therefore preferred, but it can be tedious if you’re populating a slew of columns. In either case, you
must be certain to list the right number of total values and the right type of value for each column.
The values are placed within parentheses, with each value separated by a comma. Non-numeric
values-strings are dates need to be quoted, whereas numbers do not:
INSERT INTO example(name,age) VALUES(‘Jonah’, 1);
To enter data into database from an HTML form
1. Begin a new PHP document in your text editor or IDE, to be named add_entry.php.
2. Create the initial PHP section, and check for the form submission.
3. Validate the form data.
4. Connect to the database.
5. Define the INSERT query.
6. Run the query on the database.
7. Close the database connection, the $problem conditional, and complete the main conditional
and the PHP section.
8. Create the form.
9. Finish the HTML page.
10. Save the script as add_entry.php, place it in the proper directory for your PHP-enabled server,
and test it in your browser.
Add_entry.php
<html lang= “en”>
<head>
<title>Add a Blog Entry</title>
</head>
<body>
<h1>Add a Blog Entry</h1>
<?php
/*This script adds a blog entry to the database*/
if($_SERVER[‘REQUEST_METHOD’] == ‘POST’) //Handle the form
{
//Validate the form data
$problem = FALSE;
if(!empty($_POST[‘title’]) && !empty($_POST[‘entry’]))

Developed By. Dr. Munesh Thakre Page 294 of 306


Web Engineering BE CSE SEM-VII

{
$title = trim(strip_tags($_POST[‘title’]));
$entry = trim(strip_tags($_POST[‘entry]));
}
else
{
print ‘<p style= “color: red;”>Please submit both a title and an
entry.</p>’;
$problem = TRUE;
}
if($problem)
{
//Connect and select
$abc = mysqli_connect(‘localhost’, ‘username’, ‘password’,
‘myblog’);
//Define the query
$query = “INSERT INTO entries(id, title, entry, date_entered)
VALUES(0, ‘$title’, ‘$entry’, NOW())”;
//Execute the query
if(@mysqli_query($dbc, $query))
{
print ‘<p>The blog entry has been added!</p>’;
}
else
{
print ‘<p style= “color: red;”>Could not add the entry
because:<br>’ .mysqli_error($dbc). ‘.</p><p>The
query being run was: ‘.$query. ‘</p>’;
}
$mysqli_close($dbc);//close the connection
}
}
?>
<form action= “add_entry.php” method= “post”>
<p>Entry Title :<input type= “text” name= “title” size= “40” maxsize=
“100”></p>

<p>Entry Text :<textarea name= “entry” cols= “40” rows=


“5”></textarea></p>

<input type= “submit” name= “submit” value= “Post This Entry!”>

</form>
</body>

Developed By. Dr. Munesh Thakre Page 295 of 306


Web Engineering BE CSE SEM-VII

</html>

Securing Query Data


As I mentioned in the introduction to the section “Inserting Data into a Database,” the code as
written has a pretty bad security hole in it. As it stands, if someone submits text that contains an
apostrophe, that data will break the SQL query. The result is obviously undesirable, but why is it
insecure?
If malicious users know they can break a query by typing an apostrophe, they may try to run their
own queries using this hole. If someone submitting; DROP TABLE entries; as the blog post title, the
resulting query would be:
INSERT INTO entries(id, title, query, date_entered) VALUES(0, ‘; DROP TABLE entries;’, ‘<entry
text>’, NOW());
The initial apostrophe in the provided entry title has the effect of completing the blog title value part
of the query. The semicolon then terminates the INSERT query itself. This will make the original
query syntactically invalid. Then the database will be provided with a second query – DROP TABLE
entries – with the hope that it will be executed when the original INSERT query fails.
This is known as an SQL injection attack, but fortunately it’s easy to prevent.
To do so, send potentially insecure data to be used in a query through the
mysqli_real_escape_string() function. This function will escape-preface with a backslash-any
potentially harmful characters, making the data safe to use in a query:
$var = mysqli_real_escape_string($dbc, $var);
For this function to work properly, the character set needs to be established for the communications:
mysqli_set_charset($dbc, ‘utf8’);
To secure query data
1. Open add_entry.php your text editor or IDE, if it is not already open.
2. Update the assignment of the $title and $entry variables to read.
3. Move the database connection code line.
4. Move the database closing code line.
5. After opening the database connection, identify the character set in use.
6. Save the script, place it on your PHP-enabled server, and test it in your browser.
Add_entry1.php
<html lang= “en”>
<head>

Developed By. Dr. Munesh Thakre Page 296 of 306


Web Engineering BE CSE SEM-VII

<title>Add a Blog Entry</title>


</head>
<body>
<h1>Add a Blog Entry</h1>
<?php
/*This script adds a blog entry to the database. It now does so securely.*/
if($_SERVER[‘REQUEST_METHOD’] == ‘POST’) //Handle the form
{
//Connect and Select
$dbc = mysqli_connect(‘localhost’, ‘username’, ‘password’,
‘myblog’);
//Set the character set
mysqli_set_charset($dbc, ‘utf8’);
//Validate and secure the form data
$problem = FALSE;
if(!empty($_POST[‘title’]) && !empty($_POST[‘entry’]))
{
$title = mysqli_real_escape_string($dbc,
trim(strip_tags($_POST[‘title’])));
$entry = mysqli_real_escape_string($dbc,
trim(strip_tags($_POST[‘entry])));
}
else
{
print ‘<p style= “color: red;”>Please submit both a title and an
entry.</p>’;
$problem = TRUE;
}
if(!$problem)
{
//Define the query
$query = “INSERT INTO entries(id, title, entry, date_entered)
VALUES(0, ‘$title’, ‘$entry’, NOW())”;
//Execute the query
if(@mysqli_query($dbc, $query))
{
print ‘<p>The blog entry has been added!</p>’;
}
else
{
print ‘<p style= “color: red;”>Could not add the entry
because:<br>’ .mysqli_error($dbc). ‘.</p><p>The
query being run was: ‘.$query. ‘</p>’;

Developed By. Dr. Munesh Thakre Page 297 of 306


Web Engineering BE CSE SEM-VII

}
}
$mysqli_close($dbc);//close the connection
}
?>
<form action= “add_entry1.php” method= “post”>
<p>Entry Title :<input type= “text” name= “title” size= “40” maxsize=
“100”></p>
<p>Entry Text :<textarea name= “entry” cols= “40” rows=
“5”></textarea></p>
<input type= “submit” name= “submit” value= “Post This Entry!”>
</form>
</body>
</html>

Retrieving Data from a Database


The next process is retrieving data from a populated table. You still use the mysqli_query() function
to run the query, but retrieving data is slightly different than inserting data-you have to assign the
query result to a variable and then use another function to fetch the data.
The basic syntax for retrieving data is SELECT query:
SELECT what column FROM what table
The easiest query for reading data from a table is
SELECT *from tablename
The asterisk is the equivalent of saying every column. If you require only certain columns to be
returned, you can limit your query, like so:
SELECT name, email FROM users
That query requests that only the information from two columns – name and email – be gathered.
Keep in mind that this structure doesn’t limit what rows(or records) are returned, just what colums
for those rows.
Another way to alter your query is to add a conditional restricting which rows are returned,
accomplished using a WHERE clause:
SELECT *FROM users WHERE name= ‘Larry’;
The main difference in retrieving data from a database as opposed to inserting data into a database is
that you need to handle the query differently. You should first assign the results of the query to a
variable:
$result = mysqli_query($dbc, $query);

Developed By. Dr. Munesh Thakre Page 298 of 306


Web Engineering BE CSE SEM-VII

Just as $dbc is a reference to an open database connection, $result is a reference to a query result
set. This variable is then provided to the mysqli_fetch_array() function, which retrieves the query
results:
$row = mysqli_fetch_array($result);
The function fetches one row from the result set at a time, creating an array in the process. The array
will use the selected column names as its indexes: $row[‘name’], $row[‘email’], and so on.
To retrieve data from a table
1. Begin a new PHP document in your text editor or IDE, to be named view_entries.php.
2. Begin a PHP section, and connect to the database.
3. Define the SELECT query.
4. Run the query.
5. Print out the returned results.
6. Handle the errors if the query didn’t run.
7. Close the database connection.
8. Complete the PHP section and the HTML page.
9. Save the script as view_entries.php, place it in the proper directory for your PHP-enabled
server, and test it in your browser.
10. If you want, add another record to the blog using the add_entry.php page and run this page
again.
11. Check the source code of the page to see the dynamically generated links.
view_entry.php
<!doctype html>
<html lang= “en”>
<head>
<title>View My Blog</title>
</head>
<body>
<h1>My Blog</h1>
<?php
/*This script retrieves blog entries from the database.*/
//Connect and Select
$dbc = mysqli_connect(‘localhost’, ‘username’, ‘password’, ‘myblog’);
//Define the query
$query = “SELECT * FROM entries ORDER BY date_entered DESC”;
if($r = mysqli_query($dbc, $query))
{ //Run the query
//Retrieve and print the record

Developed By. Dr. Munesh Thakre Page 299 of 306


Web Engineering BE CSE SEM-VII

while($row = mysqli_fetch_array($r))
{
print “<p><h3>{$row[‘title’]}</h3>
{$row[‘entry’]}<br>
<a href=\“edit_entry.php?id={$row[‘id’]}\”>Edit</a>
<a href=\“delete_entry.php?id={$row[‘id’]}\”>Delete</a>
</p><hr>\n”;
}
}
else
{ //Query didn’t run
print ‘<p style= “color: red;”>Could not retrieve the data
because:<br>’ .mysqli_error($dbc). ‘.</p><p>The query being run
was: ‘.$query. ‘</p>’;
}
mysqli_close($dbc);//close the connection
?>
</body>
</html>

Deleting Data in a Database


Sometimes you might also want to run a DELETE query on a database. Such a query removes
records from the database. The syntax for a delete query is:
DELETE FROM tablename WHERE column=value;
The WHERE clause isn’t required, but if it’s omitted, you’ll remove every record from the table.
You should also understand that once you delete a record, there’s no way to recover it (unless you
have a backup of the database).
As a safeguard, if you want to delete only a single record from a table, add the LIMIT clause to the
query.
DELETE FROM tablename WHERE column=value LIMIT 1;
This clause ensures that only one record is deleted at most. Once you’ve defined your query, it’s
again executed using the mysqli_query() function, like any other query.
To see if a DELETE query worked, you can use the mysqli_affected_rows() function. This function
returns the number of rows affected by an INSERT, DELETE, or UPDATE query. It takes the
database connection as an argument.
To delete data from a database
1. Begin a new PHP document in your text editor or IDE, to be named delete_entry_php.
2. Start the PHP code, and connect to the database.

Developed By. Dr. Munesh Thakre Page 300 of 306


Web Engineering BE CSE SEM-VII

3. If the page received a valid entry ID in the URL, define and execute a SELECT query.
4. Retrieve the record, and display the entry in a form.
5. Report an error if the query failed.
6. Check for the submission of the form.
7. 8Define and execute the query.
8. Check the result of the query.
9. Complete the main conditional.
10. Close the database connection, and complete the page.
11. Save the script as delete_entry.php place it in the proper directory for your PHP-enabled
server, and test it in your browser.
delete_entry.php
<html lang= “en”>
<head>
<title>Delete My Blog</title>
</head>
<body>
<h1>Delete an Entry</h1>
<?php
/*This script deletes a blog entry.*/
//Connect and Select
$dbc = mysqli_connect(‘localhost’, ‘username’, ‘password’, ‘myblog’);
if(isset($_GET[‘id’]) && is_numeric($_GET[‘id’]))
{ //Display the entry in a form
//Define the query
$query = “SELECT * FROM entries ORDER BY date_entered DESC”;
if($r = mysqli_query($dbc, $query))
{ //Run the query
$row = mysqli_fetch_array($r); //Retrieve the information
//Make the form
print ‘<form action= “delete_entry.php” method= “post”>
<p>Are you sure you want to delete this entry?</p>
<p><h3>’. $row[‘title’]. ‘</h3>’.$row[‘entry’].’ <br>
<input type= “hidden” name= “id” value= “’.$GET[‘id’].’”>
<input type= “submit” name= “submit” value= “Delete this
Entry!”></p>
</form>’;
}
else
{

Developed By. Dr. Munesh Thakre Page 301 of 306


Web Engineering BE CSE SEM-VII

print ‘<p style= “color: red;”>Could not retrieve the blog entry
because:<br>’ .mysqli_error($dbc). ‘.</p><p>The query
being run was: ‘.$query. ‘</p>’;
}
}
elseif(isset($_POST[‘id’]) && is_numeric($_POST[‘id’]))
{ //Hindle the form
//Define the query
$query = “DELETE FROM entries WHERE id = {$_POST[‘id’]}
LIMIT 1”;
$r = mysqli_query($dbc, $query); //Exceute the query
//Report on the result
if(mysqli_affected_rows($dbc)==1)
{
print ‘<p>The blog entry has been deleted.</p>’;
}
else
{
print ‘<p style= “color: red;”>Could not delete the blog entry
because:<br>’ .mysqli_error($dbc). ‘.</p><p>The query
being run was: ‘.$query. ‘</p>’;
}
}
else
{//No id received
print ‘<p style= “color: red;”>This page has been accessed in
error.</p>’;
}
$mysqli_close($dbc);//close the connection
?>
</body>
</html>

Updating Data in a Database


The final type of query is UPDATE. It’s used to alter the values of a record’s columns. The syntax
is:
UPDATE tablename SET column1_name = value, column2_name = value2 WHERE
some_column = value
As with any other query, if the values are strings, they should be placed within single quotation
marks:
UPDATE users SET first_name= ‘Eleanor’, age=7 WHERE user_id=142;

Developed By. Dr. Munesh Thakre Page 302 of 306


Web Engineering BE CSE SEM-VII

As with DELETE query, you should use a WHERE clause to limit the rows that are affected. If you
don’t do this, every record in the database will be updated.
To test that an update worked, you can again use the mysqli_affected_row() function to return the
number of records altered.
To update data in a database
1. Begin a new PHP document in your text editor or IDE, to be named edit_entry.php.
2. Start your PHP code and connect to the database.
3. If the page received a valid entry ID in the URL, define and execute a SELECT query.
4. Retrieve the record, and display the entry in a form.
5. Report an error if the query failed.
6. Check for the submission of the form.
7. Validate and secure the form data.
8. Define and execute the query.
9. Report on the success of the query.
10. Complete the conditionals.
11. Close the database connection, and complete the page.
12. Save the file as edit_entry.php, place it in the proper directory for your PHP-enabled server,
and test it in your browser.

edit_entry.php
<html lang= “en”>
<head><title>Edit a Blog Entry</title></head>
<body>
<h1>Edit an Entry</h1>
<?php
/*This script edits a blog entry using an UPDATE query.*/
//Connect and Select
$dbc = mysqli_connect(‘localhost’, ‘username’, ‘password’, ‘myblog’);
//Set the character set
mysqli_set_charset($dbc, ‘utf8’);
if(isset($_GET[‘id’]) && is_numeric($_GET[‘id’]))
{ //Display the entry in a form
//Define the query
$query = “SELECT title,enty FROM entries WHERE id={$_GET[‘id’]}”;
if($r = mysqli_query($dbc, $query))
{ //Run the query
$row = mysqli_fetch_array($r); //Retrieve the information
//Make the form

Developed By. Dr. Munesh Thakre Page 303 of 306


Web Engineering BE CSE SEM-VII

print ‘<form action= “entry_entry.php” method= “post”>


<p>Entry Title: <input type= “text” name= “title” size= “40”
maxsize= “100” value= “’.htmlentities($row[‘title’]).’”></p>
<p>Enter Text: <textarea name= “entry” cols= “40” rows=
“5”>’. Htmlentities($row[‘entry’]).’</textarea></p>

<input type= “hidden” name= “id” value= “’.$GET[‘id’].’”>


<input type= “submit” name= “submit” value= “Update this
Entry!”>
</form>’;
}
else { //couldn’t get the information
print ‘<p style= “color: red;”>Could not retrieve the blog entry
because:<br>’ .mysqli_error($dbc). ‘.</p><p>The query
being run was: ‘.$query. ‘</p>’;
}
}
elseif(isset($_POST[‘id’]) && is_numeric($_POST[‘id’]))
{ //Hindle the form
//Validate and secure the form data
$problem = FALSE;
if(!empty($_POST[‘title’]) && !empty($_POST[‘entry’]))
{
$title = mysqli_real_escape_string($dbc,
trim(strip_tags($_POST[‘title’])));
$entry = mysqli_real_escape_string($dbc,
trim(strip_tag($_POST[‘entry’])));
}
else{
print ‘<p style= “color: red;”>Please submit both a title and an entry.</p>’;
$problem = TRUE;
}
if($problem)
{
//Define the query
$query = “UPDATE entries SET title= ‘$title’, entry= ‘$entry’
WHERE id = {$_POST[‘id’]}”;
$r = mysqli_query($dbc, $query); //Exceute the query
//Report on the result
if(mysqli_affected_rows($dbc)==1) {
print ‘<p>The blog entry has been updated.</p>’;
}
else {

Developed By. Dr. Munesh Thakre Page 304 of 306


Web Engineering BE CSE SEM-VII

print ‘<p style= “color: red;”>Could not update the


entry because:<br>’ .mysqli_error($dbc).
‘.</p><p>The query being run was: ‘.$query. ‘</p>’;
}
}
}
else {//No id set
print ‘<p style= “color: red;”>This page has been accessed in error.</p>’;
}
$mysqli_close($dbc);//close the connection
?>
</body>
</html>

Developed By. Dr. Munesh Thakre Page 305 of 306


Web Engineering BE CSE SEM-VII

Unit – IV

Unit – V

Developed By. Dr. Munesh Thakre Page 306 of 306

You might also like