Web Programming
Web Programming
Unit - I
2. HTML 5 23
Unit - II
3. Navigation 35
4. Layouts 44
5. Tables 54
Unit - III
7. Javascript 80
Unit - IV
Unit - V
❖❖❖❖
UNIT - 1
1
INTERNET AND WORLD WIDE WEB
Unit Structure :
Objective
Introduction to internet and its applications.
Email
Telnet
FTP
E–commerce
Video conferencing
E business.
Internet service providers
Domain name servers
Internet address
World wide web and its evolution
URL
Browsers
Internet explorer,
Netscape navigator,
opera,
fire fox,
chrome,
Mozilla,
Search Engine
Web server
Apache
IIS
Proxy Server
HTTP protocol.
Summery
Unit End exercise
OBJECTIVE:
Internet is ---
□ A computer network consisting of a worldwide network of computers
that use the TCP/IP network protocols to facilitate data transmission
and exchange.
□ The Internet is a global system of interconnected computer networks
that use the standard Internet Protocol Suite (TCP/IP) to serve billions
of users worldwide.
□ The term Internet actually refers to the combined collection of
academic, commercial, and government networks connected over
international telecommunication backbones and routed using IP
addressing.
2
□ Email message body contains text (7bit ASCII) as well as multimedia
messages. These processes are declared in Multipurpose Internet Mail
Extensions (MIME). MIME is set of RFCs (Request for Comment)
□ Network based emails are exchanged over the internet using the SMTP
(Simple Mail Transfer protocol).
□ In the process of transporting email messages between systems, SMTP
communicates delivery parameters using a message envelope separate
from the message (header and body)itself.
□ Email addresses (both for senders and recipients) are two strings
separated by the character "@" (the "at sign"): such as user@domain
□ The right-hand part describes the domain name involved, and the left-
hand part refers to the user who belongs to that domain.
□ An email address can be up to 255 characters long and can include the
following characters:
• Lowercase letters from a toz;
• Digits
• The characters ".","_" and "-" (full stop, underscore, and hyphen)
Telnet
3
• Data transferred over telnet is vulnerable as telnet does not use any
encryption technique to mask or protect the data.
• Most implementations of Telnet have no authentication that would
ensure communication is carried out between the two desired hosts and
not intercepted in the middle.
• Commonly used Telnet daemons have several vulnerabilities
discovered over the years.
• Extensions to the Telnet protocol provide Transport Layer Security
(TLS) security and Simple Authentication and Security Layer (SASL)
authentication that address the above issues.
• Few applications of telnet include the ‗putty‘ TCP client which can
access a linux server using windows operating system, Absolute telnet
(windows client) and RUMBA (terminal emulator).
FTP
• File transfer protocol is a simple and standard network protocols that
transfers a file from one host to the other over a TCP network.
• Based on client server architecture.
• Utilizes separate control and data connection for client and server to
transmit and receive file(s) over the network.
• It is an application protocol that uses the internet‘s TCP/IP suite.
• Mainly used to transfer the web pages or related data from the source
or creator to a host that acts as a server to make the page or file
available to other hosts (uploading) or downloading programs and
other files from server to a host.
• FTP protocol can perform over a active or passive connection.
• When a connection is made from the client to server, it is called as
control connection and it remains open for duration of session. This
connection is responsible for establishing connectivity between client
and server.
• Other connection opened by client (passive) or server (active) is called
data connection and is used to transfer the data.
• As separate ports are used by client and server for these connections,
FTP becomes an put of band protocol.
• Data transfer can take place in following three modes
o Stream mode : data is sent in a continuous stream where FTP does
not do any formatting.
o Block mode: FTP breaks the data into several blocks (block
header, byte count, and data field) and then passes it on to TCP.
o Compressed mode: Data is compressed using a single algorithm.
• FTP is a old protocol and is basically low in security aspect. Data
transferred over FTP is not encrypted and is in clear text format.
4
Hence the data like usernames, passwords can be read by anyone who
can capture the FTPed package. Newer versions of the protocol,
however, apply secure shell protocol (SSH) and avoid all the problems
faced by FTP.
• Following are few types of FTP protocol with additional features
• Anonymous FTP : Users login using an ‗anonymous‘ account to
protect their confidential data.
• Remote FTP: FTP commands executed on a remote FTP server
• FTP with web browser and firewall support.
• Secure FTP (SFTP,FTPS)
ECommerce
E business
• E business is conduct of business over the internet, which includes
buying and selling of goods and even services.
• In other words it is application of information and communication
technologies in support of all activities in business.
• Applications of E business are divided into following categories–
7
o Internal business systems--
o Customer Relationship Management(CRM)
o Enterprise Resource Planning(ERP)
o Human resource management system(HRMS)
o Enterprise Communication and collaboration
o Content management
o E- mails
o Voicemails
o Web conferencing
o Electronic commerce
o B2B (business to business)
o B2C (business to customer)
o B2E business-to-employee
o B2Gbusiness-to-government
o G2Bgovernment-to-business
o G2G (government-to-government)
o G2C (government-to-citizen)
o C2C (consumer-to-consumer)
o C2B(consumer-to-business)
• A business model is defined as the organization of product, service and
information flows, and the source of revenues and benefits for
suppliers and customers. The concept of e-business model is the same
but used in the online presence.
• Few e business models are–
o E-shops
o E-commerce
o E-procurement
o E-malls
o E-auctions
o Virtual Communities
• E business has more security risks as compared to a regular business,
as E business has many more users at a time. Keeping the large
information confidential is a difficult task. Also, data integrity,
authenticity and storage of data are some challenges faced by
Ebusiness.
• Some methods to provide security are physical security as well as
encryption in data storage, transmission, antivirus software and
firewalls. Digital signature is another way to confirm the ownership
of a document.
8
INTERNET SERVICE PROVIDER
□ ISP connections–
ISPs which provide connections through phone lines like dial ups,
do not seek any information about the caller‘s (user of the internet)
physical location or address. So, caller from any location which is in reach
of the ISP, can use the services provided.
□ Services provided –
ISP host usually provide e mail, FTP and web hosting services.
Other services can be like virtual machines, clouds or entire physical
servers where clients can run their own softwares.
ISPs often take services from their upstream ISPs. i.e. they work in
hierarchy. The ISPs are divided into three categories –
□ Free ISP: these are ISPs which provide services free of cost to the users
and display advertisements till the users are connected. These are called as
freenets. These are normally run on no profit basis.
10
□ The resolver, or another DNS server acting recursively on behalf of the
resolver, negotiates use of recursive service using bits in the query
headers.
□ Resolving usually entails iterating through several name servers to find
the needed information. However, some resolvers function
simplistically and can communicate only with a single name server.
These simple resolvers (called "stub resolvers") rely on a recursive
name server to perform the work of finding information for them.
□ Operation of DNS–
□ Domain name resolvers determine the appropriate domain name
servers responsible for the domain name in question by a sequence of
queries starting with the right-most (top-level) domain label.
□ DNS recorsor consults three name servers to resolve one address. The
process is as follows–
o A network host is configured with an initial cache (so called hints) of
the known addresses of the root name servers. Such a hint file is
updated periodically by an administrator from a reliable source.
o A query to one of the root servers to find the server authoritative for
the top-level domain.
o A query to the obtained TLD server for the address of a DNS server
authoritative for the second-level domain.
o Repetition of the previous step to process each domain name label in
sequence, until the final step which returns the IP address of the host
sought.
INTERNET ADDRESS
□ Internet address follows the TCP/IP suite hence, it is also known as the
IP address.
□ Internet address has a job of identifying a node on the network. In
other words, it is a numeric lable attached to every system (computer
or any other device). The basic function of IP address are two–
□ Identification of computer or node or device and location addressing.
□ The designers of the Internet Protocol defined an IP address as a 32-bit
number[1] and this system, known as Internet Protocol Version 4
(IPv4), is still in use today. However, due to the enormous growth of
the Internet and the predicted depletion of available addresses, a new
addressing system (IPv6), using 128 bits for the address, was
developed in 1995,[3] standardized as RFC 2460 in 1998,[4] and is
being deployed worldwide since themid-2000s.
□ IP addresses are binary numbers, but they are usually stored in text
files and displayed in human-readable notations, such as 172.16.254.1
(forIPv4)
11
□ IPV4 address is a 32 bit number, which uses the decimal doted
notation consisting of 4 decimal numbers each ranging from 0 to 255
separated by dots. Network administration divides the IP address into
two parts. – the most significant 8 bits are called network address
portion the remaining bits are known as rest bits or host bits or
identifiers and they are used for host numbering in anetwork.
□ Although IPV4 provides 4.3 billion addresses, they are exhausted due
to high demand and as a result, insufficient addresses available with
IANA (Internet assigned numbers authority). The primary address
pool of IANA is expected to get exhausted by mid 2011. To
permanently address the problem, new version of IP i.e. IPV6 was
brought forward, this version moved the size of IP address from 32 bit
to 128 bits.
□ Both IPV4 as well as IPV6 have reserved addresses for private or
internal networks. This is termed as private addressing.
□ Both IPV4 and IPV6 have sub netting effect. That mean, IP networks
can be divided into smaller groups or subnets. IP addresses two
constituents that is network address and host identifier or interface
identifier are used for this purpose.
□ Internet Protocol addresses are assigned to a host either anew at the
time of booting, or permanently by fixed configuration of its hardware
or software. Persistent configuration is also known as using a static IP
address. In contrast, in situations when the computer's IP address is
assigned newly each time, this is known as using adynamic IP address
Evolution of WWW
□ In March 1989, Tim Berners-Lee wrote a proposal that referenced
ENQUIRE, a database and software project he had built in 1980, and
described a more elaborate information management system.
□ on November 12, 1990, with help from Robert Cailliau, Tim
Berners- Lee published a more formal proposal to build a "Hypertext
project" called "World Wide Web" (one word, also "W3") as a
"web" of "hypertext documents" to be viewed by "browsers" using a
client– server architecture.
12
□ This proposal estimated that a read-only web would be developed
within three months and that it would take six months to achieve
"the creation of new links and new material by readers, to achieve
universal authorshipl" as well as "the automatic notification of a
reader when new material of interest to him/her has become
available."
□ A NeXT Computer was used by Berners-Lee as the world's first web
server and also to write the first web browser, World Wide Web, in
1990.
□ Tools needed were a working Web the first web browser (which was
a web editor as well); the first web server; and the first web pages,
which described the project itself.
□ On August 6, 1991, Tim Berners-Lee posted a short summary of the
World Wide Web project on the alt. hypertext newsgroup.
□ This date also marked the debut of the Web as a publicly available
service on the Internet. The first photo on the web was uploaded by
Berners-Lee in 1992, an image of the CERN house band Les
Horribles Cernettes.
□ The first server outside Europe was set up at SLAC to host the
SPIRES-HEP database in 91 –92.
□ The concept of hypertext originated with older projects from the
1960s, such as the Hypertext Editing System (HES) at Brown
University by Ted Nelson and Douglas Engelbart.
□ Tim Berners Lee introduced the concept of the Universal Document
Identifier (UDI), later known as Uniform Resource Locator (URL)
and Uniform Resource Identifier (URI); the publishing language
Hyper Text Markup Language (HTML); and the Hypertext Transfer
Protocol(HTTP).
□ In 1993, a graphical browser was developed by a team at the
National Center for Supercomputing Applications at the University
of Illinois at Urbana-Champaign (NCSA-UIUC), led by Marc
Andreessen. This was the first web browserever.
URL
13
□ Every URL consists of some of the following:
o The scheme name (commonly called protocol), followed by a
colon. The scheme name defines the namespace, purpose, and the
syntax of the remaining part of the URL.
o Domain Name depending upon scheme(alternatively, IP address).
The domain name or IP address gives the destination location for
the URL.
o An optional port number; if omitted, the default for the scheme is
used
o Path of the resource to be fetched or the program to be run. The
path is used to specify and perhaps find the resource requested. It
may be case-sensitive for non window based servers. Eg:
http://www.mudlle.ac.in/news.html
o A query string for scripts The query string contains data to be
passed to software running on the server. It may contain
name/value pairs separated by ampersands, for example ? first_
name= John & last_name=Doe.
o Optional fragment identifier that specifies a part or a position
within the overall resource or document. When used with HTTP, it
usually specifies a section or location within the page, and the
browser may scroll to display that part of the page.
□ When resources contain references to other resources, they can use
relative links to define the location of the second resource.
□ relative URLs are dependent on the original URL containing a
hierarchical structure against which the relative link is based.
□ the ftp, http, and file URL schemes are examples of some that can be
considered hierarchical, with the components of the hierarchy being
separated by"/"
□ A URL is a URI that, "in addition to identifying a resource, provides a
means of locating the resource by describing its primary access
mechanism.
BROWSERS
14
□ This process begins when user inputs the URI in the browser. Prefix of
the URI describes how to interpret the URI. Most URIs have resource
retrieved over Hyper text Transfer Protocol. Some web browsers also
support prefixes like FTP.
□ Once this is done, the HTML script is passed to the browser‘s layout
engine. To make the script interactive java script support is needed.
With this, browser can interpret text, images, video and interactive
scripts.
□ All major browsers allow users to access multiple information
resources at the same time in different windows or in tabs. Major
browsers include pop up blockers to prevent windows to open without
users consent.
□ Most major web browsers have these user interface elements in common:
Back and forward buttons to go back to the previous resource and forward
again.
o A history list, showing resources previously visited in a list
(typically, the list is not visible all the time and has to be
summoned)
o A refresh or reload button to reload the current resource.
o A stop button to cancel loading the resource. In some browsers, the
stop button is merged with the reload button.
o A home button to return to the user's homepage
o An address bar to input the Uniform Resource Identifier (URI) of
the desired resource and display it.
o A search bar to input terms into a search engine
o A status bar to display progress in loading the resource and also the
URI of links when the cursor hovers over them, and page zooming
capability.
• The usage share of web browsers is as shown below. (Source: Median
values)
□ Internet Explorer(43.55%)
□ Mozilla Firefox (29.0%; Usage by version number)
□ Google Chrome (13.89%)
□ Safari(6.18%)
□ Opera(2.74%)
□ Mobile browsers (4.45%)
□ Some special web browsers are listed below–
INTERNET EXPLORER
15
□ It was first released as part of the add-on package Plus! for Windows
95 that year. Later versions were available as free downloads, or in
service packs. It was part of later versions of windows operating
systems.
□ The latest stable release is Internet Explorer 9, which is available as a
free update for Windows 7, Windows Vista, Windows Server 2008
and Windows Server 2008R2.
□ Internet Explorer uses a componentized architecture built on the Component
Object Model (COM) technology. It consists of several major components,
each of which is contained in a separate Dynamic- link library (DLL)
and exposes a set of COM programming interfaces hosted by the
Internet Explorer main executable, ‗iexplore.exe‘
□ Internet Explorer uses a zone-based security framework that groups
sites based on certain conditions, including whether it is an Internet- or
intranet-based site as well as a user-editable white list. Security
restrictions are applied per zone; all the sites in a zone are subject to
the restrictions.
NETSCAPE NAVIGATOR
OPERA
□ Opera is a web browser and Internet suite developed by Opera
Software. The browser handles common Internet-related tasks such as
displaying web sites, sending and receiving e-mail messages,
managing contacts, chatting on IRC, downloading files via Bit Torrent,
and reading webfeeds.
□ Opera is offered free of charge for personal computers and mobile
phones. This is the most popular mobile phone browser and is not
packages in desktop operating system.
□ Features include tabbed browsing, page zooming, mouse gestures, and
an integrated download manager. Its security features include built-in
16
phishing and malware protection, strong encryption when browsing
secure websites, and the ability to easily delete private data such as
HTTP cookies.
□ Opera runs on a variety of personal computer operating systems,
including Microsoft Windows, Mac OS X, Linux, and FreeBSD
□ Opera includes built-in tabbed browsing, ad blocking, fraud protection,
a download manager and Bit Torrent client, a search bar, and a web
feed aggregator. Opera also comes with an e-mail client called Opera
Mail and an IRC chat client builtin.
□ Opera has several security features visible to the end user. One is the
option to delete private data, such as HTTP cookies, the browsing
history, and the cache, with the click of a button. This lets users erase
personal data after browsing from a shared computer.
□ Opera Mobile is an edition of Opera designed for smart phones and
personal digital assistants(PDAs)
MOZILLA FIREFOX
□ Mozilla Firefox is a free and open source web browser descended from
the Mozilla Application Suite and managed by Mozilla Corporation.
As of February 2011[update], Firefox is the second most widely used
browser with approximately 30% of worldwide usage share of web
browsers.
□ To display web pages, Firefox uses the Gecko layout engine, which
implements most current web standards.
□ The latest Firefox features[15] include tabbed browsing, spell
checking, incremental find, live book marking, a download manager,
private browsing, location-aware browsing (also known as
"geolocation") based exclusively on a Google service.
□ Firefox runs on various operating systems including Microsoft
Windows, Linux, Mac OS X, FreeBSD, and many other platforms.
CHROME
□ Chrome, the web browser by Google, is rapidly becoming popular due
to following features-
o SPEED: Chrome is designed to be fast in every possible way: It's
quick in staring up from the desktop, loading web pages and
running complex web applications.
o SIMPLICITY: Chrome's browser window is streamlined, clean
and simple. Chrome also includes features that are designed for
efficiency and ease of use. For example, you can search and
navigate from the same box, and arrange tabs however you wish.
o SECURITY: Chrome is designed to keep you safer and more
secure on the web with built-in malware and phishing protection,
auto updates to make sure the browser is up-to-date with the latest
17
security updates, and more. Learn more about Chrome's security
features.
□ Chrome is the first browser to incorporate machine translation in the
browser itself, without requiring additional plugins orextensions.
SEARCH ENGINE
WEB SERVER
APACHE
• Apache HTTP Server is a free and open-source web server that
delivers web content through the internet. It is commonly referred to as
Apache and after development; it quickly became the most popular
HTTP client on the web.
• The word, Apache, has been taken from the name of the Native
American tribe ‗Apache‘, famous for its skills in warfare and strategy
making.
• Apache is the most widely used Web Server application in Unix-like
operating systems but can be used on almost all platforms such as
Windows, OS X, OS/2, etc
18
• It is a modular, process-based web server application that creates a
new thread with each simultaneous connection. It supports a number
of features; many of them are compiled as separate modules and
extend its core functionality, and can provide everything from server
side programming language support to authentication mechanism.
Features of Apache:
▪ Handling of static files
▪ Loadable dynamic modules
▪ Auto-indexing
▪ Compatible with IPv6
▪ Supports HTTP/2
▪ FTP connections
▪ Bandwidth throttling
▪ Load balancing
▪ Session tracking
▪ URL rewriting
▪ Geolocation based on IP address and many more
IIS
19
PROXY SERVER
• A proxy server provides a gateway between users and the internet. It is
a server, referred to as an ―intermediary‖ because it goes between end-
users and the web pages they visit online.
• Proxies provide a valuable layer of security for your computer. They
can be set up as web filters or firewalls, protecting your computer from
internet threats like malware.
• Benefits of proxy server:
▪ Enhanced security
▪ Private browsing, watching, listening and shopping
▪ Access to location– specific content
▪ Prevent employees from browsing inappropriate or distracting sites
HTTP PROTOCOL
20
The HTTP protocol is a request/response protocol based on the
client/server based architecture where web browsers, robots and search
engines, etc. act like HTTP clients, and the Web server acts as a server.
Basic Features:
✓ HTTP is connectionless protocol
✓ HTTP is media independent
✓ HTTP is stateless
EXERCISE
❖❖❖❖
22
2
HTML5
Unit Structure :
Objectives
Introduction
Why HTML5?
Formatting text by using tags
Formatting text by lists
Formatting of backgrounds
Creating hyperlinks and anchors
Style sheets
CSS formatting text using style sheets
Formatting paragraphs using style sheets.
Summary
References
Exercise
OBJECTIVES:
INTRODUCTION
23
HTML5 is a standard for structuring and presenting content on the
World Wide Web.
Features of HTML5
It allows you to play a video and audio file. You can embed audio or video
on your web pages without resorting to third-party plugins.
It facilitates you to design better forms and build web applications that
work offline.
It provides you advance features for that you would normally have to write
JavaScript to do.
WHY HTML5?
Cross-Browser Compatibility
HTML5 is easy to implement and it works with CSS3. Today all
browsers support HTML5 tags and even IE6 understands the markup
<!doctype html> and will render the pages correctly.
Offline Browsing
HTML5 also offers offline browsing, which means that visitors can
load certain elements on a web page without an active internet connection.
With HTML5 offline caching we can still load core elements of the
websites and you can view them offline.
24
Video and Audio Support
With HTML5 technology, we no longer need to rely upon third-
party plugins in order to render audio and videos. You can forget about
Flash Player and other third-party media players and plugins. You can
make your videos and audio easily accessible with the new HTML5
<video> and <audio> tags.
Tag Description
<!DOCTYPE> tag:
HTML <!DOCTYPE> tag is used to inform the browser about the
version of HTML used in the document. It is called as the document type
declaration (DTD).
<article> tag :
The HTML <article> tag defines an independent self-contained
content in a document, page, application or a site.
Syntax
<article> ... </article>
The example below shows the <article>tag .
<article>
<h1>Introduction to HTML5</h1>
<p>. HTML5 is enriched with advance features which make it easy and
interactive for developer and users..</p>
</article>
Syntax
<header> ... </header>
The example below shows the <header>tag .
<header>
<h2>Sports</h2>
<p>Cricket sport is World's no.1 sport all over the world</p>
</header>
Syntax
<section> ... </section>
The example below shows the <section>tag .
<section>
<h1>Introduction to HTML5</h1>
<p>. HTML5 is enriched with advance features which make it easy and
interactive for developer and users..</p>
</section>
Syntax
<figcaption> ... </figcaption>
The example below shows the <section>tag .
<figure>
<imgsrc="discovery.jpg" alt="Space Shuttle">
<figcaption>NASA - Space Shuttle Discovery</figcaption>
</figure>
27
Ordered List or Numbered List:
In the ordered HTML lists, all the list items are marked with
numbers by default. It is known as numbered list also. The ordered list
starts with <ol> tag and the list items start with <li> tag.
<ol>
<li>Sachin</li>
<li>Kapil</li>
<li>Rahul</li>
<li>Rohit</li>
</ol>
FORMATTING OF BACKGROUNDS
28
HTML provides you following two good ways to decorate your
webpage background.
• HTML Background with Colors
• HTML Background with Images
Syntax
<tagnamebgcolor = "color_value"...>
The example below shows the <bgcolor>attribute.
<table bgcolor = "yellow" width = "100%">
<tr>
<td>
Syntax
<tagname background = "Image_url"...>
The example below shows the < background > attribute.
<table background = "/images/html.gif" width = "100%" height = "100">
<tr><td>
HTML links are hyperlinks. You can click on a link and jump to
another document. The HTML <a> tag defines a hyperlink. To make a
hyperlink in an HTML page, use the <a> and </a> tags, which are the tags
used to define the links.
Syntax
<a href = ".......... ">Hyperlink Text </a>
The example below shows the < a > tag.
<a href="Next.html">Next Page</a>
The HTML anchor tag defines a hyperlink that links one page to
another page. It can create hyperlink to other web page as well as files,
29
location, or any URL. The href attribute is used to define the address of
the file to be linked.
If we want to open that link to another page then we can use target
attribute of <a> tag. With the help of this link will be open in next page.
Syntax
<a href = ".......... ">Hyperlink Text </a>
The example below shows the < a > tag.
<a href="First.html">Home Page</a>
STYLE SHEETS
Text Color
The color of the text is defined by the CSS color property.
body {
color: #434343;
}
Text Alignment:
The text-align property is used to set the horizontal alignment of
the text.Text can be aligned in four ways: to the left, right, centre or
justified.
h1 {
text-align: center;
}
p{
31
text-align: justify;
}
Text Decoration:
The text-decoration property is used to set or remove decorations
from text. This property accepts one of the following values: underline,
overline, line-through, and none.
h1 {
text-decoration: overline;
}
h2 {
text-decoration: line-through;
}
h3 {
text-decoration: underline;
}
Text Transformation:
The text-transform property is used to set the cases for a text.Using
this property you can change an element's text content into uppercase or
lowercase letters.
h1 {
text-transform: uppercase;
}
h2 {
text-transform: capitalize;
}
h3 {
text-transform: lowercase;
}
Text Indentation:
The text-indent property is used to set the indentation of the first
line of text within a block of text. The size of the indentation can be
specified using percentage (%), length values in pixels, ems.
p{
text-indent: 100px;
}
indent: It can be set left and right only. Creates space that represents the
distance between the edge of the frame and content.
32
margin: It can be set top, bottom, left and right. Creates space that
represents the distance between the indent and the border.
border: It can be set top, bottom, left and right. A visual effect that
represents the distance between the margin and padding.
padding: It can be set top, bottom, left and right. Represents the distance
between the border and content.
Single line css using style attribute:
<p style="text-align:right">This is some text in a paragraph.</p>
Style paragraphs with CSS:
<style>
p{
color: navy;
text-indent: 30px;
text-transform: uppercase;
}
</style>
SUMMARY
• HTML5 chapter covers the key web components driving the future of
the Web. Harness the power of HTML5 to create web apps and
solutions that deliver state-of-the-art media content and interactivity
with new Audio, Video, and Canvas elements.
• HTML5 technologies are essential knowledge for today's web
developers and designers. New APIs such as Local Storage,
Geolocation, Web Workers, and more expand the Web as a platform,
allowing for desktop-like applications that work uniformly across
platforms
REFERENCES
2.11 EXERCISE
1) What do you understand by HTML tags? How many tags are required
to create a web page in HTML5?
2) Explain the various formatting tags in HTML5.
3) Explain the various new tags introduced by HTML5 in Media
Elements.
33
4) What is the correct usage of the following HTML5 semantic elements?
5) How many ways can a CSS be integrated as a web page?
6) What benefits and demerits do External Style Sheets have?
7) What are the limitations of CSS?
8) Explain what are the components of a CSS Style?
9) What do you mean by CSS selector?
10) Which property is used for controlling the image position in the
background?
11) What is the main difference between class selectors and id selectors?
12) Which property of a table is used to the appearance of the adjacent
borders?
13) How many formats you can display a CSS colour?
14) What do you mean by animation in CSS?
15) What are pseudo elements?
❖❖❖❖
34
UNIT - 2
3
NAVIGATION
Unit Structure
3.0 Objectives
3.1 Introduction
3.2 Planning site organization
3.3 Creating text based navigation bar
3.4 Creating graphics based navigation bar
3.5 Creating image map
3.6 Redirecting to another URL
3.7 Summary
3.8 Bibliography
3.9 Unit End Exercise
OBJECTIVES
INTRODUCTION
35
Types of web navigation
➔ The use of website navigation tools allow for a website's visitors to
experience the site with the most efficiency and the least
incompetence.
➔ A website navigation system is analogous to a road map which enables
webpage visitors to explore and discover different areas and
information contained within the website.
➔ There are many different types of website navigation: Hierarchical
website navigation the structure of the website navigation is built from
general to specific.
➔ This provides a clear, simple path to all the web pages from anywhere
on the website.
➔ Global website navigation Global website navigation shows the top
level sections/pages of the website.
➔ It is available on each page and lists the main content sections/pages of
the website.
Site map:
➔ A site map (or sitemap) is a list of pages of a web site accessible to
crawlers or users.
➔ It can be either a document in any form used as a planning tool for
Web design, or a Web page that lists the pages on a website, typically
organized in hierarchical fashion.
➔ Sitemaps make relationships between pages and other content
components. It shows shape of information space in overview.
Sitemaps can demonstrate organization, navigation, and labeling
system.
36
➔ A navigation bar is a user interface element within a webpage that
contains links to other sections of the website.
➔ We can use the navigation bar to visit other sections of the website.
Example:
<html>
<head>
<title> Navigation Bar </title>
</head>
<body>
<hr />
<a href="index.htm">Home</a>
<a href="tips.htm">Tips and Tricks</a>
<a href="problems.htm">Problem-Solving</a>
<a href="products.htm">Products</a>
<a href="about.htm">About Our Store</a>
<a href="contact.htm">Contact Us</a></p>
<hr />
</body>
</html>
Output:
Output:
➔ Text hyperlinks are clear and unambiguous, but not all that attractive.
➔ We might prefer to create a navigation bar that uses buttons or other
graphics instead of text links.
➔ We can create the graphics yourself in a graphics-editing program.
Follow these guidelines:
38
• Keep the size of each button small (150 pixels wide at the most).
• Make each button the same size and shape. They should vary only
in the text on them.
• Save each button as a separate file in GIF or JPG format.
➔ There are thousands of sites with free graphical buttons you can
download.
➔ Make several copies of a button you like, and then use a text tool in a
graphics-editing program to place different text on each copy.
Example:
<html>
<head>
<title> Navigation Bar </title>
</head>
<body>
<nav>
<hr>
<p style="margin:0px">
<a href="index.htm"><imgsrc="images/btn_home.gif"
style="border: none"></a>
<a href="tips.htm"><imgsrc="images/btn_store.gif"
style="border:none"></a>
<a href="problems.htm"><imgsrc="images/btn_contactus.gif"
style="border: none"></a>
<a href="products.htm"><imgsrc="images/btn_support.gif" style=
"border: none"></a>
<hr>
</nav>
</body>
</html>
Output:
Example:
<! DOCTYPE html>
<html>
<h3>Mapping an Image
<body>
<p>Click on the different continents of the map to know about
them.</p>
<imgsrc="world-map-151576_960_720.png" width="960"
height="492" alt="World Map" usemap="#worldmap">
<map name="worldmap">
<area shape="rect" coords="184, 36, 272, 158" alt="north america"
href="https://en.wikipedia.org/wiki/North_America">
<area shape="rect" coords="282, 215, 354, 367" alt="south america"
href="https://en.wikipedia.org/wiki/South_America">
<area shape="rect" coords="506, 151, 570, 333" alt="africa"
href="https://en.wikipedia.org/wiki/Africa">
<area shape="rect" coords="618, 42, 791, 162" alt="asia"
href="https://en.wikipedia.org/wiki/Asia">
40
<area shape="rect" coords="509, 44, 593, 110" alt="europe"
href="https://en.wikipedia.org/wiki/Europe">
<area shape="rect" coords="786, 288, 862, 341" alt="australia"
href="https://en.wikipedia.org/wiki/Australia_(continent)">
<area shape="rect" coords="249, 463, 760, 488" alt="antartica"
href="https://en.wikipedia.org/wiki/Antarctica">
</map>
</body>
</html>
Output:
41
Syntax:
<meta http-equiv = "refresh" content = " time ;url = l
Example:
<! DOCTYPE html>
<html>
<head>
<title>HTML Redirect</title>
<meta http-equiv="refresh"
content="5; url = https://old.mu.ac.in/distance-open-learning/" />
</head>
<body>
<h1 style="text-align: center; color: green ;">
IDOL Mumbai University
</h1>
Output:
SUMMARY
42
BIBLIOGRAPHY
1. https://learning.oreilly.com/library/view/microsoft-html5-
step/9780735656543/ch10s03.html
2. https://www.geeksforgeeks.org/html-mapping-image/
3.https://developer.mozilla.org/en-US/docs/Web/HTML/Element/nav
❖❖❖❖
43
4
LAYOUTS
Unit Structure :
Objectives
Introduction
HTML5 Semantic Tags
Creating Divisions
Creating HTML5 Semantic Layout
Positioning and Formatting Divisions
Summary
Bibliography
Unit End Exercise
OBJECTIVES
• Understand tags and the new HTML semantic tags in breaking a page
into sections.
• Learn to place the division in a specified location within your page.
• Create a division-based layout to your web page
• Create a HTML5 Semantic layout to your web page
INTRODUCTION
Semantic HTML tags are those that clearly describe their meaning
in a human- and machine-readable way.
44
List of new semantic tags:
The semantic tags added in HTML5 are:
• <article>
• <aside>
• <details>
• <figcaption>
• <figure>
• <footer>
• <header>
• <main>
• <mark>
• <nav>
• <section>
• <summary>
• <time>
Output:
45
In this way we can use other semantic tags for accomplishment of
our purpose.
<main>: It defines the main content of the document. The content inside
main tag should be unique.
CREATING DIVISIONS
HTML provides you a lot of ways to layout your page better. Web
designers today are geared towards a more appealing way of separating
content into sections which is called the division-based layout.
46
➔ It is mandatory to close the tag.
➔ Most websites have put their content in multiple columns, multiple
columns can be created by using <div> tags.
Advantages of the Division-based Layout:
➔ You can place layout styles externally, and then make the style changes
to many pages at once simply by modifying the style sheet.
➔ It reduces the number of lines of code needed to produce a page.
The id attribute:
➔ The id attribute can be used with any tag element. When used along
with the <div>tag, it will identify and define an area of your page.
➔ As a unique identifier, the id‘s value should only be used once on your
page.
➔ Start the id value with a letter followed by any of these: letters, number
digits (1- 9), dashes (-) and underscore (_). Don‘t use space or special
characters.
➔ The value is case-sensitive.
<div id=” title”>is different from <div id=” Title”>
47
Output:
The output does not show a layout. You can clearly see how your
page is divided into different sections.
48
Figure 4.1 Semantic tags layout
</p>
</article>
<aside>
<figure>
<imgsrc="Images/laptop.jpeg" height="100px" width="60px" />
<figcaption>Figure caption goes here</figcaption>
49
</figure>
<p>
I aside tag
</p>
</aside>
<section>
<h1>This is a section heading</h1>
<p>
Hello world! Hello world! Hello world!
</p>
</section>
<footer>
<hr />
Copyright (C) 2021. All rights reserved.
</footer>
</body>
</html>
header
{
padding:0px;
text-align: center;
}
aside
{
margin-top:5px;
background-color: #f0eaea;
padding:5px;
text-align: center;
font-style: italic;
border: double 3px #b200ff;
}
50
section
{
padding:5px;
border: dashed 3px #0026ff;
margin-top:5px;
}
footer
{
padding:5px;
text-align: center;
font-weight: bold;
}
nav
{
text-align: center;
}
ul li
{
display: inline;
padding-left:5px;
padding-right:5px;
text-align: left;
font-size:16px;
font-weight: bold;
}
Output:
51
POSITIONING AND FORMATING DIVISIONS
If you insert an additional <aside>division to your web page
layout, and place your division beside another either to the right or left,
you can easily use the float style rule.
Positioning Style –
If you want to place a division on a specific spot of your page, you
can use the position style rule.
Position Style:
You must use each of these values in combination with top, right,
bottom, and /or left style rule that specifies the location to which the
position style rules refers.
Example: To position a section at exactly 100px from the top of the page
and 200px from the left side, the syntax should be:
<section style= “top:100px; left:200px; position: absolute”>
Horizontal Lines
Horizontal Lines can be useful as a visual divider between sections of text
in a web page.
You can add a horizontal line after your header then add another
horizontal line before your footer.
This will clearly show your division in your web page.
You can simply add the horizontal line <hr> (horizontal rule) tag where
you want the line to appear.
52
SUMMARY
This chapter covered semantic mark-up elements of HTML5 that
can be used in the proper layout of the web pages. Unlike the <div>
element, the semantic elements are intended to be used for a specific
purpose. The elements we covered in this article include <header>, <nav>,
<footer>, <section>, <article> and <aside>.as well as we covered the div
tags with positioning.
BIBLIOGRAPHY
1. https://www.freecodecamp.org/news/semantic-html5-elements/
2. https://www.geeksforgeeks.org/html5-semantics/
3.https://www.slideshare.net/grayzon21/html5-create-divisions-in-a-web
❖❖❖❖
53
5
TABLES
Unit Structure
Objectives
Introduction
Creating simple table
Specifying the size of the table
Specifying the width of the column
Merging table cells
Using tables for page layout
Applying table borders
Applying background and foreground fills
Changing cell padding
Spacing and alignment
Summary
Bibliography
Unit End Exercise
OBJECTIVES
INTRODUCTION
54
CREATING SIMPLE TABLES
Example:
The following table is an example of a basic table with two rows and two
columns of data.
Html code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<table>
<tr>
<td>Department</td>
<td>Subject</td>
</tr>
<tr>
<td>IDOL</td>
<td>Web Programming</td>
</tr>
</table>
</body>
</html>
55
Output:
• The width attribute specifies the width of a table. The width can be set
either as an absolute value in pixels, or as in percentage (%).
• If the width attribute is not set, it will take up the space of longest
single word in each cell.
• Table width in pixels:<table width=100>
• Table width in percentage (%): <table width=100%>
Example:
Html code:
<html>
<body >
<table width=100>
<tr>
<td>
Table width is 100 pixels
</td>
</tr>
</table>
<br>
<table width=100%>
<tr>
<td>
Table width is 100 %
</td>
</tr>
</table>
</body>
</html>
Output:
• The above HTML code display two tables, one is 100-pixel width and
another one is 100% width.
56
• First table is only 100-pixel width in any changes in browser window
state, while other table will always stretch the full width of the
window.
Example:
Html code
<html>
<head>
</head>
<body>
<table border="1" width="100%">
<col style="width:40%">
<col style="width:30%">
<col style="width:30%">
<tr>
<th>Fruits</th>
<th>Vitamin A</th>
<th>Vitamin C</th>
</tr>
<tr>
<th>Apples</th>
<td>98 ui</td>
<td>8.4 mg</td>
</tr>
<tr>
<th>Oranges</th>
<td>295 ui</td>
<td>69.7 mg</td>
</tr>
</table>
</body>
</html
Output:
57
MERGING TABLE CELLS
• We can merge two or more table cells in a column by using
the colspan attribute in a <td> HTML tag (table data).
• To merge two or more row cells, use the rowspan attribute.
Colspan:
• The colspan attribute defines the number of columns a cell should span
(or merge) horizontally.
• That is, we merge two or more Cells in a row into a single Cell.
<td colspan=2 >
The above code will merge two Cells as one Cell horizontally.
HTML code:
<html>
<body >
<table border=1 >
<tr>
<td colspan=2 >Merge</td>
</tr>
<tr>
<td>Third Cell</td>
<td>Forth Cell </td>
</tr>
</table>
</body>
</html>
Rowspan:
• The rowspan attribute specifies the number of rows a cell should span
vertically.
58
• That is, we merge two or more Cells in the same column as a single
Cell vertically.
<td rowspan=2 >
The above code will merge two Cells as one Cell vertically.
HTML code:
<html>
<body >
<table border=1 >
<tr>
<td>First Cell</td>
<td rowspan=2 >Merged</td>
</tr>
<tr>
<td valign=middle>Third Cell </td>
</tr>
</table>
</body>
</html>
🡺Rowspan merged Cells vertically, that is from top to bottom.
• HTML tables are most often used to define the layout of an entire Web
page.
• If we want to design a page that displays text in newspaper style
columns, or separates the page into distinct sections, we‘ll find tables
an essential and useful tool.
Output:
• Each table, row, and cell is its own distinct area, and each can have its
own background.
• For example, you might want to apply a different color background to
a heading row to make it stand out, or change the color of every other
line in a listing to help visitors track a line across the table.
• Table elements support the bgcolor attribute.
• To specify a background color for all of the cells in a table, all of the
cells in a row, or for individual cells, by adding the bgcolor attribute to
either the <table>, <tr>, <td>, or <th> tags as follows:
<table bgcolor= “color”>
<tr bgcolor= “color”>
<td bgcolor= “color”>
<th bgcolor= “color”>
• color is either a color name or hexadecimal color value
60
Specifying Table, Row, and Cell Colors:
Html code
<html>
<table border="5" bgcolor="white">
<caption><b>State and Capital City</b></caption>
<tr bgcolor="yellow">
<th > State</th>
<th> City</th>
</tr>
<tr >
<td bgcolor="lightblue" > Maharashtra</td>
<td> Mumbai</td>
</tr>
<tr >
<td > Karnataka</td>
<td bgcolor="lightgreen"> Bangalore</td>
</tr>
</table
</html>
Output:
61
Example:
<html>
<table border="7" bordercolor="lightblue" background="parch.jpg" >
<caption><b>State and Capital City</b></caption>
<tr style="color: blue;">
<th > State</th>
<th> City</th>
</tr>
<tr >
<td > Maharashtra</td>
<td> Mumbai</td>
</tr>
<tr >
<td > Karnataka</td>
<td style="color: red;"> Bangalore</td>
</tr>
</table
</html>
Output:
• To control the space between the table text and the cell borders, add
the cellpadding attribute to the table tag.
• The syntax for this attribute is:
<table cellpadding=“value”>
– value is the distance from the table text to the cell border,
as measured in pixels
– the default cell padding value is 1 pixel
• Cell padding refers to the space within the cells.
62
PACING AND ALIGNMENT
• The cellspacing attribute controls the amount of space inserted
between table cells.
• The syntax for specifying the cell space is:
<table cellspacing= “value”>
– value is the width of the interior borders in pixels
– the default cell spacing is 2 pixels
– Cell spacing refers to the space between the cells.
63
SUMMARY
BIBLIOGRAPHY
1.https://its.temple.edu/creating-tables-html
2.http://www.corelangs.com/html/tables/width-height.html
3.https://htmlreference.io/tables/
4.http://www.corelangs.com/html/tables/colspan-rowspan.html
5.https://www.teachucomp.com/add-table-borders-using-
html5/#:~:text=To%20assign%20a%20border%2C%20insert,and%20not
%20the%20individual%20cells.
❖❖❖❖
64
6
FORMS AND MEDIA
Unit Structure
Objectives
Introduction
Creating basic form
Using check boxes and option buttons
Creating lists
Additional input types in HTML5
Audio and Video in HTML5
HTML multimedia basics
Embedding video clips
Incorporating audio on web page
Summary
Bibliography
Unit End Exercise
OBJECTIVES
1. To gain familiarity with what web forms are, what they are used for,
how to think about designing them, and the basic HTML elements
we'll need for simple cases.
2. To understand the newer input type values available to create native
form controls, and how to implement them using HTML.
3. To learn how to embed video and audio content into a webpage, and
add captions/subtitles to video.
INTRODUCTION
The first article in our series provides you with your very first
experience of creating a web form, including designing a simple form,
implementing it using the right HTML form controls and other HTML
elements, adding some very simple styling via CSS, and describing how
data is sent to a server. We'll expand on each of these subtopics in more
detail later on in the module.
65
CREATING BASIC FORMS
• Our form will contain three text fields and one button.
• We are asking the user for their name, their e-mail and the message
they want to send.
• Hitting the button will send their data to a web server.
66
• All forms start with a <form> element, like this:
<form action="/my-handling-form-page" method="post">
</form>
• This element formally defines a form.
• The action attribute defines the location (URL) where the form's
collected data should be sent when it is submitted.
• The method attribute defines which HTTP method to send the data with
(usually get or post).
• The data entry portion contains three text fields, each with a
corresponding <label>:
• The input field for the name is a single-line text field.
• The input field for the e-mail is an input of type email: a single-line text
field that accepts only e-mail addresses.
• The input field for the message is a <textarea>; a multiline text field.
Output:
67
USING CHECK BOXES AND OPTION BUTTONS
<input type="checkbox">:
• The <input type="checkbox"> defines a checkbox.
• The checkbox is shown as a square box that is ticked (checked) when
activated.
• Checkboxes are used to let a user select one or more options of a
limited number of choices.
Example:
<html>
<head>
<title> Input type = "checkbox" </title></head>
<body>
<h2> input type="checkbox" </h2>
<p>Choose your Ice-cream flavours :</p>
<div>
<input type="checkbox" id="Vanilla" name="Vanilla"checked>
<label for="Vanilla">Vanilla</label>
</div>
<div>
<input type="checkbox" id="horns" name="Strawberry">
<label for="Strawberry">Strawberry</label>
</div>
</body>
</html>
Output:
Option Buttons:
• Option buttons are sometimes called Radio Buttons, and they force the
user into choosing only one item in a list, such as a Male/Female
option, or selecting a payment method.
• The Option button HTML look like this:
<INPUT TYPE="Radio" Name="Gender" Value="Male">
68
Male
<INPUT TYPE="Radio" Name="Gender"
Value="Female">Female
• After typing the INPUT tag, the word TYPE comes next. For Option
Buttons, the type is "Radio".
• The NAME is definitely needed here, and note that the NAME for
both in our code above is "Gender".
• We use the same name for each group of option buttons we are adding
to your form.
• So if you wanted payment option buttons, the code might be this:
<INPUT TYPE="Radio" Name="payment" Value="CC">
Credit Card
<INPUT TYPE="Radio" Name="payment" Value="DC">
Debit Card
<INPUT TYPE="Radio" Name="payment" Value="PP">
PayPal
• This time, each radio button has the name "payment".
• The reason you keep the same name for each group of option buttons
is simply to distinguish one group of option buttons from another.
• The VALUE attribute is quite useful.
• When the user submits the form to us using the Submit button, these
VALUES are going to be returned.
• If we just got Radio1 and Radio2, you won't know (or won't
remember, more likely) which option the user has selected.
• Manipulating values with scripts is also a lot easier if the Value is the
same as the text the user sees.
• If you want to have a default option button selected, use the word
"Checked":
<INPUT TYPE="Radio" Name="payment" Value="CC">
Credit Card
<INPUT TYPE="Radio" Name="payment" Value="DC">
Debit Card
<INPUT TYPE="Radio" Name="payment"
Value="PP" Checked>PayPal
• Attaching a label to each button is very useful for your visitors.
• When the label is clicked it will select the option button it is named
for:
Example:
<html>
<head>
<title> Input type = "Option" </title></head>
<body>
<h2> input type="Option" </h2>
69
<p>Choose your Payment option :</p>
<div>
<LABEL FOR="R1">Credit Card</LABEL>
<INPUT TYPE="Radio" Name="payment" ID="R1"
Value="Credit Card">
</div>
<div>
<LABEL FOR="R2">Debit Card</LABEL>
<INPUT TYPE="Radio" Name="payment" ID="R2" Value="Debit
Card">
</div
<div>
<LABEL FOR="R3">PayPal</LABEL>
<INPUT TYPE="Radio" Name="payment" ID="R3" Value="PayPal"
Checked>
</div>
</body>
</html>
Output:
CREATING LIST
Example:
<!DOCTYPE html>
<html>
<body>
<h2>Grocery list</h2>
<ul>
<li>Bread</li>
<li>Eggs</li>
<li>Milk</li>
<li>Coffee</li>
</ul>
</body>
</html>
Output:
Example:
<! DOCTYPE html>
<html>
<body>
<h2>Grocery List</h2>
<ol>
<li>Bread</li>
<li>Eggs</li>
<li>Milk</li>
<li>Coffee</li>
</ol>
</body>
</html>
71
Output:
Example:
<! DOCTYPE html>
<html>
<body>
<h2>A Description List</h2>
<dl>
<dt>Coffee</dt>
<dd>- 500 gms</dd>
<dt>Milk</dt>
<dd>- 1 ltr Tetra Pack</dd>
</dl>
</body>
</html>
Output:
72
• When this type is used, the user is required to type a valid email
address into the field.
• Any other content causes the browser to display an error when the
form is submitted. You can see this in action in the below screenshot.
Search field:
• Search fields are intended to be used to create search boxes on pages
and apps.
• This type of field is set by using the value search for
the type attribute:
<input type=‖search‖ id= ―search‖ name=‖ search‖>
• The main difference between a text field and a search field is how the
browser styles its appearance.
• Often, search fields are rendered with rounded corners; they also
sometimes display an "Ⓒ", which clears the field of any value when
clicked.
• The below screenshots show a non-empty search field in Firefox 71,
Safari 13, and Chrome 79 on macOS, and Edge 18 and Chrome 79 on
Windows 10.
• Note that the clear icon only appears if the field has a value, and,
apart from Safari, it is only displayed when the field is focused.
73
Phone number field
A special field for filling in phone numbers can be created
using tel as the value of the type attribute:
< input type=‖tel‖id= ―tel‖name=‖ tel‖>
• When accessed via a touch device with a dynamic keyboard, most
devices will display a numeric keypad when type="tel" is
encountered, meaning this type is useful whenever a numeric keypad
is useful, and doesn't just have to be used for telephone numbers.
URL field
A special type of field for entering URLs can be created using the
value url for the type attribute:
< input type=‖url‖ id= ―url‖name=‖ url‖>
• It adds special validation constraints to the field.
• The browser will report an error if no protocol (such as http:) is
entered, or if the URL is otherwise malformed.
Numeric field:
• Controls for entering numbers can be created with
an <input> type of number.
• This control looks like a text field but allows only floating-point
numbers, and usually provides buttons in the form of a spinner to
increase and decrease the value of the control.
• Let's look at some examples. The first one below creates a number
control whose value is restricted to any value between 1 and 10, and
whose increase and decrease buttons change its value by 2.
< input type=‖number‖ id= ―number‖name=‖ number‖ min= ―1‖
max= ―10‖ step= ―2‖ >
• The number input type makes sense when the range of valid values is
limited, for example a person's age or height.
74
• <input type="datetime-local"> creates a widget to display and pick a
date with time with no specific time zone information.
< input type= ―datetime-local‖ id= ―datetime‖name=‖ datetime‖>
<video controls
<source src= ―sample.mp4‖ type= ―video /mp3>
<p> your browser doesn‘t support HTML5 video. Here is a <a
href= ―sample.mp4‖> link to the video</a> instead.<p>
</video>
controls
Users must be able to control video and audio playback (it's
especially critical for people who have epilepsy.) You must either use
the controls attribute to include the browser's own control interface
75
• This takes up less space than a video player, as there is no visual
component — you just need to display controls to play the audio. Other
differences from HTML video are as follows:
• The <audio> element doesn't support the width/height attributes —
again, there is no visual component, so there is nothing to assign a
width or height to.
• It also doesn't support the poster attribute — again, no visual
component
What is Multimedia?
• Multimedia comes in many different formats.
• It can be almost anything you can hear or see, like images, music,
sound, videos, records, films, animations, and more.
• Web pages often contain multimedia elements of different types and
formats.
• A combination of video and audio files can also be used in websites to
gain popularity in terms of viewership or provide information and
entertainment to the users.
• HTML helps you to add multimedia files on your website by providing
various multimedia tags.
• These tags include AUDIO, VIDEO, EMBED, and OBJECT.
• The AUDIO tag is used to display the audio file on the Web page,
whereas the VIDEO tag is used to display the video files on the Web
page.
• The EMBED and OBJECT tags display the multimedia files on a Web
page as well as embed the files from other websites.
Browser Support:
• The first web browsers had support for text only, limited to a single
font in a single color.
• Later came browsers with support for color, fonts, images, and
multimedia!
76
Multimedia Formats:
Multimedia elements (like audio or video) are stored in media files.
• The most common way to discover the type of a file, is to look at the
file extension.
• Multimedia files have formats and different extensions like: .wav,
.mp3, .mp4, .mpg, .wmv, and .avi.
Example:
<!DOCTYPE html>
<html>
<body>
<h1 style="color: green;">
IDOL Video Songs
</h1>
<h3>
How to embed Video in a HTML document?
</h3>
<video controls width= "400" height= "300">
<source src="aapla.mp4" type= "video/mp4">
</video>
</body>
</html>
77
• The HTML5 video player supports three formats, but not all of them
have the same level of browser support.
• This means you can add sources in different formats to ensure the
user can see the video.
• It is always recommended to add HTML5 video controls to your
player.
• Using special buttons in the player window, the user can manually
start and stop the video, skip to specific place using the slider, or
toggle between window and full screen video display.
• To add video controls, include the controls attribute.
Player Dimensions:
• To define the size of your player, you can use the height and width
attributes.
• The video will keep the same aspect ratio.
• In the HTML5 video example above, the values are set to 300 for the
height and 400 for the width.
Syntax:
<audio>
<source src="sample.mp3" type="audio/mpeg">
</audio>
Example:
<!DOCTYPE html>
<html>
<body>
<h1 style="color: green;">
IDOL Audio Songs
</h1>
<h3>
How to embed audio in a HTML document?
</h3>
<audio controls>
78
<source src="Test.mp3" type="audio/mp3">
<source src="Test.ogg" type="audio/ogg">
</audio>
</body>
</html>
Output:
SUMMARY
• In this chapter we have studied basic input types of html and new
HTML5 input type as well as controls.
• We build the form by using controls and input types.
• We focusing on multimedia to embed video and audio in to web pages.
BIBLIOGRAPHY
1. https://developer.mozilla.org/en-US/docs/Learn/Forms/Your_first_form
2. https://www.w3schools.com/tags/att_input_type_checkbox.asp
3. https://www.homeandlearn.co.uk/WD/wds8p5.html
4. https://www.tutorialspoint.com/html5/html5_audio_video.htm
5. https://www.bitdegree.org/learn/html5-video-player
6.https://www.geeksforgeeks.org/how-to-embed-audio-element-in-a-html-
document/
7. https://codescracker.com/html/html-multimedia-working.htm
79
Unit -III
7
JAVASCRIPT
Unit Structure :
Objective
Introduction
Client side JavaScript
Server side JavaScript
JavaScript objects
JavaScript security
Operators
Assignment
Arithmetic
Comparison
Modulus
Increament
Decreament
Unary negation
Logical operators
Short circuit evaluation
String operators
Special operators
Conditional operators
Comma operators
Delete
New
This
Void
Statements
Break
Comment
Continue
Delete
Do while
Export
For
For in
80
Function
Ifelse
Import
Labelled
Return
Switch
Var
While
With
Core java script
Array
Boolean
Object
Date
Math
Number
Object
String
reg Exp
OBJECTIVE
INTRODUCTION
81
□ Javascript is originally a scripting language developed by European
Computer Manufacturer‘s association (ECMA)
□ Javascript that runs at the client side (ie at the client‘s browser) is
client side java script (CCJS) and javascript that runs at the server is
serverside java script (SSJS)
□ Javascript being object oriented, uses number of built in javascript as
well as objects can be created.
□ Every object has properties and methods. Property is value(s)
associated with an object. Methods are actions associated with an
object.
□ Example:<scripttype="text/javascript">
document. write("This message is written by JavaScript");
</script>
in above example, ‗document‘ is object and write() is a method of
document object.
□ Javascript runs in a web browser, and when a script written by a third
party is executed on the browser, there is a risk of running a spyware
or a virusprogram.
□ Hence, each time javascript is loaded on the browser implements a
security policy designed to minimise the risk of such unknown code.
□ Security policy is set of rules governing what scripts can do under
which circumstances.
□ Modern javascript security is based upon Java. Scripts downloaded are
isolated from the operating system and then executed. This is known
as the ‗sandbox‘ model. Some scripts are often stored randomly here
and there. And hence, many times obtain more power than expected by
design or by accident.
□ Scripts in general are given limited access and more access is only
given with the user consent. Taking a consent for every execution is
not a practical solution.
□ Scripts from ‗trusted‘ source are many times excluded from this
consent procedure.
□ A policy called ‗same origin‘ does not block scripts coming from the
same origin as trusted scripts. This same origin check is performed on
all methods of windows object, also on embedded and externally
linked objects.
82
JAVASCRIPT OPERATORS
83
! Not Negation !(x==y) TRUE As x and y are
not equal.
String
+ Concatenation Connects If x = ―5‖ x+y=―55‖
two strings. and y= ―5‖
then
Conditional
? Variable If a = 0, a =8, If condition is
=(condition)? b=7 b =7 satisfied, first
value1:value2 a=(b= value is
=10)?5:8 assigned, else
the second
value is
assigned.
Short circuit evaluation
&& Sand Short circuit If x = 0; x = 66 If p is not null,
and p = 66 then assign
x=p && value of p to x.
p.getvalue()
84
New Creates new var x= new x becomes new instance of
instance of Fn() function Fn and gets all its
the object properties and methods.
Void Evaluates Void expr Undefined
expression .
and
return
s undefined
Output
85
JAVASCRIPT STATEMENTS
86
JavaScript Comments
87
□ Rules for JavaScript variable names:
o Variable names are case sensitive (y and Y are two different
variables)
o Variable names must begin with a letter or the underscore character
□ Creating variables in JavaScript is most often referred to as "declaring"
variables.
□ You declare JavaScript variables with the var keyword like varx;
□ After the declaration shown above, the variables are empty (they have
no values yet). However, you can also assign values to the variables
when you declare them like var x = 10; After the execution of this
statement, the variable x will hold the value10
□ A variable declared within a JavaScript function becomes LOCAL
and can only be accessed within that function. (the variable has
localscope).
□ You can have local variables with the same name in different
functions, because local variables are only recognized by the function
in which they are declared.
□ Local variables are destroyed when you exit the function.
□ Variables declared outside a function become GLOBAL, and all
scripts and functions on the web page can access it.
□ Global variables are destroyed when you close thepage.
□ If you declare a variable, without using "var", the variable always
becomes GLOBAL.
□ If you assign values to variables that have not yet been declared, the
variables will automatically be declared as global variables.
□ All javascript operators can be used with variables
□ Example –
88
Conditional statements
□ Conditional statements are used to perform different actions based on
different conditions.
□ In JavaScript we have the following conditional statements:
□ If statement - This statement is used to execute some code only if a
specified condition is true.
□ Syntax:
if (condition)
{
code to be execute difconditionis
true
}
□ If...elsestatement-This statement is used to execute some code if the
condition is true and another code if the condition is false
□ Syntax:
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
□ If...else if ............... else statement - This statement is used to select
one of many blocks of code to be executed
□ Syntax:
if (condition1)
{
code to be executed if condition1 is true
}
89
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if neither condition1 nor condition2 istrue
}
Example
Output
90
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
}
Example:
Output
91
Loop statements
□ Loops execute a block of code a specified number of times, or while a
specified condition is true.
□ Often when you write code, you want the same block of code to run
over and over again in a row. Instead of adding several almost equal
lines in a script we can use loops to perform a task like this.
□ In JavaScript, there are two different kind of loops:
o for - loops through a block of code a specified number of times. It can
be used only when it is known in advance, how many times we have to
run the loop.
o while - loops through a block of code while a specified condition is
true.
□ For Loop Syntax:
for (variable=startvalue;variable<=endvalue;variabl
e=variable+increment)
{
code to be executed
}
□ Example:
Javascript given below will print 5 numbers. Each time, value of
the variable is incremented by 1.
92
□ While loop syntax
while(var<=end value)
{
code to be executed
}
□ While loop can be used with any comparison operator.
□ Do While loop is a variation to the while loop. In this case block will
be executed at least once, as the statements are executed before the
condition is tested. Syntax for do while is as follows–
do
{
code to be executed
}
while (var<=endvalue);
□ Consider the example where number is printed after incrementing
itby1.This is performed while the number is less than orequalto
5. Script and the outputs with while and do while loop are as given below
<html>
<body>
<script type="text/javascript">var i=6;
do
{
document.write("The number is " + i); document.write("<br />");
i++;
}
while (i<=5);
</script>
</body>
</html>
93
□ Changes in script with just while loop and corresponding output--
while (i<=5)
{
document.write("The number is " + i); document.write("<br />");
i++;
}
document.write(―value of i is printed outside the loop‖);
document.write(―<br>\‖ + i);
94
Function
□ Function is a segment of program that performs a given task.
□ A function contains code that will be executed by an event or by a call
to the function.
□ You may call a function from anywhere within a page (or even from
other pages if the function is embedded in an external JavaScript file).
□ Functions can be defined both in the <head> and in the <body> section
of a document.
□ However, to assure that a function is read/loaded by the browser
before it is called, it should be put functions in the<head>section.
□ Syntax of the function is as follows–
function name(var1,var2,...,varX)
{
some code
}
□ Function always includes parenthesis after the name of function‗()‘
95
□ Function calls are case sensitive as javascript is case sensitive.
□ The return statement is used to specify the value that is returned from
the function.
So, functions that are going to return a value must use the return
statement.
□ If a variable is declared using "var", within a function, the variable can
only be accessed within that function.
□ The variable is destroyed once function call is over. These variables
are called local variables. Local variables can have the same name in
different functions, because each is recognized only by the function in
which it is declared.
□ If a variable is declared outside a function, all the functions on your
page can access it.
□ The lifetime of these variables starts when they are declared, and ends
when the page is closed.
□ Following is an example of function. Function products computes and
returns product of variables a and b.
□ Basic advantage of using a function is reusability. Same task can be
performed again and again simply by calling the function which
performs the task.
Example:
96
COREJAVASCRIPT
Math object –
□ The Math object allows you to perform mathematical tasks.
□ The Math object includes several mathematical constants and methods.
▪ round() – rounds the number to nearest integer value.
▪ random() - returns a random number between 0 and1.
▪ max() - returns the number with the highest value of two specified
numbers.
▪ min() - returns the number with the lowest value of two specified
numbers.
Array –
□ An Array is an ordered collection of data values.
□ In JavaScript, an array is just an object that has an index to refer to its
contents. In other words, the fields in the array are numbered, and you
can refer to the number position of the field.
□ The array index is included in square brackets immediately after the
array name. In JavaScript, the array index starts with zero, so the first
element in an array would be array Name[0], and the third would be
array Name[2].
□ JavaScript does not have multi-dimensional arrays, but you can nest
them, which is to say, an array element can contain another array.
□ You access them listing the array numbers starting for the outmost
array and working inward. Therefore, the third element (position 2) of
or inside the ninth element (position 8) would bearrayName[8][2].
99
SUMMARY
□ JavaScript is light weighted programming language used for small
applications.
□ Javascrit is object based programming language made inC++.
□ Javascript can be executed either on client side browser or on server
side browser.
□ Javascripts can be downloaded and run and carry a threat of virus
attack. Security of javascript depends upon the security of java
language. The process of executing the javascript code after isolating it
from the operating system is called ‗sandbox‘ model.
□ Different types of javascript operators help perform various arithmetic,
logical, string and other types of functions.
□ Browser sequentially executes javascript statements of various types
such as conditional and loop
□ statements. Some of loop statements are while, do while, switch
statement etc.
□ Number, Boolean, string are few data types used in JavaScript.
EXERCISE
❖❖❖❖
100
8
DOCUMENT AND ITS ASSOCIATED
OBJECTS &
EVENT AND EVENT HANDLERS
Unit Structure :
Objective
Document and associated objects
Document
Link
Area
Anchor
Image
Applet
Layer
Events and Event Handlers
General information about events
Defining event handlers
Event
on Abort
on Blur
on Change
on Click
on DblClick
on Drag Drop
on Error
on Focus
on Key Down
on Key Press
on Key Up
on Load
on Mouse Down
on Mouse Move
on Mouse Out
on Mouse Over
on Mouse Up
on Move
on Reset
101
on Resize
on Select
on Submit
on Unload
8.1 OBJECTIVE
Document
• Each HTML document loaded into a browser window becomes a
Document object.
• The Document object provides access to all HTML elements in a
page, from within a script.
• The Document object is also part of the Window object, and can be
accessed through the ‗window. Document‘ property.
• Document object is part of document object model.
• This model has a fixed hierarchy, where topmost object in the
hierarchy is Browser itself.
• After browser window object and inside window, as shown below,
comes the document object.
• Relation of document object to the window object can be depicted in
the fig given below –
102
|-> Document
|-> Anchor
|-> Link
|-> Images
|->Tags
|->Form
|-> Text-box
|-> Text Area
|-> Radio Button
|-> Check Box
|->Select
|->Button
Fig 8.3 Script and output Demonstrating write method and title
property of Document object.
104
Fig 8.4 Script Demonstrating the Document. open() method to open a
text stream
Fig 8.5 Output of the script Before and After Clicking the „New
Document‟ button.
105
Link
• The Link object represents an HTML link element.
• The link element must be placed inside the head section of an HTML
document, and it specifies a link to an external resource.
• In other words, link tag defines how a click on object can redirect or
take the browser window to a new location specified by the address
specified.
• A common use of the <link> tag is to link to external style sheets.
• Some of the properties of javascript link objects are as given below—
charset: -Sets or returns the character encoding of a linked document
href: -Sets or returns the URL of a linked document
hreflang:- Sets or returns the language code of the linked document
media: - Sets or returns the media type for the link element
type: - Sets or returns the content type of the linked document
• In addition to above properties, link object supports all standard
properties like id, length, chartypeetc.
106
Fig 8.6 Script and Outputs Demonstrating length property of link
Area
• The Area object represents an area inside an HTML image-map (an
image-map is an image with clickable areas).
• For each <area> tag in an HTML document, an Area object is created.
• In addition to standard properties and methods, javascript area object
supports following properties –
alt: Sets or returns the value of the alt attribute of an area
cords: Sets or returns the value of the coords attribute of an area
hash: Sets or returns the anchor part of the href attribute value
host: Sets or returns the hostname: port part of the href attribute value
hostname: Sets or returns the hostname part of the href attribute value
href: Sets or returns the value of the href attribute of an area
noHref: Sets or returns the value of the no href attribute of an area
pathname: Sets or returns the pathname part of the href attribute value
port: Sets or returns the port part of the href attribute value
protocol: Sets or returns the protocol part of the href attribute value
search: Sets or returns the query string part of the href attribute value
shape: Sets or returns the value of the shape attribute of an area
target: Sets or returns the value of the target attribute of an area
107
• Following example shows an image map and returns the shape of an
area marked in the image map.
Anchor
• The Anchor object represents an HTML hyperlink.
• For each <a> tag in an HTML document, an Anchor object is created.
• An anchor allows you to create a link to another document (with the
href attribute), or to a different point in the same document (with the
name attribute).
• You can access an anchor by using get Element ById(), or by
searching through the anchors[] array of the Document object.
• In addition to standard properties and methods, javascript anchor
object supports following properties–
108
charset Sets or returns the value of the charset attribute of a link href Sets
or returns the value of the href attribute of a link hre flang Sets or returns
the value of the hre flang attribute of a link name Sets or returns the value
of the name attribute of alink
rev Sets or returns the value of the rev attribute of a link target Sets or
returns the value of the target attribute of a link type Sets or returns the
value of the type attribute of alink
109
align : Sets or returns the value of the align attribute of an image
alt : Sets or returns the value of the alt attribute of an image
border : Sets or returns the value of the border attribute of an
image
complete : Returns whether or not the browser is finished loading an
image
height : Sets or returns the value of the height attribute of an image
hspace : Sets or returns the value of the hspace attribute of an image
longDesc : Sets or returns the value of the longdesc attribute of an image
lowsrc : Sets or returns a URL to a low-resolution version of an image
name : Sets or returns the name of an image
src : Sets or returns the value of the src attribute of an image
useMap : Sets or returns the value of the use map attribute of an image
vspace : Sets or returns the value of the vspace attribute of an image
width : Sets or returns the value of the width attribute of an image
110
Fig 8.9 Before and after using the anchor link.
Image
• The Image object represents an embedded image.
• For each <img> tag in an HTML document, an Image object is
created.
• Notice that images are not technically inserted into an HTML page,
images are linked to HTML pages. The <img> tag creates a holding
space for the referenced image.
• Image object, in addition to the standard properties and methods,
supports following properties and events.
• Image ObjectEvents
111
• Alt attribute gives the text to be displayed, if the image can not be
displayed.
• Also, a lower version of image to speed up loading, can be shown
using a lowsrc option attribute.
Example:
Fig 8.10 source code for demonstrating some image properties and
attributes.
112
Fig 8.12 After click of the command buttons, border added and a
increased sized image.
Applet
• Applet tag was used in earlier version of HTML (HTML4) to embed
anjavaappletina browser. It is not supported in HTML
5.0 and is replaced by the object tag.
• The <object> tag defines an embedded object within an HTML
document. It is used to embed multimedia (like audio, video, Java
applets, ActiveX, PDF, and Flash) in your webpages.
• You can also use the <object> tag to embed another webpage into your
HTML document.
• You can use the <param> tag to pass parameters to plugins that have
been embedded using the <object>tag.
• An object element must appear inside the body element. The text
between the <object> and </object> is an alternate text, for browsers
that do not support this tag.
• At least one of the "data" and "type" attributes MUST be defined
where data specifies a URL that refers to the object's data and type
Specifies the MIME type of data specified in the data attribute.
(Multipurpose Internet Mail Extensions (MIME) is an Internet
113
standard that extends the format of email to support Text in
character sets other than ASCII, Non-text attachments, Message bodies
with multiple parts, Header information in non-ASCII character sets.
□ They are JavaScript code that are not added inside the <script> tags,
but rather, inside the html tags, that execute JavaScript when
something happens, such as pressing a button, moving your mouse
over a link, submitting a formetc.
□ The basic syntax of these event handlersis:
name_of_handler="JavaScript code here"
□ For example:
□ When events are associated with functions, the functions are written in
the head section within the <script> tag and are called from the event
handlers.
Example :
<html>
<body>
<h1 onclick="this.innerHTML='Welcome to
EventHandlers'">Click on this text</h1>
</body>
</html>
114
□ This code will generate following output–
EVENT
Fig 8.13 Script to demonstrate on mouse over event and its event
handler
116
Fig 8.14 Newly Loaded page
117
Fig 8.17 Cursor pointing venus.
EXERCISES
❖❖❖❖
118
UNIT - IV
9
BASICS OF PHP
Unit Structure :
Objectives
Introduction
Why PHP and My SQL?
Server-side scripting
PHP syntax and variables
Comments, types
Summary
References
Unit End Exercise
OBJECTIVES:
INTRODUCTION
119
• Why PHP?
Following are some reasons why PHP is popular now days
120
🡺MySQL is a first choice of PHP developers. As an open-source
Relational Database Management System (RDBMS) that uses SQL
language, MySQL database helps to automate data retrieving and provide
great support in PHP MySQL web application development.
121
SERVER-SIDE SCRIPTING
Three are the main areas where PHP scripts are used:
• Server-side scripting:
This is the most used and main target for PHP. You need three things to
make this work the way you need it. The PHP parser (CGI or server
module), a web server and a web browser. You need to run the web server
where. You can access the PHP program output with a web browser,
viewing the PHP page through the server. All these can run on your home
machine if you are just experimenting with PHP programming.
A PHP script is executed on the server, and the plain HTML result
is sent back to the browser.
The default file extension for PHP files is ".php". A PHP file normally
contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that
uses a built-in PHP function "echo" to output the text "Hello World!" on a
web page:
Example:
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello IDOL!";
122
?>
</body>
</html>
Output:
My first PHP page
Hello IDOL!
In the example below, all three echo statements below are equal and legal.
<!DOCTYPE html>
<html>
<body>
<?php
ECHO " Hello Mumbai!<br>";
echo " Hello Mumbai!<br>";
EcHo " Hello Mumbai!<br>";
?>
</body>
</html>
Output:
Hello Mumbai!
Hello Mumbai!
Hello Mumbai!
<!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>
123
Output:
My car is red
My house is
My boat is
Overview of variables:
🡺The variables in PHP are used for saving the value of the program.
These values can be used later whenever needed by the programmer. The
latest value assigned to the variable is its value. All the variables are
preceded by a $ sign. User does not need to declare the variable before the
assignment. The = operator is used for assigning the values to the variable.
Output Variables:
The PHP echo statement is often used to output data to the screen.
The following example will show how to output text and a variable:
<!DOCTYPE html>
<html>
<body>
<?php
$txt = "SIOM";
echo "welcome to $txt!";
?>
</body>
</html>
Output:
welcome to SIOM!
Scope of variables:
🡺The variables in PHP are available to a specific limit in the coding.
There are four types of variable scope defined as mentioned below.
1. Local variables
The local variables are the one defined inside the function. The variable
declared outside the function are corresponding to another function.
<?php
$a = 10;
function add()
{
$a = 1;
124
print "Value of $a is: <br>";
}
add();
print "Value of $a here is:<br>";
?>
Output:
Output for the above code is as shown below:
Value of $a is 1
Value of $a here is 10
2. Global variables
The global variables are accessed anywhere in the program. The variable
is explicitly declared to be global in a function. The GLOBAL keyword is
used before the variable name.
<?php
$var1 = 20;
function display()
{
GLOBAL $var1;
$var1 ++;
print " Variable is: $var1;
}
display();
?>
Output:
The result generated when the code is executed is:
Variable is: 20
3. Static variables
The static variables maintain its value even when the user exits the
function. The STATIC keyword is used to define the static variable.
<?php
function increase()
{
STATIC $counter = 0;
$counter ++;
print $counter;
print "<br/>";
}
increase();
increase();
?>
Output:
The output generated when the code is executed is:
1
2
125
TYPES, COMMENTS
PHP has a total of eight data types which we use to construct our
variables –
• Integers − are whole numbers, without a decimal point, like 4195.
• Doubles − are floating-point numbers, like 3.14159 or 49.1.
• Booleans − have only two possible values either true or false.
• NULL − is a special type that only has one value: NULL.
• Strings − are sequences of characters, like 'PHP supports string
operations.'
• Arrays − are named and indexed collections of other values.
• Objects − are instances of programmer-defined classes, which can
package up both other kinds of values and functions that are specific
to the class.
• Resources − are special variables that hold references to resources
external to PHP (such as database connections).
The first five are simple types, and the next two (arrays and
objects) are compound - the compound types can package up other
arbitrary values of arbitrary type, whereas the simple types cannot.
• Integers:
They are whole numbers, without a decimal point, like 4195. They
are the simplest type .they correspond to simple whole numbers, both
positive and negative. Integers can be assigned to variables, or they can be
used in expressions,
$int_var = 12345;
$another_int = -12345 + 12345;
• Doubles:
They like 3.14159 or 49.1. By default, doubles print with the
minimum number of decimal places needed. For example,
<?php
$many = 2.2888800;
$many_2 = 2.2111200;
$few = $many + $many_2;
126
• Boolean
They have only two possible values either true or false. PHP
provides a couple of constants especially for use as Booleans: TRUE and
FALSE, which can be used like so
if (TRUE)
print("This will always print<br>");
else
print("This will never print<br>");
Each of the following variables has the truth value embedded in its
name when it is used in a Boolean context.
$true_num = 3 + 0.14159;
$true_str = "Tried and true"
$true_array[49] = "An array element";
$false_array = array();
$false_null = NULL;
$false_num = 999 - 999;
$false_str = " ";
NULL:
🡺NULL is a special type that only has one value: NULL. To give a
variable the NULL value, simply assign it like this –
$my_var = NULL;
Strings:
🡺They are sequences of characters, like "PHP supports string
operations". Following are valid examples of string
$string_1 = "This is a string in double quotes";
$string_2 = 'This is a somewhat longer, singly quoted string';
$string_39 = "This string has thirty-nine characters";
$string_0 = " "; // a string with zero characters
Singly quoted strings are treated almost literally, whereas doubly quoted
strings replace variables with their values as well as specially interpreting
certain character sequences.
<?php
$variable = "name";
$literally = 'My $variable will not print!';
print($literally);
print "<br>";
$literally = "My $variable will print!";
print($literally);
?>
Output:
My $variable will not print!
My name will print!
SUMMARY
🡺These scripts are embedded into the HTML documents that are served
by the web server.
128
REFERENCES
• https://www.studytonight.com/php/introduction-to-php
• https://www.brainvire.com/
• https://assets.ctfassets.net/
• https://www.w3schools.com/
• https://www.go4expert.com/
• https://www.tutorialspoint.com/
❖❖❖❖
129
10
CONTROL STRUCTURE AND LOOPING
Unit Structure :
Objectives
Introduction
Control structures
Branching
Looping
Termination
Summary
References
Unit End Exercise
OBJECTIVES
INTRODUCTION
CONTROL STRUCTURES
BRANCHING
PHP IF Else:
If… then... else is the simplest control structure. It evaluates the conditions
using Boolean logic
When to use if… then… else
HERE,
• ―if (condition is true)” is the control structure
• ―block one‖ is the code to be executed if the condition is true
• {…else…} is the fallback if the condition is false
• ―block two‖ is the block of code executed if the condition is false
How it works The flow chart shown below illustrates how the if
then… else control
131
Example The code below uses ―if… then… else‖ to determine the larger
value between two numbers.
<?php
$first_number = 7;
$second_number = 21;
if ($first_number> $second_number){
echo "$first_number is greater than $second_number";
}
else{
echo "$second_number is greater than $first_number";
}
?>
Output:
21 is greater than 7
If no condition has been met then the default block of code is executed.
HERE,
• “switch(…){…}” is the control structure block code
• “case value: case…” are the blocks of code to be executed depending
on the value of the condition
• “default:” is the block of code to be executed when no value matches
with the condition
How it works The flow chart shown below illustrates how the switch
control
132
Example: The code below uses the switch control structure to display a
message depending on the day of the week.
<?php
$today = "wednesday";
switch($today){
case "sunday":
echo "pray for us sinners.";
break;
case "wednesday":
echo "out for dinner";
break;
case "saturday":
echo "take care as you go out tonight.";
break;
default:
echo "have a nice day at work";
break;
}
?>
Output: out for dinner
Summary
• Control structures are used to control the execution of the program
• The if then... else is when you have more than route block of code to
execute depending on the value of the condition
• Switch… case is used to when you have a number of block codes, and
you only have to execute one of them depending on the value of the set
case.
133
PHP LOOP: FOR, FOREACH, WHILE, DO WHILE
The above code outputs ―21 is greater than 7‖ For loops For... loops
execute the block of code a specifiednumber of times. There are basically
two types of for loops;
• for
• for… each.
Let‘s now look at them separately. For loop It has the following
basic syntax
<?php
for (initialize; condition; increment){
//code to be executed
}
?>
HERE,
• “for…{…}” is the loop block
• ―initialize‖ usually an integer; it is used to set the counter‘s initial
value.
• “condition” the condition that is evaluated for each php execution. If
it evaluates to true then execution of the for... loop is terminated. If it
evaluates to false, the execution of the for... loop continues.
• “increment” is used to increment the initial value of counter integer.
The flowchart shown below illustrates how for loop in php works
Example: The code below uses the ―for… loop‖ to print values of
multiplying 10 by 0 through to 10
<?php
for ($i = 0; $i< 10; $i++){
134
$product = 10 * $i;
echo "The product of 10 * $i is $product <br/>";
}
?>
Output:
The product of 10 x 0 is 0
The product of 10 x 1 is 10
The product of 10 x 2 is 20
The product of 10 x 3 is 30
The product of 10 x 4 is 40
The product of 10 x 5 is 50
The product of 10 x 6 is 60
The product of 10 x 7 is 70
The product of 10 x 8 is 80
The product of 10 x 9 is 90
HERE,
• “foreach(…){…}” is the foreach php loop block code
• “$array_data” is the array variable to be looped through
• “$array_value“ is the temporary variable that holds the current array
item values.
• ―block of code…‖ is the piece of code that operates on the array values
How it works The flowchart shown below illustrates how the for…
each… loop works
135
Example The code below uses for… each loop to read and print the
elements of an array.
<?php
$animals_list = array("Lion","Wolf","Dog","Leopard","Tiger");
foreach($animals_list as $array_values){
echo $array_values . "<br>";
}
?>
Output:
Lion
Wolf
Dog
Leopard
Tiger
While Loop:
PHP While loop
They are used to execute a block of code a repeatedly until the set
condition gets satisfied
136
While loop
It has the following syntax
<?php
while (condition){
block of code to be executed;
}
?>
HERE,
• “while(…){…}” is the while loop block code
• “condition” is the condition to be evaluated by the while loop
• “block of code…” is the code to be executed if the condition gets
satisfied
How it works
• The flow chart shown below illustrates how the while… loop works
The example below uses the while… loop to print numbers 1 to 10.
<?php
$i = 0;
while ($i<10){
echo $i + 1 . "<br>";
$i++;
}
?>
Output:
1
2
3
4
5
6
7
137
8
9
10
PHP Do While:
The difference between While… loop and Do… while loop is do… while
is executed at-least once before the condition is evaluated.
HERE,
• “do{…} while(…)” is the do… while loop block code
• “condition” is the condition to be evaluated by the while loop
• “block of code…” is the code that is executed at least once by the
do… while loop
How it works
• The flow chart shown below illustrates how the while… loop works
138
Example
We are now going to modify the while… loop example and implement it
using the do… while loop and set the counter initial value to 9.
Output:
9
Note the above example outputs 9 only.
This is because the do… while loop is executed at least once even if the
set condition evaluates to false.
Summary
• The for… loop is used to execute a block of a specified number of
times
• The foreach… loop is used to loop through arrays
• While… loop is used to execute a block of code as long as the set
condition is made to be false
• The do… while loop is used to execute the block of code at least once
then the rest of the execution is dependent on the evaluation of the set
condition
Break:
• A break statement can be used to terminate or to come out from the
loop or conditional statement unconditionally.
• It can be used in switch statement to break and come out from the
switch statement after each case expression.
• Whenever, break statement is encounter within the program then it
will break the current loop or block.
• A break statement is normally used with if statement.
• When certain condition becomes true to terminate the loop then break
statement can be used.
139
The following program demonstrates the use of break statement.
Loop will be terminated as soon as the counter value becomes greater
than 5.
<?php
for( $i = 1; $i<= 10 ; $i++ )
{
if ($i> 5)
break; // terminate loop
echo "$i"."</br>" ;
}
?>
Continue:
• A continue statement can be used into the loop when we want to skip
some statement to be executed and continue the execution of above
statement based on some specific condition.
• Similar to break statement, continue is also used with if statement.
• When compiler encounters continue, statements after continue are
skipped and control transfers to the statement above continue.
Exit:
• An exit statement is used to terminate the current execution flow.
• As soon as exit statement is found, it will terminate the program.
140
• It can be used to output a message and terminate the current script: for
example exit(―Good Bye!‖);
• It can also be used with error code. For example: exit(1), exit(0376).
• the following program demonstrates the use of exit statements.
<?php
$filename = 'sample.txt' ;
$file = fopen($filename, 'r') // open file for reading
or exit("unable to open file ($filename)");
?>
SUMMARY
🡺Control structures are used to control the execution of the program. The
if then... else is when you have more than route block of code to
execute depending on the value of the condition
➔ Switch… case is used to when you have a number of block codes, and
you only have to execute one of them depending on the value of the set
case
REFERENCES
https://code.tutsplus.com/
https://www.guru99.com/
http://www.hexainclude.com/
https://www.brainvire.com/
https://assets.ctfassets.net/
https://www.w3schools.com/
https://www.go4expert.com/
https://www.tutorialspoint.com/
141
UNIT END EXERCISE
Conditions:
• Minimum age required for vote is 18.
• You can use PHP Functions.
• You can use Decision Making Statements.
3. Write a PHP program to check whether a number is positive, negative
or zero.
4. Write a Program to display count, from 5 to 15 using PHP loop as
given below.
5. Write a program to calculate factorial of a number using for loop in
php.
❖❖❖❖
142
11
FUNCTIONS AND METHODS
Unit Structure :
Objectives
Functions
Passing information with PHP GET, POST
Formatting form variables
Super global arrays
Strings and string functions
Summary
References
Unit End Exercise
OBJECTIVES
FUNCTIONS
The real power of PHP comes from its functions. PHP has more
than 1000 built-in functions, and in addition you can create your own
custom functions.
PHP Built-in Functions:
PHP has over 1000 built-in functions that can be called directly,
from within a script, to perform a specific task.
143
Create a User Defined Function in PHP:
A user-defined function declaration starts with the word function:
Syntax:
Function Name() {
code to be executed;
}
<!DOCTYPE html>
<html>
<body>
<?php
function writeMsg() {
echo "Welcome to IDOL!";
}
writeMsg();
?>
</body>
</html>
Output:
Welcome to IDOL!
144
<!DOCTYPE html>
<html>
<body>
<?php
function familyName($fname) {
echo "$fname Dixit.<br>";
}
familyName("Rahul");
familyName("Hemant");
familyName("Ajay");
familyName("Rajesh");
familyName("Mukesh");
?>
</body>
</html>
Output:
Rahul Dixit.
Hemant Dixit.
Ajay Dixit.
Rajesh Dixit.
Mukesh Dixit.
The following example has a function with two arguments ($fname and
$year):
<!DOCTYPE html>
<html>
<body>
<?php
function familyName($fname, $year) {
echo "$fname Navale. Born in $year <br>";
}
familyName("Rahul","1975");
familyName("Hemant","1978");
familyName("Mukesh","1983");
?>
</body>
</html>
Output:
Rahul Navale. Born in 1975
Hemant Navale. Born in 1978
Mukesh Navale. Born in 1983
145
PHP is a Loosely Typed Language:
In the example above, notice that we did not have to tell PHP
which data type the variable is.
Output:
10
To specify strict we need to set declare(strict_types=1);. This must
be on the very first line of the PHP file.
Output:
The height is : 350
The height is : 50
The height is : 135
The height is : 80
Output:
5 + 10 = 15
7 + 13 = 20
2+4=6
🡺To declare a type for the function return, add a colon ( : ) and the type
right before the opening curly ( { )bracket when declaring the function.
🡺In the following example we specify the return type for the function
147
<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : float {
return $a + $b;
}
echo addNumbers(1.2, 5.2);
?>
Output:
6.4
You can specify a different return type, than the argument types, but
make sure the return is the correct type
<?php declare(strict_types=1); // strict requirement
function addNumbers(float $a, float $b) : int {
return (int)($a + $b);
}
echo addNumbers(1.2, 5.2);
?>
Output:
6
<!DOCTYPE html>
<html>
<body>
<?php
function add_five(&$value) {
$value += 5;
}
$num = 2;
add_five($num);
echo $num;
?>
</body>
</html>
Output:
7
148
PASSING INFORMATION WITH PHP GET, POST
🡺There are two ways the browser client can send information to the web
server.
name1=value1&name2=value2&name3=value3
➔ Spaces are removed and replaced with the + character and any other no
alphanumeric characters are replaced with a hexadecimal value. After the
information is encoded it is sent to the server.
🡺The GET method produces a long string that appears in your server
logs, in the browser's Location: box.
🡺GET can't be used to send binary data, like images or word documents,
to the server.
🡺The PHP provides $_GET associative array to access all the sent
information using GET method.
<?php
if( $_GET["name"] || $_GET["age"] ) {
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
149
exit();
}
?>
<html>
<body>
</body>
</html>
Output:
• The POST method does not have any restriction on data size to be
sent.
• The POST method can be used to send ASCII as well as binary data.
• The data sent by POST method goes through HTTP header so security
depends on HTTP protocol. By using Secure HTTP you can make
sure that your information is secure.
• The PHP provides $_POST associative array to access all the sent
information using POST method.
• The following example by putting the source code in test.php script.
<?php
if( $_POST["name"] || $_POST["age"] ) {
if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
die ("invalid name and name should be alpha");
}
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";
exit();
}
?>
<html>
<body>
150
<form action = "<?php $_PHP_SELF ?>" method = "POST">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>
Output:
🡺This shows how to keep the values in the input fields when the user hits
the submit button.
🡺In the comment textarea field, we put the script between the <textarea>
and </textarea> tags. The little script outputs the value of the $name,
$email, $website, and $comment variables.
➔ Then, we also need to show which radio button that was checked. For
this, we must manipulate the checked attribute.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
151
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also
allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-
9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
153
Output:
SUPERGLOBAL ARRAYS
PHP $GLOBALS:
🡺$GLOBALS is a PHP super global variable which is used to access
global variables from anywhere in the PHP script also from within
functions or methods.
🡺The example below shows how to use the super global variable
$GLOBALS.
<html>
<body>
<?php
$x = 75;
154
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
</body>
</html>
Output:
100
PHP $_SERVER:
🡺$_SERVER is a PHP super global variable which holds information
about headers, paths, and script locations.
<html>
<body>
<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>
</body>
</html>
Output:
/demo/demo_global_server.php
35.194.26.41
35.194.26.41
showphp.php?filename=demo_global_server
155
The following table lists the most important elements that can go inside
$_SERVER
Element/Code Description
PHP $_REQUEST:
🡺PHP $_REQUEST is a PHP super global variable which is used to
collect data after submitting an HTML form.
➔ The example below shows a form with an input field and a submit
button. When a user submits the data by clicking on "Submit", the form
data is sent to the file specified in the action attribute of the <form> tag.
🡺In this example, we point to this file itself for processing form data. If
you wish to use another PHP file to process form data, replace that with
the filename of your choice. Then, we can use the super global variable
$_REQUEST to collect the value of the input field.
<html>
<body>
<form method="post" action="<?php echo
$_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = htmlspecialchars($_REQUEST['fname']);
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
156
Output:
PHP $_POST:
🡺PHP $_POST is a PHP super global variable which is used to collect
form data after submitting an HTML form with method="post". $_POST
is also widely used to pass variables.
🡺The example below shows a form with an input field and a submit
button. When a user submits the data by clicking on "Submit", the form
data is sent to the file specified in the action attribute of the <form> tag.
🡺In this example, we point to the file itself for processing form data. If
you wish to use another PHP file to process form data, replace that with
the filename of your choice. Then, we can use the super global variable
$_POST to collect the value of the input field.
<html>
<body>
<form method="post" action="<?php echo
$_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
Output:
PHP $_GET:
🡺PHP $_GET is a PHP super global variable which is used to collect
form data after submitting an HTML form with method="get".
➔ When a user clicks on the link "Test $GET", the parameters "subject"
and "web" are sent to "test_get.php", and you can then access their values
in "test_get.php" with $_GET.
Output:
Test $GET
<?php
var_dump('You need to be logged in to view this page');
?>
Output:
🡺If the single quote is part of the string value, it can be escaped using the
backslash.The code below illustrates how to escape a single quote.
<?php
echo 'I \'ll be back after 20 minutes';
?>
158
Output:
I'll be back after 20 minutes
🡺Variable names can be used inside double quotes and their values will
be displayed.
HERE,
The above example creates a simple string with the value of Pune.
The variable name is then used in the string created using double quotes
and its value is interpolated at run time.
Output:
Pune is in Maharashtra
🡺It is more commonly used in validating input fields where the user is
limited to enter a fixed length of characters.
Syntax:
Strlen(string);
Example:
<?php
echo strlen(―Welcome to IDOL‖);//will return the length of given string
?>
2. Counting of the number of words in a String:
➔ Another function which enables display of the number of words in any
specific string is str_word_count(). This function is also useful in
validation of input fields.
159
Syntax
Str_word_count(string)
Example:
Example
<?php
echo str_word_count(―Welcome to Pune‖);//will return the number of
words in a string
?>
Output: 3
3. Reversing a String:
🡺Strrev() is used for reversing a string. You can use this function to get
the reverse version of any string.
Syntax:
Strev(string)
Example:
<?php
echo strrev(―Welcome to pune‖);// will return the string starting from the
end
?>
Output:
enup ot emocleW
🡺If found, then it returns the specific position. If not found at all, then it
will return ―False‖. Strops() is most commonly used in validating input
fields like email.
Syntax:
Strpos(string,text);
Example
<?php
echo strpos(―Welcome to Sinhgad‖,‖Sinhgad‖);
?>
Output:
7
Syntax:
Str_replace(string to be replaced,text,string)
160
Example:
<?php
echo str_replace(―Pune‖, ―the programming world‖, ―Welcome to Pune‖);
?>
Syntax: Ucwords(string)
Example:
<?php
echo ucwords(―welcome to the php world‖);
?>
Output:
Welcome To The Php World
Syntax: Strtoupper(string);
Example
<?php
echo strtoupper(―welcome to sinhgad‖);// It will convert all letters of
string into uppercase
?>
Syntax: Strtolower(string)
Example:
<?php
echo strtolower(―WELCOME TO PUNE‖);
?>
Output:
welcome to pune
161
SUMMARY
🡺There are two ways the browser client can send information to the web
server that is GET and POST methods that we studied in this chapter.
REFERENCES
https://www.cloudways.com/
https://www.guru99.com/
https://www.studytonight.com/php/introduction-to-php
https://www.brainvire.com/
https://assets.ctfassets.net/
https://www.w3schools.com/
https://www.go4expert.com/
https://www.tutorialspoint.com/
❖❖❖❖
162
12
REGULAR EXPRESSION AND ARRAYS
Unit Structure :
Objectives
Introduction
Regular Expressions
Arrays
Number handling
Basic PHP errors
Summary
References
Unit End Exercise
OBJECTIVES
INTRODUCTION
163
REGULAR EXPRESSIONS
🡺Regular expressions are one of the most powerful tools available today
for effective and efficient text processing and manipulations.
➔ For example, it can be used to verify whether the format of data i.e.
name, email, phone number, etc. entered by the user was correct or not,
find or replace matching string within text content, and so on.
🡺PHP supports Perl style regular expressions via its preg_ family of
functions. Why Perl style regular expressions? Because Perl (Practical
Extraction and Report Language) was the first mainstream programming
language that provided integrated support for regular expressions and it is
well known for its strong support of regular expressions and its
extraordinary text processing and manipulation capabilities.
🡺Let's begin with a brief overview of the commonly used PHP's built-in
pattern-matching functions before delving deep into the world of regular
expressions.
Character Classes:
➔ Square brackets surrounding a pattern of characters are called a
character class e.g. [abc]. A character class always matches a single
character out of a list of specified characters that means the expression
[abc] matches only a, b or c character.
🡺Negated character classes can also be defined that match any character
except those contained within the brackets. A negated character class is
164
defined by placing a caret. (^) symbol immediately after the opening
bracket, like this [^abc].
🡺You can also define a range of characters by using the hyphen (-)
character inside a character class, like [0-9]. Let's look at some examples
of character classes:
The following example will show you how to find whether a pattern exists
in a string or not using the regular expression and PHP preg_match()
function.
<html>
<head>
<title>Match a Pattern against a String Using RegExp in PHP</title>
</head>
<body>
<?php
$pattern = "/ca[kf]e/";
$text = "He was eating cake in the cafe.";
if(preg_match($pattern, $text)){
echo "Match found!";
} else{
echo "Match not found.";
}
?>
</body>
</html>
Output:
Match found!
Similarly, you can use the preg_match_all() function to find all matches
within a string.
<html>
<head>
<title>Find all Occurrences of a Pattern in a String Using RegExp in
PHP</title>
165
</head>
<body>
<?php
$pattern = "/ca[kf]e/";
$text = "He was eating cake in the cafe.";
$matches = preg_match_all($pattern, $text, $array);
echo $matches . " matches were found."
?>
</body>
</html>
The following example will show you how to find and replace space with
a hyphen character in a string using regular expression and PHP
preg_replace() function
<html>
<head>
<title>Find and Replace Characters in a String Using RegExp in
PHP</title>
</head>
<body>
<?php
$pattern = "/\s/";
$replacement = "-";
$text = "Earth revolves around\nthe\tSun";
166
// Replace spaces, newlines and tabs
echo preg_replace($pattern, $replacement, $text);
echo "<br>";
// Replace only spaces
echo str_replace(" ", "-", $text);
?>
</body>
</html>
Output:
Earth-revolves-around-the-Sun
Earth-revolves-around the Sun
Repetition Quantifiers:
🡺if you want to match on more than one character? For example, let's say
you want to find out words containing one or more instances of the letter
p, or words containing at least two p's, and so on.
🡺This is where quantifiers come into play. With quantifiers you can
specify how many times a character in a regular expression should match.
The following table lists the various ways to quantify a particular pattern
The regular expression in the following example will splits the string at
comma, sequence of commas, whitespace, or combination thereof using
the PHP preg_split() function.
<html>
<head>
<title>Split a String Using RegExp in PHP</title>
</head>
<body>
<?php
$pattern = "/[\s,]+/";
167
$text = "My favourite colors are red, green and blue";
$parts = preg_split($pattern, $text);
Output:
My
favourite
colors
are
red
green
and
blue
Position Anchors:
🡺There are certain situations where you want to match at the beginning
or end of a line, word, or string.
🡺To do this you can use anchors. Two common anchors are caret (^)
which represent the start of the string, and the dollar ($) sign which
represent the end of the string.
The regular expression in the following example will display only those
names from the names array which start with the letter "J" using the PHP
preg_grep() function.
<html>
<head>
<title>Match Strings Beginning with Specific Characters Using RegExp in
PHP</title>
</head>
<body>
<?php
$pattern = "/^s/";
168
$names = array("sinhgad", "rajgad", "shivneri");
$matches = preg_grep($pattern, $names);
ARRAYS
🡺An array is a data structure that stores one or more similar type of
values in a single value. For example, if you want to store 100 numbers
then instead of defining 100 variables it‘s easy to define an array of 100
length.
🡺There are three different kind of arrays and each array value is accessed
using an ID c which is called array index.
Numeric Array:
🡺These arrays can store numbers, strings and any object but their index
will be represented by numbers. By default, array index starts from zero.
🡺Example
Following is the example showing how to create and access numeric
arrays. Here we have used array() function to create array.
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value ) {
echo "Value is $value <br />";
}
169
/* Second method to create array. */
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
foreach( $numbers as $value ) {
echo "Value is $value <br />";
}
?>
</body>
</html>
Output:
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five
Associative Arrays:
🡺The associative arrays are very similar to numeric arrays in term of
functionality but they are different in terms of their index.
🡺Associative array will have their index as string so that you can
establish a strong association between key and values.
Example:
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array("Rahul" => 2000, "qadir" => 1000, "zara" => 500);
echo "Salary of Rahul is ". $salaries['Rahul'] . "<br />";
echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
Multidimensional Arrays:
🡺A multi-dimensional array each element in the main array can also be
an array. And each element in the sub-array can be an array, and so on.
Values in the multi-dimensional array are accessed using multiple index.
<html>
<body>
<?php
$marks = array(
"Rahul" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
"qadir" => array (
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),
"zara" => array (
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);
/* Accessing multi-dimensional array values */
echo "Marks for Rahul in physics : " ;
echo $marks['Rahul']['physics'] . "<br />";
echo "Marks for qadir in maths : ";
echo $marks['qadir']['maths'] . "<br />";
echo "Marks for zara in chemistry : " ;
echo $marks['zara']['chemistry'] . "<br />";
171
?>
</body>
</html>
Output:
Marks for Rahul in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39
NUMBER HANDLING
🡺One thing to notice about PHP is that it provides automatic data type
conversion.
🡺So, if you assign an integer value to a variable, the type of that variable
will automatically be an integer. Then, if you assign a string to the same
variable, the type will change to a string.
PHP Integers:
🡺An integer is a number without any decimal part.2, 256, -256, 10358, -
179567 are all integers. While 7.56, 10.0, 150.67 are floats.
• is_int()
• is_integer() - alias of is_int()
• is_long() - alias of is_int()
Example
Check if the type of a variable is integer:
<html>
<body>
<?php
172
// Check if the type of a variable is integer
$x = 5985;
var_dump(is_int($x));
echo "<br>";
// Check again...
$x = 59.85;
var_dump(is_int($x));
?>
</body>
</html>
Output:
bool(true)
bool(false)
PHP Floats:
🡺A float is a number with a decimal point or a number in exponential
form. 2.0, 256.4, 10.358, 7.64E+5, 5.56E-5 are all floats.
Example
Check if the type of a variable is float:
<html>
<body>
<?php
// Check if the type of a variable is float
$x = 10.365;
var_dump(is_float($x));
?>
</body>
</html>
Output:
bool(true)
PHP Infinity:
🡺A numeric value that is larger than PHP_FLOAT_MAX is considered
infinite.
However, the PHP var_dump() function returns the data type and value:
173
Example
Check if a numeric value is finite or infinite:
<html>
<body>
<?php
// Check if a numeric value is finite or infinite
$x = 1.9e411;
var_dump($x);
?>
</body>
</html>
Output:
float(INF)
PHP NaN:
🡺NaN stands for Not a Number.NaN is used for impossible mathematical
operations.
However, the PHP var_dump() function returns the data type and value:
Example
Invalid calculation will return a NaN value:
<html>
<body>
<?php
// Invalid calculation will return a NaN value
$x = acos(8);
var_dump($x);
?>
</body>
</html>
Output: float(NAN)
Example:
Check if the variable is numeric:
<html>
<body>
<?php
// Check if the variable is numeric
$x = 5985;
174
var_dump(is_numeric($x));
echo "<br>";
$x = "5985";
var_dump(is_numeric($x));
echo "<br>";
$x = "59.85" + 100;
var_dump(is_numeric($x));
echo "<br>";
$x = "Hello";
var_dump(is_numeric($x));
?>
</body>
</html>
Output:
bool(true)
bool(true)
bool(true)
bool(false)
The (int), (integer), or intval() function are often used to convert a value to
an integer.
Example
Cast float and string to integer:
<html>
<body>
<?php
// Cast float to int
$x = 23465.768;
$int_cast = (int)$x;
echo $int_cast;
echo "<br>";
// Cast string to int
$x = "23465.768";
$int_cast = (int)$x;
echo $int_cast;
?>
</body>
</html>
Output:
23465
23465
175
BASIC PHP ERRORS
🡺A PHP Error occurs when something is wrong in the PHP code. The
error can be as simple as a missing semicolon, or as complex as calling an
incorrect variable.
🡺To efficiently resolve a PHP issue in a script, you must understand what
kind of problem is occurring.
Warning Error:
🡺A warning error in PHP does not stop the script from running. It only
warns you that there is a problem, one that is likely to cause bigger issues
in the future.
Example:
<?php
echo "Warning error"';
include ("external_file.php");
?>
Notice Error:
🡺Notice errors are minor errors. They are similar to warning errors, as
they also don‘t stop code execution.
176
Example:
<?php
$a="Defined error";
echo "Notice error";
echo $b;
?>
🡺For example, the following script would stop execution and signal a
parse error:
<?php
echo "Red";
echo "Blue";
echo "Green"
?>
Fatal Error:
🡺Fatal errors are ones that crash your program and are classified as
critical errors. An undefined function or class in the script is the main
reason for this type of error.
177
• Compile time fatal error (when a programmer tries to use nonexistent
data)
• Runtime fatal error (happens while the program is running, causing the
code to stop working completely)
<?php
function sub()
{
$sub=6-1;
echo "The sub= ".$sub;
}
div();
?>
The output tells you why it is unable to compile, as in the image below
SUMMARY
REFERENCES
https://www.guru99.com/
https://www.tutorialrepublic.com/
https://www.w3schools.com/
https://www.tutorialspoint.com/
https://phoenixnap.com/
178
UNIT END EXERCISE
❖❖❖❖
179
13
INTRODUCTION TO ADVANCE PHP AND
MYSQL
Unit Structure :
PHP files can contain text, HTML, CSS, JavaScript, and PHP
code. PHP code are executed on the server, and the result is returned to the
browser as plain HTML
Advantages of MySQL
MySQL is an open-source database, so you don't have to pay a
single penny to use it.
MySQL is quicker than other databases, so it can work well even with the
large data set.
MySQL is very friendly with PHP, the most popular language for
web development.
MYSQL FUNCTIONS
⮚ Inbuilt Function
⮚ User Defined Function
Inbuilt Function:
There are several Inbuilt functions are available in php. Generally
all its are single line functions.
181
User Defined Function :
A user defined function declaration starts with the word
"function":
Syntax
function function_Name()
{
code to be executed;
}
Function names are NOT case-sensitive.
<?php function fun() {
echo "Hello world!";
}
fun(); // call the function
?>
Syntax of mysql_connection
connection mysql_connect(server, user, password);
server:
Optional − The host name running database server. If not specified then
default value is localhost:3306.
User:
Optional − The username accessing the database. If not specified then
default is the name of the user that owns the server process.
password :
Optional − The password of the user accessing the database. If not
specified then default is an empty password.
PHP mysql_select_db() Function:
The mysql_select_db() function sets the active MySQL database. This
function returns TRUE on success, or FALSE on failure.
mysql_create_db() function attempts to create a new database on the
server associated with the specified link identifier.
182
The mysqli_select_db() function is used to change the default
database for the connection.
Example:
$conn = mysqli_connect($host, $user, $pass,$dbname);
$sql = "CREATE DATABASE myDb";
mysql_query($conn, $sql);
result: The result resource that is being evaluated. This result comes from
a call to mysql_query().
row :The row number from the result that's being retrieved. Row numbers
start at 0.
Example:
⮚ mysql_close()
⮚ This function used to disconnect Mysql database
183
INTEGRATING WEB FORMS AND DATABASES
• Create a connection
• Select database
• Perform database query
• Use return data
• Close connection
⮚ Create a connection
It is very important when you want to start a dynamic website to create
a connection with your SQL (we are talking about MySQL) by using
mysql_connect() function. In mysql_connect() arguments should be a
string and it‘s important to use die() function with mysql_error() function
to check if there is a problem with the connection or not.
⮚ Select database
Now we have to select the database which we are creating and saving
our data by using mysql_select_db() function which the arguments are the
name of the database and connection we made earlier.
⮚ Close connection
To close connection, it is better to use mysql_close() function to close
MySQL connection. This is a very important function as it closes the
connection to the database server. Your script will still run if you do not
include this function. And too many open MySQL connections can cause
problems for your account. This is a good practice to close the MySQL
connection once all the queries are executed.
184
<?php
// Five steps to PHP database connections:
// Create a database connection
// $connection allows us to keep referring to this connection after it is
established
$connection = mysql_connect("localhost","root","myPassword");
if (!$connection) {
die("Database connection failed: " . mysql_error());
}
// Select a database to use
$db_select = mysql_select_db("widget_corp",$connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
// Perform database query
$result = mysql_query("SELECT * FROM subjects", $connection);
if (!$result) {
die("Database query failed: " . mysql_error());
}
// Use returned data
while ($row = mysql_fetch_array($result)) {
echo $row["menu_name"]." ".$row["position"]."<br />";
}
// Close connection
mysql_close($connection);
185
die("Connection failed: " . $conn->connect_error); }
Output:
Id: 1 Name: Sachin Sharma Address: Mumbai
Id: 2 Name: Kapil Varma Address: Delhi
Id: 3 Name: Rajesh kumarAddress:Surati
Syntax:
The below is generic syntax of SQL INSERT INTO command to
insert a single record in MySQL table:
187
die('Error: '.mysql_error($con));
}
*/
mysql_close($con);
}
?><html>
<body>
<form action ="student_info.html" method ="POST">
<input type ="submit" value="Go Back" />
</form>
</body>
</html>
188
BUILDING FORMS FROM QUERIES
We can create and use forms in PHP. To get form data, the form
request may be get or post. To retrieve data from get request, we need to
use $_GET, for post request $_POST.
To show the values in the input fields after the user hits the submit
button, we add a little PHP script inside the value attribute of the
following input fields: name, email, and website.
<html>
<head>
<title>Sign-In</title>
<link rel="stylesheet" type="text/css" href="CSS/style.css">
</head>
<body id="body-color">
<div id="Sign-In">
<fieldset style="width:30%"><legend>LOG-IN HERE</legend>
<form method="POST" action="connectivity.php">
User <br><input type="text" name="user" size="40"><br>
Password <br><input type="password" name="pass" size="40"><br>
<input id="button" type="submit" name="submit" value="Log-In">
</form>
</fieldset>
</div></body></html>
student_Login.html
<?php
if( $_POST['name'] || $_POST["address"] )
{
if (preg_match("/[^A-Za-z'-]/",$_POST['name'] ))
{
die ("invalid name and name should be alpha");
}
189
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or
die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or
die("Failed to connect to MySQL: " . mysql_error());
//inserting Record to the database
$name = $_POST['name'];
$address = $_POST['address'];
$gender = $_POST['gender'];
echo $name;
echo "<br/>";
echo $address;
echo "<br/>";
echo $gender;
echo "<br/>";
$sql="INSERT INTO student_info(Name,Address,Gender)
VALUES('$name','$address','$gender')";
//$query = "INSERT INTO
contact(contactName,contactEmail,message)VALUES('$name','$e
mail','$message')";
// $result = mysql_query($sql)or die(mysql_error());
mysql_query($sql)or die(mysql_error());
echo "Successfully updated database";
/*
if($result)
{
echo "Successfully updated database";
}
else
{
die('Error: '.mysql_error($con));
}
*/
mysql_close($con); } ?>
<html>
<body>
<form action ="student_info.html" method ="POST">
<input type ="submit" value="Go Back" />
</form>
</body>
</html>
190
student_insert.php
SUMMARY
🡺In this chapter we have learn how to design dynamic webpages We can
create and use forms in PHP. To get form data, the form request may be
get or post. To retrieve data from get request, we need to use $_GET, for
post request $_POST
EXERCISE
1. Create a simple HTML form and accept the user name and display the
name through PHP echo statement.
2. How can we connect to a MySQL database from a PHP script?
3. How can we access the data sent through the URL with the GET
method?
4. Design PHP Registration form using get and post method.
❖❖❖❖
191
14
ADVANCED PHP
Unit Structure:
PHP String
String Function
Regular Expressions
PHP Sessions
PHP Cookies
HTTP
E-Mail
Summary
References
Exercise
PHP STRING
There are some string literal in PHP such as single quoted, double quoted,
heredoc syntax.
strlen() Function:
The strlen() function is used to find the length of a string. The strlen()
function is predefined function of PHP. It is used to find the length of
string or returns the length of a string including all the whitespaces and
special character.
Output: 15
str_word_count() Function:
The PHP str_word_count() function counts the number of words in a
string.
Output: 2
stringstrcmp() Function:
String comparison is one of the most common tasks in programming and
development. strcmp() is a string comparison function in PHP. It is a built-
in function of PHP, which is case sensitive.
This function compares two strings and tells whether a string is greater,
less, or equal to another string. strcmp() function accepts two strings
parameter, which is mandatory to pass in the function body. Both
parameters are mandatory to pass in strcmp() function().
Output: 0
1
stringstrrev() Function:
The strrev() function is predefined function of PHP. It is used to reverse a
string. It is one of the most basic string operations which are used by
programmers and developers.
Output:!dlrowolleH
PHP
stringsubstr_count() Function:
The substr_count() is a built-in function of PHP. It counts the number of
times a substring occurs in the given string. The substr_count() is a case-
sensitive function.
Syntax of substr_count() function
substr_count($string, $substring, $start, $length)
$string (required): The $string parameter is the main string parameter in
which occurrence's of substring is counted. It is a mandatory parameter.
$substring (required): The value passed in this parameter is searched in
$string parameter and returns the counted occurrence of substring. It is
also a mandatory parameter.
$start (optional): This parameter consists of an integer value. It specifies
that from where to start the counting.
$length (optional): This parameter is an optional parameter and depends
on $start parameter.
Example of substr_count() function
<?php
$str1 = "God is one, God is every where";
$str2 = "God";
echosubstr_count($str1, $str2); //Output 2
?>
194
Output: 2
stringstrpos()Function:
The strops() is in-built function of PHP. It is used to find the
position of the first occurrence of a string inside another string or substring
in a string.
Output: 13
195
Regular Expression Modifiers
Modifiers can change how a search is performed.
Modifier Description
\d Find a digit
Function Description
196
PHP preg_match() function:
The preg_match() function will tell you whether a string contains
matches of a pattern. This function searches the pattern inside the string
and returns true if the pattern exists otherwise returns false.
Output: The preg_split() function returns Array ( [0] => Web [1] =>
Technology )
PHP SESSIONS
PHP session is object which is used to store and pass information from
one page to another temporarily. A session is a way to store information to
be used across multiple pages.
Sessions are a simple way to store data for individual users against a
unique session ID.
Session IDs are normally sent to the browser via session, cookies and the
ID is used to retrieve existing session data. Session variables solve this
problem by storing user information to be used across multiple pages. By
default, session variables last until the user closes the browser.
198
Starting a PHP Session
A PHP session is easily started by making a call to the session_start()
function. This function first checks if a session is already started and if
none is started then it starts one. It is recommended to put the call to
session_start() at the beginning of the page.
Session variables are set with the PHP global variable: $_SESSION.
Session variables are stored in associative array called $_SESSION[].
These variables can be accessed during lifetime of a session.
Syntax of Session
$_SESSION[“session_object"] = “Value";
Example:
<?php
// Set session variables
$_SESSION[―session_object"] = ―Value";
$_SESSION["student"] = "Sachin";
?>
PHP Session demonstration
To Create Session variable
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["SportName‖] = "Cricket";
$_SESSION["Country"] = "India";
echo "Session variables are set.";
?></body></html>
Save this file session_create.php
Send the data from second page to third page and destroy the session.
<?php
session_start();
?>
<!DOCTYPE html>
<html><body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
echo "All session variables are now removed, and the session is
destroyed."
?></body></html>
PHP COOKIES
A cookie is a small file with the maximum size of 4KB that the web server
stores on the client computer.
Cookie is created at server side and saved to client browser. Each time
when client sends request to the server, cookie is embedded with request.
Such way, cookie can be received at the server side.
A cookie created by a user can only be visible to them. Other users cannot
see its value.
PHP setcookie() function is used to set cookie with HTTP response. Once
cookie is set, you can access it by $_COOKIE superglobal variable.
<?php
// Setting a cookie
setcookie("username", "KapilDev", time()+1*60*60); // using expiry in 1
hour(1*60*60 seconds or 3600 seconds)
?>
Delete Cookies:
If you want to destroy a cookie before its expiry time, then you set the
expiry time to a time that has already passed. You can delete a cookie by
calling the same setcookie() function with the cookie name and any value
however this time you need the set the expiration date in the past, as
shown in the example below:
201
<?php
setcookie ("CookieName", "", time() - 3600);// set the expiration date to
one hour ago
?>
Example of deleting Cookies
<?php
setcookie(" username ", time() - 360,'/');
?>
PHP HTTP
PHP mail () function is used to send email in PHP. You can send text
message, html message and attachment with message using PHP mail()
function. Sending email messages are very common for a web application.
202
The mail() function allows you to send emails directly from a script. For
the mail functions to be available, PHP requires an installed and working
email system. The program to be used is defined by the configuration
settings in the php.ini file.
PHP makes use of mail() function to send an email. This function requires
three mandatory arguments that specify the recipient's email address, the
subject of the message and the actual message additionally there are other
two optional parameters.
Parameter Description
to The recipient's email address.
subject Required. Specifies the subject of the email. This parameter
cannot contain any newline characters
message Required. Defines the message to be sent. Lines should not
exceed 70 characters
Optional — The following parameters are optional
headers Optional. Specifies additional headers, like From, Cc, and Bcc.
parameters Optional. Specifies an additional parameter to the send mail
program
203
SUMMARY
REFERENCES
QUESTIONS:
❖❖❖❖
204
Follow for more useful content
Telegram
@codehype
Join Telegram for
FREE Coding
Resources
CodeHype