0% found this document useful (0 votes)
132 views273 pages

Web Designing and Development

Uploaded by

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

Web Designing and Development

Uploaded by

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

WEB DESIGNING AND

DEVELOPMENT

1
Sr.No. Index
1. WEB PROGRAMMING
1.1 WWW
1.2 Web Browser
1.3 URL
1.4 DNS
1.5 Website
1.6 Web Page
1.6.1 Static Web Page
1.6.2 Dynamic Web Page
1.6.3 Differences between Static & Dynamic Page
1.7 Web Development Process
1.8 Script
1.8.1 Client Side Scripting
1.8.2 Server Side Scripting
1.9 How the web works?
1.9.1 HTTP Request
1.9.2 HTTP Response
1.10 Web Server
1.10.1 Apache Web Server
1.11 HTTP Protocol
1.11.1 Features of HTTP
1.12 HTTPS Protocol
1.13 FTP
1.13.1 Advantages of FTP
1.14 Web Hosting
1.14.1 Types of Web Hosting Services
1.15 Document Root

2 HTML AND CSS


2.1 HTML
2.2 Use of HTML Documents
2.3 HTML Tags
2.4 Advantages of HTML
2.5 HTML Document Structure
2.6 Basic Tags & Attributes
2.6.1 Tags
2.6.2 Types of Tags
2.6.3 Attributes
2.7 Document Tag
2.8 Text Formatting Tag
2.9 HTML List
2.10 HTML Link
2.10.1 Creating Link with other pages
2
2.10.2 Link Titles
2.10.3 Absolute URL vs Relative URL
2.10.4 Link to an Email Address
2.10.5 Button as Link
2.10.6 <LINK>
2.11 Inserting Special Characters
2.12 Inserting Image
2.12.1 Use an Image as Link
2.13 Relative Path & Absolute Path
2.14 Image Maps
2.15 Table
2.15.1 Tables inside of Tables
2.15.2 Cell Padding & Cell Spacing
2.15.3 Colspan & Rowspan
2.16 FRAMES
2.17 Form
2.18 HTML5
2.18.1 New HTML5 Elements(Tags)
2.19 HTML5 Document Structure
2.20 Multimedia Element
2.21 List of HTML5 Elements
2.22 HTML5 Input types
2.22.1 Web Form HTML5 Input Types
2.23 Cascading Style Sheet
2.24 What does CSS do?
2.25 Why use CSS?
2.26 CSS Comment
2.27 CSS Syntax
2.28 Types of CSS
2.29 CSS Selector
2.30 CSS Font
2.31 CSS Text Properties
2.32 CSS Background Properties
2.33 CSS List Properties
2.34 CSS Margin Properties
2.35 CSS Padding Properties
2.36 CSS Border Style Properties
2.37 HTML <div>tag
2.38 Navigation Bars
2.39 Bootstrap
2.40 Grid System
2.41 Text Classes
2.42 Table Classes
2.43 Image Shape Classes
3
2.44 Jumbotron
2.45 Page Header
2.46 Wells
2.47 Alerts
2.48 Buttons
2.49 Gluphicons
2.50 Badges
2.51 Labels
2.52 Progress Bar
2.53 Pagination
2.54 Breadcrumbs
2.55 Pager
2.56 Dropdown
2.57 Collapsible
2.58 Menus
2.59 Navigation Bars using Bootstrap
2.60 Forms
2.61 Media Object
2.62 Carousel Plugin

3 JAVASCRIPT
3.1 Javascript
3.2 Features of Javascript
3.3 History of Javascript
3.4 Application of Javascript
3.5 Javascript Example
3.6 Javascript Variables
3.7 Javascript Operators
3.8 Conditional Statements
3.9 Looping Statements
3.10 Javascript break & continue
3.11 Dialog Boxes
3.12 Javascript Array
3.13 Javascript Functions
3.14 Built in Functions
3.14.1 String Function
3.14.2 Math Function
3.14.3 Array Function
3.15 Date Methods
3.16 JS Events
3.17 Document Object Model
3.18 Javascript Form Validation

4. Introduction to PHP as Programming Language


4
4.1 Introduction to PHP
4.2 History of PHP
4.3 Open Source
4.4 How PHP Works?
4.5 Relationship between Apache, MySQL & PHP-AMP Module
4.6 Creating & Saving a PHP File
4.7 PHP Start & End Tags
4.8 Comments in PHP
4.9 PHP Echo & Print Statement
4.10 PHP Variable & Variable Rules
4.11 Data Types
4.12 Type Casting
4.13 PHP Operators
4.14 PHP Constants
4.15 Flow Control Statements
4.15.1 If Statement
4.15.2 If…else Statement
4.15.3 If…else if…else Statement
4.15.4 Switch Statement
4.16 Loops
4.16.1 While loop
4.16.2 Do…while loop
4.16.3 For loop
4.16.4 Foreach loop
4.17 Break & Continue

5 PHP CONCEPTS
5.1 Arrays
5.1.1 Types of Array
5.1.2 Functions of Array
5.2 User Defined Function
5.3 Variable Scope
5.4 String Functions
5.5 Math Functions
5.6 Date Functions
5.7 File Functions

6 ADVANCED PHP
6.1 GET & POST Method
6.2 The REQUEST Variable
6.3 PHP Cookies
6.4 PHP Session
6.5 MySQL
6.6 PHP+MySQL Database System
5
6.7 Database
6.8 RDBMS Terminology
6.9 MySQLi
6.9.1 MySQLi Database
6.10 PHP Regular Expressions
6.10.1 Types of Regular Expressions
6.11 File Uploading
6.12 Sending Mail
6.13 AJAX

6
1. WEB PROGRAMMING

1.1 WWW:

 The World Wide Web (WWW) is combination of all resources and users
on the Internet that are using the Hypertext Transfer Protocol (HTTP).
 A broader definition comes from the World Wide Web Consortium
(W3C): "The World Wide Web is the universe of network-accessible
information, an embodiment (example) of human knowledge."
 The Web, as it's commonly known, is often confused with the internet.
Although the two are intricately (complexly) connected, they are
different things. The internet is, as its name implies, a network -- a vast,
global network that incorporates a multitude of lesser networks.
 As such, the internet consists of supporting infrastructure and other
technologies. In contrast, the Web is a communications model that,
through HTTP, enables the exchange of information over the internet.
 Tim Berners-Lee is the inventor of the Web and the director of the W3C,
the organization that oversees its development. Berners-Lee
developed hypertext, the method of instant cross-referencing that
supports communications on the Web, making it easy to link content on
one web page to content located elsewhere.
 The introduction of hypertext revolutionized the way people used the
internet.
 In 1989, Berners-Lee began work on the first World Wide
Web server at CERN. He called the server "httpd” and dubbed the
first client "WWW.”
 Originally, WWW was just a WYSIWYG (“What You See Is What You
Get”) hypertext browser/editor that ran in the NeXTStep environment.
 The World Wide Web has been widely available since 1991.

1.2 Web Browser :

 A web browser (commonly referred to as a browser) is a software


application for accessing information on the World Wide Web.
 When a user requests a particular website, the web browser retrieves
the necessary content from a web server and then displays the
resulting web page on the user's device.
 A web browser is not the same thing as a search engine, though the two
are often confused. For a user, a search engine is just a website, such
7
as Google Search, Bing that stores searchable data about other websites.
However, to connect to a website's server and display its web pages, a
user must have a web browser installed.
 Browsers translate web pages and websites delivered using Hypertext
Transfer Protocol (HTTP) into human-readable content.
 They also have the ability to display other protocols and prefixes, such as
secure HTTP (HTTPS), File Transfer Protocol (FTP), email handling
(mailto:), and files (file:).
 In addition, most browsers also support external plug-ins required to
display active content, such as in-page video, audio and game content.
 As of 2019, more than 4.3 billion people use a browser, which is about
55% of the world's population. The three most popular browsers
are Chrome, Firefox, and Safari.

1.3 URL:

 A Uniform Resource Locator (URL), termed as web address, is a


reference to a web resource that specifies its location on a computer
network and a mechanism for retrieving it.
 A URL is a specific type of Uniform Resource Identifier (URI), although
many people use the two terms interchangeably.
 URLs occur most commonly to reference web pages (http), but are also
used for file transfer (ftp), email, database access, and many other
applications.
 Most web browsers display the URL of a web page above the page in an
address bar. A typical URL could have the form
http://www.example.com/index.html, which indicates a protocol (http),
a hostname (www.example.com) and a file name (index.html).
 URL were defined in RFC 1738 in 1994 by Sir Tim Berners-Lee, the
inventor of the World Wide Web, and the URI working group of the
Internet Engineering Task Force (IETF).

1.4 DNS :

 The Domain Name System (DNS) is the phonebook of the Internet.


Humans access information online through domain names, like
moneycontrol.com or espn.com.
 Web browsers interact through Internet Protocol (IP) addresses. DNS
translates domain names to IP addresses so browsers can load Internet
resources.

8
 Each device connected to the Internet has a unique IP address which
other machines use to find the device.
 DNS servers eliminate the need for humans to memorize IP addresses in
octal format such as 192.168.1.1 (in IPv4), or more complex newer
alphanumeric IP addresses in hexadecimal format such as
2001:0db8:85a3:0000:0000:8a2e:0370:7334 (in IPv6).

1.5 Website :

 A website is a collection of publicly accessible, interlinked Web pages


that share a single domain name.
 Websites can be created and maintained by an individual, group,
business or organization to serve a variety of purposes. Together, all
publicly accessible websites constitute the World Wide Web.
 Websites come in a nearly endless variety, including educational sites,
news sites, forums, social media sites, e-commerce sites, and so on. The
pages within a website are usually a mix of text and other media. That
said, there are no rules dictating the form of a website.
 A person could create a website of nothing but black and white photos
of roses, or the word "cat" linked to another Web page with the word
"mouse."
 However, many sites follow a standard pattern of a homepage that links
off to other categories and content within the website. Originally,
websites were categorized by their top-level domains.
 Some examples include: Government agency websites = .gov,
Educational institutions’ websites = .edu, Nonprofit organizations’
websites = .org, Commercial websites = .com, information sites = .info.
 Although these top-level domains extensions still exist, they say little
about a website's actual content.
 In the modern day internet, the ".com" extension is by far the most
popular domain, a long with many other country-specific extensions.

1.6 WebPage:

 Web page is a document available on world wide web. Web Pages are
stored on web server and can be viewed using a web browser.
 A web page can contain huge information including text, graphics, audio,
video and hyper links. These hyper links are the link to other web pages.
 Web page can be categorized in following 2 types :
o Static Web Page
o Dynamic Web Page

9
1.6.1 Static Web Pages

 As appearing from the word static that static webpage or flat page
means a webpage in which all the information and material is
presented before users as it is exactly stored. Static web page shows
same information and data to all users.
 Static Web pages display the exact same information whenever
anyone visits it. Static Web pages do not have to be simple plain text.
They can feature detailed multimedia design and even videos.
However, every visitor to that page will be received by the exact same
text, multimedia design or video every time he visits the page until
you alter that page's source code.

 In internet technology Hyper Text Markup Language (HTML) was the


first language or channel by which people started to create static web
pages. HTML offers the style of text, paragraphs creation and line
breaks. But the most important function and feature of HTML is link
creation option.

 Static web pages are useful for those materials and contents that are
rarely need to be revised or updated. There are many advantage of
static web page in sense that they are quick and cheap to develop and
there hosting is also inexpensive.

1.6.2 Dynamic Web Pages

 Dynamic web page is that kind of web page, which each time shows
different content and materials to its viewer whenever visited by user.
It randomly changes according to time, accessing and interaction by the
users.
10
 Dynamic Web pages are capable of producing different content for
different visitors from the same source code file. The website can display
different content based on what operating system or browser the visitor
is using, whether she is using a PC or a mobile device, or even the source
that referred the visitor. A dynamic Web page is not necessarily better
than a static Web page.

 Client side scripting and server side scripting are two kinds of dynamic
web pages. In client side scripting web pages change according to your
action in web page. In this system you can download the content and
after modifying it can upload the same. In server side scripting web
pages changes whenever a web page is loaded.

 Examples includes login & sign up pages, application & submission


forums, inquiry and shopping carts pages. Dynamic web pages are
created by the using different internet languages like PHP, ASP, .NET and
JSP.

1.6.3 Differences between Static and dynamic page

 In static web pages the theme and content of web pages remained fixed
and in dynamic web pages they changed according to run time.
 Browsing and loading of static web pages are quicker than dynamic web
pages because unlike dynamic web pages they do not required the request
of server.
 Changing the content in static web pages is a difficult task because you have
to develop and upload a new page while in dynamic web pages server
application do this automatically.
 If file extension of a URL is in .htm or .html then it is a static web pages.
While if it is in .php, .asp and .jsp then it is the example of dynamic web pages.
 Static web pages are created through HTML language while dynamic web
11
pages are created by the usage of PHP, JavaScript and Action script
languages.
 Static web pages plan is an easy and cheap method if you wants to create a
static and non- updating web pages. While dynamic web pages method is
advisable if you have plan to update the content and material frequently.

1.7 Web Development Process:

 Despite conventional wisdom, the core part of website development


and design is not necessary for the coding process.
 Indeed, such technologies as HTML, CSS, and JavaScript give the web we
know its shape and define the way we interact with the information. But
what usually stay behind the scenes and, at the same time, remain the
crucial part of website development life cycle are the stages of
preliminary information gathering, detailed planning, and post-launch
maintenance.
 The exact process will vary slightly from designer to designer, but the
basics are the same. So, here are seven main steps:
1. Information Gathering
2. Planning
3. Design
4. Content Writing and Assembly
5. Coding
6. Testing, Review and Launch
7. Maintenance.
1) Information Gathering:
 This stage, the stage of discovering and researching, determines how the
subsequent steps will look like.
 The most important task at this point is to get a clear understanding of
your future website purposes, the main goals you wish to get, and the
target audience you want to attract to your site.
 Such kind of a website development questionnaire helps to develop the
best strategy for further project management.
 News portal differs from the entertainment websites, and online
resources for teenagers looks different than sites for adults. Different
types of websites provide visitors with different functionality, which
means that different technologies should be used according to purposes.
 A well described and detailed plan based on this pre-development data
can protect you from spending extra resources on solving the
12
unexpected issues such as design changing or adding the functionality
that wasn’t initially planned.
 Estimated time: from 1 to 2 weeks

2) Planning:
 At this stage of the website development cycle, the developer creates
the data that allow a customer to judge how the entire site will look like.
 Based on the information that was gathered together in the previous
phase, the sitemap is created.
 The sitemap should describe the relations between the main areas of
your website. Such representation could help understand how usable
the final product will be.
 It can show you the “relationship” between the different pages of a
website, so you can judge how easy it will be for the end-user to find the
required information or service if he starts from the main page.
 The main reason behind the sitemap creation is to build a user-friendly
and easy to navigate website.
 The other important thing is select technology stack – programming
language, frameworks, CMS that you’re going to use.
 Estimated time: from 2 to 6 weeks

3) Design:
 During the design phase, your website takes shape. All the visual content,
such as images, photos, and videos is created at this step.
 Once again, all the info that was gathered through the first phase is crucial.
The customer and target audience must be kept in mind while you work on
a design.
 The website layout is result of a designer’s work. It can be a graphic sketch
or an actual graphic design.

13
 The primary function of the layout is to represent information structure,
visualize the content, and demonstrate basic functionality. Layouts contain
colors, logos, images & can give a general understanding of future product.
 After that, the customer can review the layout and send you his feedback. If
the client is not sure about some aspects of your design, you should change
the layout and send it back to him. This cycle should be repeated until the
customer is completely satisfied.
 Estimated time: from 4 to 12 weeks

4) Content Writing and Assembly:


 Content writing and compiling usually overlaps with other stages of website
creation, and its role can’t be underestimated.
 At this step, it is necessary to put in writing the very essence you’d like to
communicate to the audience of your website and add calls-to-action.
Content writing also involves the creation of catching headlines, text
editing, writing new text, compiling the existing text, etc., which takes time
and effort.
 As a rule, the client undertakes to provide website content ready to
migrate to the site. It is better when all website content is provided before
or during website coding.
 Estimated time: from 5 to 15 weeks

5) Coding:
 At this step, you can finally start creating the website itself. Graphic
elements that have been designed during the previous stages should be
used to create an actual website.
 Usually, the home page is created first, and then all sub-pages are added,
according to the website hierarchy that was previously created in the form
of a sitemap.
 Frameworks and CMS should be implemented to make sure that the server
can handle the installation and set-up smoothly.
 All static web page elements that were designed during mock-up & layout
creation should be created and tested. Then, special features & interactivity
should be added. A deep understanding of every website development
technology that you’re going to use is crucial at this phase.
 When you use CMS for site creation, you can also install CMS plugins at this
step if there’s a need. The other important step is SEO (Search Engine
Optimization). SEO is the optimization of website elements ( e.g., title,

14
description, keyword) that can help your site achieve higher rankings in the
search engines. And, once again, valid code is pretty important for SEO.
 Estimated time: from 6 to 15 weeks

6) Testing, Review, and Launch


 Testing is probably the most routine part of a process. Every single link
should be tested to make sure that there are no broken ones among them.
You should check every form, every script, run a spell-checking software to
find possible typos.
 Use code validators to check if your code follows the current web
standards. Valid code is necessary, for ex., if cross-browser compatibility is
crucial for you.
 After you check and re-check your website, it’s time to upload it to a server.
An FTP (File Transfer Protocol) software is used for that purpose. After
you deployed the files, you should run yet another, final test to be sure that
all your files have been installed correctly.
 Estimated time: from 2 to 4 weeks

7) Maintenance:
 What’s important to remember is that a website is more of a service
than a product. It’s not enough to “deliver” a website to a user.
 You should also make sure that everything works fine, and everybody is
satisfied and always be prepared to make changes in another case.
Feedback system added to the site will allow you to detect possible
problems the end-users face.
 The highest priority task, in this case, is to fix the problem as fast as you
can. If you won’t, you may find one day that your users prefer to use
another website rather than put up with the inconvenience.
 The other important thing is keeping your website up to date. If you use
a CMS, regular updates will prevent you from bugs and decrease security
risks.
 Estimated time: ongoing

1.8 Scripts
 A script is a set of instructions. For Web pages they are instructions either
to the Web browser (client-side scripting) or to the server (server-side
scripting).

1.8.1 Client-side Scripting


15
 The client is the system on which the Web browser is running. JavaScript is
the main client side scripting language for the Web. Client-side scripts are
interpreted by the browser.
 The process with client-side scripting is:
1. the user requests a Web page from the server

2. the server finds the page and sends it to the user

3. the page is displayed on the browser with any scripts running during or
after display
 So client-side scripting is used to make Web pages change after they arrive
at the browser. It is useful for making pages a bit more interesting and user-
friendly. It can also provide useful gadgets such as calculators, clocks etc.
 Client-side scripts depend on the user's computer. If that computer is slow
they may run slowly. They may not run at all if the browser does not
understand the scripting language.

1.8.2 Server-side Scripting


 The server is where the Web page and other content lives. The server
sends pages to the user/client on request.
 The process is:

1. the user requests a Web page from the server

2. the script in the page is interpreted by the server creating or changing


the page content to suit the Users requirements
3. the page in its final form is sent to the user and then cannot be
changed using server-side scripting
 The use of HTML forms or clever links allow data to be sent to the server
and processed. The results may come back as a second Web page.

 Server-side scripting tends to be used for allowing users to have individual


accounts and providing data from databases. It allows a level of privacy,
personalization and provision of information that is very powerful. E-
commerce and social networking sites are mainly developed with server-
side scripting.

 PHP, JSP and ASP.net are the main technologies for server-side scripting.

 The script is interpreted by the server meaning that it will always work the
same way. Server-side scripts are never seen by the user (so they can't copy
your code). They run on the server and generate results which are sent to

16
the user. Running all these scripts puts a lot of load onto a server but none
on the user's system.

1.9 How the web works?


World wide web use classical client/server architecture.

1.9.1 HTTP Request:


 The HTTP request message consist of following,
 A request line (e.g. GET /index.php HTTP1.1)
 Request header fields (e.g. Accept-Language: en)
 An empty line (CRLF)
 An optional message body
 The request line and other header fields must end with CRLF (Carriage
return, Line Feed) (/r/n)
 A request line contains the method of request followed by the resource
we want and at the end protocol version used.
 HTTP Request Methods: GET, POST, PUT, DELETE etc...
 There are many request header fields available with HTTP Request, some
of are listed below
 Accept : Media type(s) that is/are acceptable for the response. (e.g.
Accept: text/html)
 Accept-Charset: Character sets that are acceptable. (e.g. Accept-
Charset: utf-8)
 Date: The date and time at which the message was originated (e.g.
Date: Tue, 15 Nov 1994 08:12:31 GMT)
 Host: The domain name of the server (e.g. Host: darshan.ac.in)
 User-Agent: details of the browser used (e.g. User-Agent:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36)
 Example:
17
1.9.2 HTTP Response :
 After receiving and interpreting a HTTP request message, a server responds
with an HTTP response message.
 The HTTP response message consist of following,
 Status-Line (format= HTTP-Version SP Status-Code SP Reason-Phrase
CRLF)
 *(( general-header | response-header | entity-header ) CRLF)
 An empty line (CRLF)
 An optional message body
 Status-Line consist of
 HTTP-Version, which can be HTTP/1.1
 Status-Code is a 3 digit code which is in below format
 1xx: Informational - Request received, continuing process
 2xx: Success - The action was successfully received,
understood, and accepted
 3xx: Redirection - Further action must be taken in order to
complete the request
 4xx: Client Error - The request contains bad syntax or cannot
be fulfilled
 5xx: Server Error - The server failed to fulfill an apparently valid
request
 Reason-Phase is a textual representation of the status code in human
readable format.
 Example:

18
 HTTP Status codes with reason phrase:
1. "100": Continue

2. "101": Switching Protocols


3. "200": OK
4. "201": Created
5. "202": Accepted
6. "203": Non-Authoritative Information
7. "204": No Content
8. "205": Reset Content
9. "206": Partial Content
10. "300": Multiple Choices
11. "301": Moved Permanently
12. "302": Found
13. "303": See Other
14. "304": Not Modified
15. "305": Use Proxy
16. "307": Temporary Redirect
17. "400": Bad Request
18. "401": Unauthorized
19. "402": Payment Required
20. "403": Forbidden
21. “404": Not Found
19
22. "405": Method Not Allowed
23. "406": Not Acceptable
24. "407": Proxy Authentication Required
25. "408": Request Time-out
26. "409": Conflict
27. "410": Gone
28. "411": Length Required
29. "412": Precondition Failed
30. "413": Request Entity Too Large
31. "414": Request-URI Too Large
32. "415": Unsupported Media Type
33. "416": Requested range not satisfiable
34. "417": Expectation Failed
35. "500": Internal Server Error
36. "501": Not Implemented
37. "502": Bad Gateway
38. "503": Service Unavailable
39. "504": Gateway Time-out
40. "505": HTTP Version not supported

1.10 Web Server :

 A web server is server software, that can satisfy client HTTP requests on
the public World Wide Web or also on private LANs and WANs.
 The primary function of a web server is to store, process and deliver web
pages to clients.
 This primary function definition was good a few decades ago but nowadays
it is better to use the terms of Web contents and / or Web resources
instead of Web Pages because it cover all kind of contents that can be
delivered to clients by web server.

20
 Examples of Web contents may be HTML files, XHTML files, image files,
style sheets, scripts, other types of generic files that may be downloaded
by clients, etc…
 A user agent, commonly a web browser or web crawler, initiates
communication by making a request for a specific resource using HTTP and
the server responds with the content of that resource or an error message
if unable to do so.
 Commonly used web servers,
 For PHP: Apache
 For ASP: IIS
 For JSP: Tomcat, Glassfish

1.10.1 APACHE Web Server :

 The Apache HTTP Server ("httpd") was launched in 1995 and it has been
the most popular web server on the Internet since April 1996.
 We can download and install apache web server separately from
http://httpd.apache.org/download.cgi
 We can also download Apache web server with bundle like XAMPP, WAMP
or LAMP.
 XAMPP is the most popular PHP development environment consist
of Apache, MariaDB, PHP, Perl and many other packages.
 WAMP is popular PHP development environment for Windows OS.
 LAMP is popular PHP development environment for Linux based OS.
 We are going to use XAMPP bundle as it has installable versions of
Windows as well as Linux.
 We can download XAMPP and install XAMPP from
https://www.apachefriends.org/index.html

21
 configure the XAMPP
 Sometimes we need to change the server configuration in some specific
conditions like,
 Port is occupied
 To add/load modules
 To change max upload size
 To change root directory
 Etc…
 We can configure Apache server using httpd.conf file located at
xampp/apache/conf folder.
 We can configure some parameters of the server using php.ini file located
at xampp/php folder.
 Important settings in httpd.conf file are,
 Changing port number for apache : to change the port number for
apache go to httpd.conf file and change Listen:80 to any other
available port number, we can also change port for https using httpd-
ssl.conf file.
 Loading/Unloading Modules in apache : to load/unload modules in
apache we can go to httpd.conf and remove/add the comment
code(#) from the module we want to load/unload.
 Changing Root Directory: to change root directory we can change
DocumentRoot and <Directory> tag to point new directory.
 Important settings in php.ini file are,

22
 upload_max_filesize setting is for the maximum allowed size for
uploaded files in the scripts.
 post_max_size setting is for the maximum allowed size of POST data
that PHP will accept.
 error_reporting = E_ALL & ~E_NOTICE setting has default values as
E_ALL and ~E_NOTICE which shows all errors except notices.
 max_execution_time = 30, Maximum execution time is set to
seconds for any script to limit the time in production servers.
 mysql.default_host = hostname setting is done to connect to MySQL
with default server if no other server host is mentioned.
 mysql.default_user = username setting is done to connect MySQL
with default username, if no other name is mentioned.
 mysql.default_password = password setting is done to connect
MySQL with default password if no other password is mentioned.

1.11 HTTP Protocol

 HTTP stands for Hyper Text Transfer Protocol.

 It is a protocol used to access the data on the World Wide Web (www).

 The HTTP protocol can be used to transfer the data in the form of
plain text, hypertext, audio, video, and so on.

 This protocol is known as Hyper Text Transfer Protocol because of


its efficiency that allows us to use in a hypertext environment
where there are rapid jumps from one document to another
document.

 HTTP is similar to the FTP as it also transfers the files from one
host to another host. But, HTTP is simpler than FTP as HTTP uses
only one connection, i.e., no control connection to transfer the
files.

 HTTP is used to carry the data in the form of MIME-like format.

 HTTP is similar to SMTP as the data is transferred between client and


server. The HTTP differs from the SMTP in the way the messages are
sent from the client to the server and from server to the client. SMTP
messages are stored and forwarded while HTTP messages are
delivered immediately.

1.11.1 Features of HTTP:

o Connectionless protocol:
23
HTTP is a connectionless protocol. HTTP client initiates a request and
waits for a response from the server. When the server receives the
request, the server processes the request and sends back the
response to the HTTP client after which the client disconnects the
connection. The connection between client and server exist only
during the current request and response time only.

o Media independent:
HTTP protocol is a media independent as data can be sent as long
as both the client and server know how to handle the data content.
It is required for both the client and server to specify the content
type in MIME-type header.

o Stateless:
HTTP is a stateless protocol as both the client and server know each
other only during the current request. Due to this nature of the
protocol, both the client and server do not retain the information
between various requests of the web pages.

1.12 HTTPS Protocol

 HTTPS is the protocol where encrypted HTTP data is transferred over


a secure connection. By using secure connection such as Transport
Layer Security or Secure Sockets Layer, the privacy and integrity of
data are maintained and authentication of websites is also validated.
 HTTPS ensures data security over the network - mainly public
networks like Wi-Fi. HTTP is not encrypted and is vulnerable to
attackers who are eavesdropping and can gain access to website
database and sensitive information.
 HTTPS encryption is done bi-directionally, which means that the data
is encrypted at both the client and server sides. Only the client can
decode the information that comes from the server. So, HTTPS does
encryption of data between a client and a server, which protects
against hackers.
 But how do you ensure if you are seeing an HTTPS-enabled web
page? Just check the address bar that carries the site name against
different background colors with a lock icon at the left corner.
 However, this design can be different for different browsers. For
example, consider going to a bank website, say hdfcbank.com. A non-
secured HTTP will open up. But when we go to the login page, we can
see an HTTPS in the address bar with some specific design.
 HTTPS is mainly used by those websites which deal with monetary
transactions or transfer user's personal data which could be

24
highly sensitive. Banking websites are common examples of
HTTPS.

1.13 FTP

 FTP stands for File transfer protocol.

 FTP is a standard internet protocol provided by TCP/IP used


for transmitting the files from one host to another.

 It is mainly used for transferring the web page files from their
creator to the computer that acts as a server for other
computers on the internet.

 It is also used for downloading the files to computer from other


servers.

 File Transport Protocol, or FTP, is an open protocol standard that is


widely used to transport and receive large files.

 It can also be used to send configuration files and software


updates for network switches and routers.

 FTP uses ports for communications and also uses encryption to


protect the information being received and sent.

1.13.1 Advantages of FTP:


 Speed: One of the biggest advantages of FTP is speed. The FTP
is one of the fastest ways to transfer the files from one
computer to another computer.
 Efficient: It is more efficient as we do not need to complete all
the operations to get the entire file.
 Security: To access the FTP server, we need to login with
the username and password. Therefore, we can say that
FTP is more secure.
 Back & forth movement: FTP allows us to transfer the files back
and forth. Suppose you are a manager of the company, you send
some information to all the employees, and they all send
information back on the same server.

1.14 Web Hosting :


 Web hosting is a service that allows organizations and individuals
to post a website or web page onto the Internet.
 A web host, or web hosting service provider, is a business that
provides the technologies and services needed for the website or
25
webpage to be viewed in the Internet. Websites are hosted, or
stored, on special computers called servers.
 When Internet users want to view your website, all they need to
do is type your website address or domain into their browser.
 Their computer will then connect to your server and your Web-
Pages will be delivered to them through the browser.
 Most hosting companies require that you own your domain in
order to host with them. If you do not have a domain, the hosting
companies will help you purchase one.

Here are some features you should be expecting from your


hosting provider:
Email Accounts:
 As mentioned earlier, most hosting providers require users to
have their own domain name. With a domain name (e.g.
www.yourwebsite.com) and email account features provided by
your hosting company, you can create domain email accounts
(e.g. [email protected]).

FTP Access:
 The use of FTP lets you upload files from your local computer to your web
server. If you build your website using your own HTML files, you can
transfer the files from your computer to the web server through FTP,
allowing your website to be accessed through the internet.
1.14.1 Types of Web Hosting Services

1.) Domain Hosting


A good option for small businesses is to pay for domain hosting. Domain
hosting allows you to host your site anywhere you like: on an ISP, a free
hosting service, or even your own server. You buy a domain name and
have the provider forward all requests for that domain to the actual web
location. This is often less expensive than buying both the domain and the
hosting service, and it allows businesses to brand their URLs.

26
2.) Shared hosting
Shared hosting is perfect for entry-level website hosting. This is where
your website will be stored on the same server as multiple other websites.
With a shared hosting plan, all domains share the same server resources,
such as RAM (Random Access Memory) and CPU (Central Processing Unit).
However, because all resources are shared, the cost of shared hosting
plans are relatively low, making them an excellent option for website
owners in their beginning stages.

Although shared hosting provides website owners with a more simplistic


approach to the web, the trade-off is that you’re sharing the server with
multiple other website owners. This means that surges in usage can
ultimately affect your website’s user experience.

Shared hosting plans are ideal for website owners that do not receive a
large amount of web traffic.

3.) Virtual private server (VPS) hosting


A VPS hosting plan is the ultimate middle ground between a shared server
and a dedicated server. It’s ideal for website owners that need more
control, but don’t necessarily need a dedicated server.

VPS hosting is unique because each website is hosted within its own space
on the server, though it still shares a physical server with other users.
While VPS hosting provides website owners with more customization and
storage space, they’re still not able to handle incredibly high traffic levels
or spikes in usage meaning that the site performance can still be affected
by other sites on the server

Typically, VPS hosting is used by website owners who want dedicated


hosting but don’t have the technical knowledge needed. VPS hosting
offers the cost benefits of shared hosting with the control of dedicated
hosting. A great choice for advanced users and those that want specific
software and package installations.

4.) Dedicated server hosting


Dedicated hosting gives website owners the most control over the server
that their website is stored on. That’s because the server is exclusively
rented by you and your website is the only one stored on it. This means
that you have full root and admin access, so you can control everything
from security to operating system that you run.

However, all that control comes with a price.

Dedicated servers cost are one of the most expensive web hosting
options. Typically, they are used by website owners with high levels of
website traffic, and those who are in need of complete control of their
servers. In addition, a high level of technical expertise is required for the
27
installation and ongoing management of the server.

5.) Cloud hosting


Cloud hosting is the current buzzword of the technology industry. In
regards to web hosting, it means many computers working together,
running applications using combined computing resources. It’s a hosting
solution that works via a network and enables companies to consume the
computing resource like a utility.

This allows users to employ as many resources as they need without


having to build and maintain their own computing infrastructure. The
resources that are being used are spread across several servers, reducing
the chance of any downtime due to a server malfunction.

Cloud-based hosting is scalable, meaning your site can grow over time,
using as many resources as it requires and while the website owner only
pays for what they need.

6.) Managed hosting


Most hosting packages you will find online are likely to be managed.
Hosting companies provide technical services such as hardware and
software setup and configuration, maintenance, hardware replacement,
technical support, patching, updating and monitoring. With managed
hosting, the provider looks after the day-to-day management of the
hardware, operating systems and standardised applications.

Although there are many different options to choose from when it comes
to web hosting, it all comes down to choosing a plan that fits your needs.
Each plan caters to the specifications of different groups and realizing
what your needs in a website are will help you ensure that you’re choosing
the right plan for you and your business.

7.) Collocation
Instead of keeping servers in-house or at a private data center, you may
choose to “co- locate” your equipment by renting space in a collocation
center. The center will provide the power, bandwidth, IP address and
cooling systems that your server requires. Space is rented out in racks and
cabinets.

Collocation gives access to higher levels of bandwidth than a normal office


server room at a much lower cost. You’re left to your own devices
(literally) and will be expected to take care of everything including the
hardware, software and services.
8) Free Web Hosting
Free web hosting is another good option for smaller, personal websites.
There are many free hosting providers that offer all types of features;

28
some include CGI access and more. The drawback to most free hosting
services is that they are funded by advertising that appears on your site,
so free web hosting so generally best for personal, rather than business,
websites.

9) Paid Hosting
With paid hosting, you pay a fee for space and services on a web hosting
provider's server. Monthly fees can range from a few dollars to several
hundred dollars. Obviously, the more you pay, the more features you
should have at your disposal. Services can include CGI access, database
support, ASP, ecommerce, SSL, additional space on the server, extra
bandwidth, and more.

10) Virtual hosting

Virtual hosting is a method for hosting multiple domain names (with


separate handling of each name) on a single server (or pool of servers).
This allows one server to share its resources, such as memory and
processor cycles, without requiring all services provided to use the same
host name. The term virtual hosting is usually used in reference to web
servers but the principles do carry over to other internet services.

One widely used application is shared web hosting. The price for shared
web hosting is lower than for a dedicated web server because many
customers can be hosted on a single server. It is also very common for a
single entity to want to use multiple names on the same machine so that
the names can reflect services offered rather than where those services
happen to be hosted.

There are two main types of virtual hosting, name-based and IP-based.
Name-based virtual hosting uses the host name presented by the client.
This saves IP addresses and the associated administrative overhead but
the protocol being served must supply the host name at an appropriate
point. In particular, there are significant difficulties using name-based
virtual hosting with SSL/TLS. IP-based virtual hosting uses a separate IP
address for each host name, and it can be performed with any protocol
but requires a dedicated IP address per domain name served. Port-based
virtual hosting is also possible in principle but is rarely used in practice
because it is unfriendly to users.

29
Name-based and IP-based virtual hosting can be combined: a server may have
multiple IP addresses and serve multiple names on some or all of those IP
addresses. This technique can be useful when using SSL/TLS with wildcard
certificates. For example, if a server operator had two certificates, one for
*.example.com and one for *.example.net, the operator could serve
foo.example.com and bar.example.com off the same IP address but would need
a separate IP address for baz.example.net.

11) Multi-Homing

 Multi-homing is a mechanism used to configure one computer with


more than one network interface and multiple IP addresses. It
provides enhanced and reliable Internet connectivity without
compromising efficient performance. The multi-homing computer
is known as the host and is directly or indirectly connected to more
than one network.

 Multi-homing provides many benefits, including the following:

 The multiple simultaneous Internet connections make system


failure less likely than with a system with a single Internet
connection.
 Users interact with the Internet through multiple doorways. During
failover, only one door closes, while the other doors continue
working.
 In Web management, multi-homing helps load balancing and
allows a network to work with the lowest downtime.
 The system is maintained during disaster and recovery.
30
The two main types of multi-homing are:
1. IPv4 multi-homing:

A multi-homed public IP address must be configured with two or more


Internet service provider (ISP) connections. When any link or route fails,
network traffic is automatically rerouted. IPv4's major drawback is its
central connection point (shared transmission line and/or edge router) for
two ISPs, which can result in failure of the entire network if the central
point fails. The Border Gateway Protocol (BGP) is used for multi-homing
purposes.

2. IPv6 multi-homing:

Multi-homing is on the rise with IPv6 computer systems, which provide


more efficient support for it. Many communication devices are shifting to
IPv6, and multi-homing allows easy data transfer. However, IPv6 multi-
homing is not yet standardized.

1.15 Document Root

The document root is a directory (a folder) that is stored on your host's


servers and that is designated for holding web pages. When someone else
looks at your web site, this is the location they will be accessing.

In order for a website to be accessible to visitors, it must be published to the


correct directory, the "document root."

If you log into your host you might see a number of directories as shown

below:
Remember, every host is different, so yours will probably not look exactly like
the picture above. Yours is quite likely to have a completely different set of
folders.
In the example shown above, the document root is the "www" directory,
but of course your host may well use a different folder. Some of the more
common alternatives are:
Htdocs
httpdocs
html
public_html
31
web
empty — no value (such as GoDaddy-hosted sites)
Your host may even have several folders nested inside each other, one of
which is the document root. In the example above the document root was:
/www/

but your host may use something like one of these:


/web/public/
/example.com/www/public/
/example.com/public_html/

Your primary domain is rooted in the public_html folder.

Your addon and subdomain names will be rooted to their own folders inside
public_html.

After you create an Addon domain (or subdomain), you can find the Document
Root inside cPanel.

Your host's technical support should have sent you this information when your
first signed up for their services. If necessary, please contact them to find out
your document root.

To further complicate matters, not all hosts refer to this folder as the
document root! They might instead call it:
Start directory
Home directory
Web publishing
Directory Remote
Root

32
2. HTML and CSS
2.1 HTML :

 HTML stands for Hyper Text Markup Language and is used to create
web pages.
 Hypertext is a way of organizing information so readers can choose their
own path through the material. Instead of clicking through sequentially
organized pages, a hypertext user clicks specially highlighted text, called
a hyperlink (or just a link for short), to go directly to information of
interest.
 Markup Language you simply “mark up” a text document with tags that
tell a Web browser how to structure and display it.
 HTML originally was developed with the intent of defining the structure
of documents (headings, paragraphs, lists, and so forth) to facilitate the
sharing of scientific information between researchers.
 The name of the source file has to end with the extension : “.htm” or
“.html “.

2.2 USE OF HTML DOCUMENTS

 The World Wide Web commonly known as the Web is a system of


interlinked hypertext documents that are accessed via the Internet.
 With a web browser, one can view web pages that may contain text,
images, videos, and other multimedia and navigate between them via
hyperlinks.

2.3 HTML TAGS

 HTML markup tags are usually called HTML tags.


 HTML tags are keywords (tag names) surrounded by angle brackets like
<html>.
 HTML tags normally come in pairs like <p> and </p>.
 The first tag in a pair is the start tag, the second tag is the end tag.
 The end tag is written like the start tag, with a slash before the tag name.
 Start and end tags are also called opening tags and closing tags.
 <tagname>content</tagname>

33
2.4 Advantages of HTML
 Easy to use.
 Support on almost every browser.
 Widely used on almost every website.
 Free of cost.
 Easy to learn and code even novice programmer.

2.5 HTML Document Structure


<HTML>
<HEAD>
<TITLE>My first HTML document</TITLE>
</HEAD>
<BODY>
Hello world!
</BODY>
</HTML>

2.6 BASIC TAGS & ATTRIBUTES

2.6.1 TAGS

 Tags are instructions that are embedded into the text of the documents.
 An HTML tag is a signal to a browser that it should do something other
than just through text up on the screen.
 Syntax : < TAG > … … … … </TAG >
 Note: Tags START with an open angle bracket (<) and END with close
angle bracket (>).

2.6.2 Types of TAGS

 TAGS are basically divided into two parts :

1. Paired Tags :
 The Tags written along with a companion tag is called PAIRED TAG.
 For example,
 The <B> tag with its companion tag </B>.
 The text between this both tag are written in BOLD.
 The effect of paired tag is applied only to the text they contain.
 The OPENING tag activates the effect & the CLOSING tag closes the effect.

34
2. Singular Tags:
 This tag is also known as STAND-ALONE tags.
 A singular tags does not have a companion tag.

2.6.3 ATTRIBUTES

 Additional Information supplied to an HTML Tag is called as ATTRIBUTES


of Tags.
 Attributes are written immediately following the tag separated by a
Space.
 Multiple Attributes can be associated with a Tag.
 Attribute are used with tag that provides the extract information and
actions.
 Some HTML tags require additional information to be supplied to them.
 For example…when a picture is placed on the screen, information like the
HEIGHT and WIDTH of the Picture can be specified.

 For example :
<IMG src=“filename.jpg” height=”500px” width=”100%”>
 Here <IMG> tag tells a web browser to display a graphical image but
which image? Then src attribute give picture file path information and
display that picture in the browser.

2.7 DOCUMENT TAG


<html></html>
The <html> tag tells the browser that this is an HTML document. The
<html> tag represents the root of an HTML document. The <html> tag is the
container for all other HTML elements
<head></head>
The <head> element is a container for all the head elements. The <head>
element must include a title for the document, and can include scripts,
styles, meta information, and more.
The following elements can go inside the <head> element: <title> (this
element is required in the head section), <style>, <base>, <link>, <meta>,
<script>, <noscript>

35
<body></body>
The <body> tag defines the document's body. The <body> element contains
all the contents of an HTML document, such as text, hyperlinks, images,
tables, lists, etc.
<title></title>
The <title> tag is required in all HTML documents and it defines the title of
the document. The <title> element:
a) defines a title in the browser toolbar .
b) provides a title for the page when it is added to favorites .
c) displays a title for the page in search-engine results .

<!-- -->
The comment tag is used to insert comments in the source code. Comments
are not displayed in the browsers. You can use comments to explain your code,
which can help you when you edit the source code at a later date. This is
especially useful if you have a lot of code.
Example :
<!--This is a comment. Comments are not displayed in the browser-->

2.8 TEXT FORMATTING TAG

<h1></h6>
The <h1> to <h6> tags are used to define HTML headings. <h1> defines the
most important heading. <h6> defines the least important heading.

Example :
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>

<h6>This is heading 6</h6>


Attributes
36
Attribute Value Description

Align left Specifies the alignment of a text.


center
right
justify

<p>
The <p> tag defines a paragraph. Browsers automatically add some space
(margin) before and after each <p> element.

Attributes
Attribute Value Description

Align left Specifies the alignment of a text.


center
right
justify

<Pre></Pre>
The <pre> tag defines preformatted text. Text in a <pre> element is displayed
in a fixed-width font (usually Courier), and it preserves both spaces and line
breaks.

<B></B>
The <b> tag specifies bold text.
Example: <p>This is normal text - <b>and this is bold text</b>.</p>

<U></U>
The <u> tag represents some text that should be stylistically different from
normal text, such as misspelled words or proper nouns in Chinese.
Example :<p>This is a <u>paragraph</u>.</p>

<I></I>
The <i> tag defines a part of text in an alternate voice or mood. The content of
the <i> tag is usually displayed in italic. The <i> tag can be used to indicate a
37
technical term, a phrase from another language, a thought, or a ship name,
etc.
Example :<p>He named his car <i>The lightning</i>, because it was very
fast.</p>

<tt></tt>
The <tt> tag defines teletype text.
Example :<p><tt>Teletype text</tt></p>

<sub></sub>
The <sub> tag defines subscript text. Subscript text appears half a character
below the normal line, and is sometimes rendered in a smaller font. Subscript
text can be used for chemical formulas, like H2O.
Example :

<p>This text contains <sub>subscript</sub>


text.</p>

<strike></strike>
The <strike> tag defines strikethrough text.
Example :
<p>Version 2.0 is <strike>not yet available!</strike> now available!</p>

<sup></sup>
The <sup> tag defines superscript text. Superscript text appears half a
character above the normal line, and is sometimes rendered in a smaller font.
Example :
<p>This text contains <sup>superscript</sup> text.</p>

<Big></Big>
The <big> tag defines bigger text.
Example :<p><big>Bigger text</big></p>
38
<Strong></Strong>
The <strong> tag is a phrase tag. It defines important text.
Example :<strong>Strong text</strong>

<Small></Small>
The <small> tag defines smaller text (and other side comments).
Example :College<small>of Information & Technology </small>

<font></font>
The <font> tag specifies the font face, font size, and color of text.
Attributes
Attribute Value Description

Color rgb(x,x,x),#xxxxxx Specifies the color of text


colorname

Face font_family Specifies the font of text

Size Number Specifies the size of text

Example :
<font size="3" color="#0000FF">This is some text!</font>
<font size="3" color="rgb(255,0,0)">This is some
text!</font>
<font size="3" color="red">This is some
text!</font>

<blink></blink>
The HTML Blink Element (<blink>) is a non-standard element causing the
enclosed text to flash slowly.

39
Example: <blink> Example of blink tag.</blink>

<marquee></marquee>
The HTML <marquee> element is used to insert a scrolling area of text.
Attribute Value Description

Behavior Scroll Sets how the text is scrolled within the marquee.
Possible values are scroll, slide and alternate. If no
Slide
value is specified, the default value is scroll.
Alternate

Bgcolor Sets the background color through color name or


hexadecimal value.
Direction Left Sets the direction of the scrolling within the
marquee. Possible values are left, right, up and
Right
down. If no value is specified, the default value is
Up left.
Down

Height Sets the height in pixels or percentage value.

Hspace Sets the horizontal margin

Loop Sets the number of times the marquee will scroll.


If no value is specified, the default value is −1,
which means the marquee will scroll continuously.

Scrollamount Sets the amount of scrolling at each interval in


pixels. The default value is 6.

Scrolldelay Sets the interval between each scroll movement in


milliseconds. The default value is 85. Note that any
value smaller than 60 is ignored and the value 60 is
used instead, unless true speed is specified.
Truespeed By default, scrolldelay values lower than 60 are
ignored. If truespeed is present, those values are
not ignored.
Vspace Sets the vertical margin in pixels or percentage
value.
40
Width Sets the width in pixels or percentage value.

Example:
1. <marquee>This text will scroll from right to left</marquee>
2. <marquee direction="up">This text will scroll from bottom to
top</marquee>
3. <marquee direction="down" width="250" height="200"
behavior="alternate">
<marquee behavior="alternate">This text will bounce</marquee>
</marquee>

2.9 HTML List


 HTML lists allow web developers to group a set of related items in lists .
 There are three types of list available in HTML:
1. Ordered List
2. Unordered List
3. Description List

1.Ordered List : <ol></ol>


The <ol> tag defines an ordered list. An ordered list can be numerical or
alphabetical. Use the <li> tag to define list items.

Attribute Value Description

Start Number Specifies the start value of an ordered list

Type 1 Specifies the kind of marker to use in the


A list
a
I
I

Example:
<ol type=i> <ol start="50">
<li>Coffee</li> <li>Coffee</li>
<li>Tea</li> <li>Tea</li>
<li>Milk</li> <li>Milk</li>
</ol> </ol>

41
<il></li>
The <li> tag defines a list item. The <li> tag is used in ordered lists(<ol>),
unordered lists (<ul>).
2.Unordered List : <ul></ul>
The <ul> tag defines an unordered (bulleted) list. Use the <ul> tag together
with the <li> tag to create unordered lists.
Attribute Value Description

Type disc Specifies the kind of marker to use in the


square list
circle

3.Description List : <dl></dl>

A description list is a list of terms, with a description of each term.

The <dl> tag defines the description list, the <dt> tag defines the term (name),
and the <dd> tag describes each term.

Example: <dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>

2.10 HTML Link :

2.10.1CREATING LINK WITH OTHER PAGES : <A></A>


The <a> tag defines a hyperlink, which is used to link from one page to
another. The most important attribute of the <a> element is the href attribute,
which indicates the link's destination.
By default, links will appear as follows in all browsers:
• An unvisited link is underlined and blue.
• A visited link is underlined and purple.
• An active link is underlined and red .
Attribute Value Description

Href URL Specifies the URL of the page the link goes
to

42
Target _blank Specifies where the linked
_self document is to be loaded
_top
_parent
frame_name

Syntax : <a href="url">link text</a>


Example : <a href="http://www.google.com">Visit google.com!</a>
<a href=”http://www.google.com” target=”_blank”>Visit google.com!</a>

2.10.2 Link Titles

The title attribute specifies extra information about an element. The


information is most often shown as a tooltip text when the mouse moves over
the element.

Example :

<a href="https://www.google.com" title="Go to Google">Google Search</a>

2.10.3 Absolute URLs vs. Relative URLs

Both examples above are using an absolute URL (a full web address) in
the href attribute.

A local link (a link to a page within the same website) is specified with
a relative URL (without the "https://www" part):

Example:

<h2>Absolute URLs</h2>
<a href="https://www.google.com/">Google</a>

<h2>Relative URLs</h2>
<a href="html_images.php">HTML Images</a>
<a href="/css/default.php">CSS Tutorial</a>

2.10.4 Link to an Email Address

Use mailto: inside the href attribute to create a link that opens the user's email
program (to let them send a new email):

Example: <a href="mailto:[email protected]">Send email</a>

43
2.10.5 Button as a Link

To use an HTML button as a link, you have to add some JavaScript code.

JavaScript allows you to specify what happens at certain events, such as a click
of a button:

Example:

<button onclick="document.location='default.php'">HTML Tutorial</button>

2.10.6 <Link>
The <link> tag defines the relationship between a document and an external
resource.
The <link> tag is most used to link to style sheets.
Attribute Value Description

Href URL Specifies the location of the linked


document

Example :
<head>
<link rel="stylesheet" type="text/css" href="theme.css">
</head>

2.11 INSERTING SPECIAL CHARACTERS :


Result Description Entity Name Entity Number
non-breaking space &nbsp; &#160;

< less than &lt; &#60;

> greater than &gt; &#62;


& ampersand &amp; &#38;

¢ cent &cent; &#162;


£ pound &pound; &#163;

¥ yen &yen; &#165;


€ euro &euro; &#8364;

44
© copyright &copy; &#169;
® registered trademark &reg; &#174;

₹ Rupee Symbol &#8377;

2.12 INSERTING IMAGE : <img>

 The <img> tag defines an image in an HTML page.


 It has two required attributes: src and alt.

Example : <img src="smiley.gif" alt="Smiley face" height="42px"


width="100%">

Attribute Value Description

Align top Specifies the alignment of an image according to


bottom surrounding elements
middle
left
right
Alt Text Specifies an alternate text for an image

Border Pixels Specifies the width of the border around an image

Height Pixels Specifies the height of an image

Hspace Pixels Specifies the whitespace on left and right side of an


image
Src URL Specifies the URL of an image

Vspace Pixels Specifies the whitespace on top and


bottom of an image

Width Pixels Specifies the width of an image

45
2.12.1 Use an Image as a Link

To use an image as a link, just put the <img> tag inside the <a> tag:

Example :

<a href="default.php">
<img src="smiley.gif" alt="HTML
tutorial" style="width:42px;height:42px;">
</a>

2.13 Relative Path & Absolute Path:

Relative Path : A relative file path points to a file relative to the current page.If
you have your images in a sub-folder, you must include the folder name in
the src attribute:

Example :

Path Description

<img src="picture.jpg"> The "picture.jpg" file is located in the


same folder as the current page

<img src="images/picture.jpg"> The "picture.jpg" file is located in the


images folder in the current folder

<img src="/images/picture.jpg"> The "picture.jpg" file is located in the


images folder at the root of the current
web

<img src="../picture.jpg"> The "picture.jpg" file is located in the


folder one level up from the current
folder

Absolute Path: An absolute path is defined as specifying the location of a file


or directory from the root directory(/). In other words,we can say that an
46
absolute path is a complete path from start of actual file system from /
directory.

Example :

<img src="D://HTML/images/green.jpg" alt="Absolute Path">

2.14 Image Maps

The HTML <map> tag defines an image map. An image map is an image with
clickable areas. The areas are defined with one or more <area> tags.

Try to click on the computer, phone, or the cup of coffee in the image below:

Example:

<html>
<body>

<h2>Image Maps</h2>
<p>Click on the computer, the phone, or the cup of coffee to go to a new page
and read more about the topic:</p>

<img src="workplace.jpg" alt="Workplace" usemap="#workmap" width="400"


height="379">

<map name="workmap">
<area shape="rect" coords="34,44,270,350" alt="Computer"
href="computer.htm">
<area shape="rect" coords="290,172,333,250" alt="Phone"
href="phone.htm">
47
<area shape="circle" coords="337,300,44" alt="Cup of coffee"
href="coffee.htm">
</map>

</body>
</html>
How Does it Work?

The idea behind an image map is that you should be able to perform different
actions depending on where in the image you click.

To create an image map you need an image, and some HTML code that
describes the clickable areas.

2.15 TABLE : <table></table>


The <table> tag defines an HTML table. An HTML table consists of the <table>
element and one or more <tr>, <th>, and <td> elements. The <tr> element
defines a table row, the <th> element defines a table header, and the <td>
element defines a table cell.

Attribute Value Description

Align left Specifies the alignment of a table according to


center surrounding text
right
Bgcolor rgb(x,x,x) Specifies the background color for a table
#xxxxxx
colorname

Border “1” Specifies whether the table cells should have borders
or not

Cellpadding Pixels Specifies the space between the cell wall and the cell
content
Cellspacing Pixels Specifies the space between cells

Width Pixels,% Specifies the width of a table

48
<tr></tr>
 The <tr> tag defines a row in an HTML table.
 A <tr> element contains one or more <th> or <td> elements.

Attribute Value Description

Align right Aligns the content in a table row


left
center
justify

Bgcolor rgb(x,x,x) Specifies a background color for a table row


#xxxxxx
color name

Valign top Not supported in HTML5.


middle Vertical aligns the content in a table row
bottom
baseline

<th></th> & <td></td>


An HTML table has two kinds of cells:
• Header cells - contains header information (created with the <th>
element)
• Standard cells - contains data (created with the <td> element)
The <th> tag defines a header cell in an HTML table. The text in <th> elements
are bold and centered by default.

Attribute Value Description

Align left Aligns the content in a header cell


right
center
justify
char

49
Bgcolor rgb(x,x,x) Specifies the background color of a header cell
#xxxxxx
colorname

Colspan Number Specifies the number of columns a header cell


should span
Height pixels Sets the height of a header cell
%

Rowspan Number Specifies the number of rows a header cell


should span
Valign top Vertical aligns the content in a header cell
middle
bottom
baseline
Width Pixels,% Specifies the width of a header cell

he <td> tag defines a standard cell in an HTML table. The text in <td> elements
are regular and left-aligned by default.

Example:
<table>
<tr>
<th>Sr.</th><th>Name</th>
</tr>
<tr>
<td>1</td><td>ABC</td>
</tr>
</table>

<caption>
The <caption> tag defines a table caption. The <caption> tag must be inserted
immediately after the <table> tag.
Example : <table>
<caption>Monthly savings</caption>
<tr>
<th>Sr.</th><th>Name</th>
50
</tr>
<tr>
<td>1</td><td>ABC</td>
<td>2</td><td>XYZ</td>
</tr>
</table>

2.15.1 Tables Inside of Tables:

<table>
<tr>
<th>ABC</th><th>XYZ</th>
</tr>
<tr>
<table>
<tr>
<th>Sr.</th><th>Name</th>
</tr>
<tr>
<td>1</td><td>ABC</td>
<td>2</td><td>XYZ</td>
</tr>
</table>
</tr>
</table>

2.15.2 Cell Padding and Cell Spacing:

 Cell padding is the space between the cell edges and the cell content.
 By default the padding is set to 0.

 Cell spacing is the space between each cell.


 By default the space is set to 2 pixels.

51
Example:
<table border="2px" cellspacing="10" height="10px" width="10px"
bgcolor="cyan">

<!- - <table border="2px" cellpadding="10" height="10px" width="10px"


bgcolor="cyan">

-->

<tr>
<th>Product</th>
</tr>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>abc</td>
<td>20</td>
</tr>
</table>

2.15.3 Colspan & Rowspan :

HTML tables can have cells that spans over multiple rows and/or columns.
 To make a cell span over multiple columns, use the colspan attribute:

Example:
<table>
<tr>
<th colspan="2">Name</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>43</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>57</td>
</tr>
</table>

52
Name Age
Jill Smith 43
Eve Jackson 57

 To make a cell span over multiple rows, use the rowspan attribute:
Example:
<table>
<tr>
<th>Name</th>
<td>Jill</td>
</tr>
<tr>
<th rowspan="2">Phone</th>
<td>555-1234</td>
</tr>
<tr>
<td>555-8745</td>
</tr>
</table>

Name Jill
555-1234
Phone
555-8745

2.16 FRAMES:
<frameset></frameset>

 The <frameset> element holds one or more <frame> elements. Each


<frame> element can hold a separate document.
 The <frameset> element specifies HOW MANY columns or rows there
will be in the frameset, and HOW MUCH percentage/pixels of space will
occupy each of them.

Attribute Value Description

Cols pixels Specifies the number and size of columns


% in a frameset
*

53
Rows pixels Specifies the number and size of rows in a
%,* frameset

<frame></frame>
The <frame> tag defines one particular window (frame) within a <frameset>.
Each <frame> in a <frameset> can have different attributes, such as border,
scrolling, the ability to resize, etc.

Attribute Value Description

Frameborder 0 Specifies whether or not to display a


1 border around a frame

Marginheight Pixels Specifies the top and bottom margins of a


frame
Marginwidth Pixels Specifies the left and right margins of a
frame
Scrolling yes Specifies whether or not to display
no scrollbars in a frame
auto
Src URL Specifies the URL of the document to show
in a frame

Example : Creating Column Frames


<frameset cols="25%,*,25%">
<frame src="frame_a.htm">
<frame src="frame_b.htm">
<frame src="frame_c.htm">
</frameset>
Example:Creating Row Frames
<frameset rows="14%,11%,15%">
<frame src="../CSS/img.jpg">
<frame src="../CSS/img.jpg">
<frame src="../CSS/img.jpg">
</frameset>

Example:Creating Complex Frames [ using rows and cols attribute ]


<frameset rows="80%,20%">
54
<frameset cols="20%,40%,20%">
<frame src="image.jpg">
<frameset rows="40%,20%">
<frame src="image.jpg">
<frame src="image.jpg">
</frameset>
<frame src="image.jpg">
</frameset>
<frame src="image.jpg">
</frameset>

2.17 FORM
<form></form>
HTML forms are used to pass data to a server. An HTML form can contain input
elements like text fields, checkboxes, radio-buttons, submit buttons and more.
A form can also contain select lists, textarea, fieldset, legend, and label
elements. The <form> tag is used to create an HTML form:
<form>
input elements
:
</form>

 Attributes of form

Action
 The action attribute specifies where to send the form-data when a form
is submitted.
 Syntax: <form action="URL">
 Possible values for URL:
o An absolute URL - points to another web site (like action =
"http://www.example.com/example.htm")
o A relative URL - points to a file within a web site (like
action="example.php")

Enctype
 The enctype attribute specifies how the form-data should be encoded
when submitting it to the server.
 Syntax: <form enctype="value">
 Note: The enctype attribute can be used only if method="post".

55
Method
• The method attribute specifies how to send form-data (the form-data is sent
to the page specified in the action attribute).
• Syntax: <form method="get|post">

Name
 The name attribute specifies the name of a form.
 The name attribute is used to reference elements in a JavaScript, or to
reference form data after a form is submitted.
 Syntax: <form name = "text">
o text - Specifies the name of the form

Target
 The target attribute specifies a name or a keyword that indicates where
to display the response that is received after submitting the form.
 Syntax: <form target="_blank|_self|_parent|_top">

 INPUT ELEMENTS
The most important form element is the <input> element. The <input>
element is used to select user information. An <input> element can vary in
many ways, depending on the type attribute. An <input> element can be of
type text field, checkbox, password, radio button, submit button, and more.

1. Text Fields
<input type="text"> defines a one-line input field that a user can
enter text into:
Example:
<form>

56
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
</form>

2. Password Field
<input type="password"> defines an input field in which text is
covered by bullets.
Example:
<form>
Password: <input type="password" name="pwd">
</form>

3. Radio Buttons
<input type="radio"> defines a radio button. Radio buttons let a user select
ONLY ONE of a limited number of choices:
Example:
<form>
<input type="radio" name="gender" value="male">Male<br>
<input type="radio" name="gender" value="female">Female
</form>

4. Checkboxes
<input type="checkbox"> defines a checkbox. Checkboxes let a user select
ZERO or MORE options of a limited number of choices.
Example:
<form>
<input type="checkbox" name="vehicle" value="Bike">I have
a bike<br><input type="checkbox" name="vehicle"
value="Car">I have a car
</form>

5. Submit Button
<input type="submit"> defines a submit button. A submit button is used to
send form data to a server. The data is sent to the page specified in the
form's action attribute. The file defined in the action attribute usually does
something with the received input:
Example:
<form name="input" action="test2.html" method="get">
Username: <input type="text" name="user">

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

6. Button
The button INPUT tag gives you a way to create simple input buttons with
custom text. It is similar to the INPUT submit tag but is slightly more
flexible. Example:
<form>
<input type="button" value="this is a text button">
</form>

7. File
The file INPUT tag provides a file upload form box for HTML forms. It allows
you to solicit files from your readers such as images or video.
Syntax
<input accept="file_extension|audio/*|video/*|image/*|media_type">

Tip: To specify more than one value, separate the values with a comma
(e.g. <input accept="audio/*,video/*,image/*" />.

Attribute Values

Value Description

file_extension Specify the file extension(s) (e.g: .gif, .jpg, .png, .doc) the user can
pick from

audio/* The user can pick all sound files

video/* The user can pick all video files

image/* The user can pick all image files

Example:
<form enctype="multipart/form-data">
58
<input type="file" accept="image/*">
</form>

8. Hidden
The hidden INPUT tag allows HTML form developers to store information
for delivery with the form data that is invisible to the form users. The
hidden form fields are used to save state in multi-page forms, collect cookie
data to deliver to the form, and just store data beyond what the customer
fills in.
Example:
<form><input type="hidden" name="date-submitted" value="2010-12-10">
</form>

9. Reset
The reset INPUT tag sets the form back to its initial state when the form
was loaded. In most forms this means that it clears the contents of the
form, but if the form started out with preloaded contents, that is what will
display when the reset button is clicked.
Example:
<form>
<input type="reset">
</form>

10. Dropdown
<select>
The <select> element is used to create a drop-down list. The <option>
tags inside the <select> element define the available options in the list.
<option>
The <option> tag defines an option in a select list. <option> elements go
inside a <select> or <datalist> element.

Example:
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>

59
11. <textarea>
The <textarea> tag defines a multi-line text input control. A text area can
hold an unlimited number of characters, and the text renders in a fixed-
width font (usually Courier). The size of a text area can be specified by
the cols and rows attributes
Attribute Value Description

Autofocus autofocus Specifies that a text area should


automatically get focus when the page loads

Cols Number Specifies the visible width of a text area

Disabled disabled Specifies that a text area should be disabled

Form form_id Specifies one or more forms the text area


belongs to
Maxlength Number Specifies the maximum number of characters
allowed in the text area

Name Text Specifies a name for a text area

Placeholder Text Specifies a short hint that describes the


expected value of a text area

Readonly readonly Specifies that a text area should be read-only

Required required Specifies that a text area is required/must be


filled out
Rows Number Specifies the visible number of lines in a text
area
Wrap hard Specifies how the text in a text area is to be
soft wrapped when submitted in a form

Example:
<textarea rows="4" cols="50">
Welcome to our College. It provides education and placement facilities.
</textarea>

60
 HTML Form Example:
<html>
<head>
<title>FORM</title>
</head>
<body bgcolor="black" text="cyan">
<form action="a.html" name="registraton" method="POST"><!--GET-->
<fieldset>
<legend align="center">Registration Form</legend>
<label>Name:</label>
<input type="text" size="40" placeholder="Enter Your Name here..."
name="nm"/>
<br/>
Password:
<input type="password"name="pw"/>
<br/>

Email :
<input type="Email"name="email"/>
<br/>
Gender:
<input type="radio" name="rbt_gender" value="male"/>Male
<input type="radio" name="rbt_gender" value="female"/>Female
<br/>
Hobby:
<input type="checkbox" name="chk_tv" value="tv"/>TV
<input type="checkbox" name="chk_dance" value="Dance"/>Dance
<input type="checkbox" name="chk_sing" value="sing"/>Singing
<br/>
61
Address:
<textarea cols="20" rows="5" name="address">
</textarea>
<br/>
City:
<select name="dd_city">
<option value="">--select city--</option>
<option value="Rajkot">Rajkot</option>
<option value="surat">Surat</option>
<option value="vapi">Vapi</option>
</select>
<br/>
Upload Photo:
<input type="file"/>
<br/>
Date Of Birth:
<input type="date"/>
<br/>
Time:
<input type="time"/>
<br/>
Number:
<input type="number" max="10" min="1"/>
<br/>
Range:
<input type="range"max="10" min="1"/>
<br/>
color:
<input type="color"/>

62
<br/>
Search:
<input type="search"/>
<br/>
<input type="reset" name="btn_reset" value="reset"/>
<br/>
<br/><input type="button" value="OK"/>
<br/><input type="button" value="done"/>
<input type="submit" name="btn_submit" value="submit form"/>
<br/>
</form>
</body>
</html>

2.18 HTML5
 HTML5 is the latest and most enhanced version of HTML.
 HTML5 is a co-operation between the World Wide Web Consortium
(W3C) and the Web Hypertext Application Technology Working Group
(WHATWG).

2.18.1 New HTML5 Elements(tags):


 New Semantic elements like <header>, <footer>, <article>, <section>
etc.
 New values of input element like number, date, time, email, range.
 New graphic elements: <svg> and <canvas>.
 New multimedia elements: <audio> and <video>.
Note:
 Semantic elements: elements with a meaning.
o <form>, <table>, <header>,<article> - Clearly defines its content.

 Non-semantic elements: <div> - Tells nothing about its content.

2.19 HTML5 Document Structure:


The DOCTYPE declaration for HTML5: <!DOCTYPE html>

63
All HTML documents must start with a <!DOCTYPE> declaration.

The declaration is not an HTML tag. It is an "information" to the browser


about what document type to expect.

In HTML5, the <!DOCTYPE> declaration is simple: <!DOCTYPE html>

The character encoding (charset) declaration: <meta charset="UTF-8">


Example:
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>......</title>
</head>

<body>
<header>......</header>
<nav>......</nav>
<article>
<section> ......</section>
</article>
<aside>......</aside>
<footer>......</footer>
</body>
</html>

2.20 Multimedia Element


Using Embed
The <embed> tag defines a container for external (non-HTML) content. e.g.:
<embed height="50" width="300" src=" Song1.mp3">

Using Object
The <object> tag can also define a container for external (non-HTML) content.
e.g.: <object height="50" width="100" data=" Song1.mp3"></object>

Using Hyperlink
e.g.: <a href="Song1.mp3">Play the sound</a>
64
Audio Controls
 To play an audio file in webpage, use the <audio> element.

 The controls attribute adds audio controls, like play, pause, and volume.

 The <source> element allows you to specify alternative audio files which
the browser may choose from.
 supported audio formats: MP3, WAV, and OGG

Example:

<!DOCTYPE html>
<html>
<body>
<audio controls>
<source
src="E:\songs\poem.mp3"> </audio>
</body>
</html>

Video Controls
 To show a video in HTML, use the <video> element

 The controls attribute adds video controls, like play, pause, and volume.

 Set width and height attributes.

 To start a video automatically use the autoplay attribute


Example:
<!DOCTYPE html>
<html>
<body>
<video width="400" height="500"
autoplay> <source
src="E:\Video\Sunlight.mp4">
</video>
</body>
</html>

65
2.21 List of HTML5 Elements:

Tags (Elements) Description

<article> Represents an independent piece of content of a


document, such as a blog entry or newspaper article

<aside > Represents a piece of content that is only slightly related to


the rest of the page.

<audio> Defines an audio file.

<canvas> This is used for rendering dynamic bitmap graphics on the


fly, such as graphs or games.

<command> Represents a command the user can invoke.

<datalist> Together with the a new list attribute for input can be used
to make comboboxes

<details> Represents additional information or controls which the


user can obtain on demand

<figure> Represents a piece of self-contained flow content, typically


referenced as a single unit from the main flow of the
document.

<footer> Represents a footer for a section and can contain


information about the author, copyright information, et
cetera.

<header> Represents a group of introductory or navigational aids.

<mark> Represents a run of text in one document marked or


highlighted for reference purposes, due to its relevance in
another context.

<nav> Represents a section of the document intended for


navigation.

66
<output> Represents some type of output, such as from a calculation
done through scripting.

<section> Represents a generic document or application section

<time> Represents a date and/or time.

<video> Defines a video file.

2.22 HTML5 Attributes

HTML5 added the following attributes for <input>:

· autocomplete
· autofocus
· form
· formaction
· formmethod
· formnovalidate
· formtarget
· height and width
· list
· min and max
· multiple
· pattern (regexp)
· placeholder
· required
· step

the following attributes for <form>:

· autocomplete
· novalidate
1. autocomplete attribute
· A form or input field should have autocomplete on or off.

· When autocomplete is on, the browser automatically completes


the input values based on values that the user has entered before.
· It is possible to have autocomplete "on" for the form, and "off" for
specific input fields, or vice versa.
67
Example:
<form autocomplete="on">
First name: <input type="text" name="fname"><br>

Last name: <input type="text" name="lname"><br>


E-mail: <input type="email" name="email" autocomplete="off">
<br> <input type="submit">
</form>

2. novalidate attribute
· The form data should not be validated when it submitted.
· User can enter any value.
Example:
<form novalidate>

URL: <input type="url" name=”usr_url”><br> E-


mail: <input type="email" name="user_email">
<input type="submit">
</form>

3. autofocus attribute

The input field should automatically get focused (selected for input)
when the page loads.
Example:
<form>

First name:<input type="text" name="fname"


autofocus><br> Last name: <input type="text"
name="lname"><br> <input type="submit">

68
</form>

4. form attribute id
It allows user to reference a specific form by its ID on any orphaned field.

Example:
<body>
<form id="reg_form">

First name: <input type="text"


name="fname"><br> <input type="submit"
value="Submit">
</form>

<p>The "Last name" field is outside the form, but still part of
the form.</p>

Last name: <input type="text" name="lname" form="reg_form">


</body>

5. formaction attribute
· It specifies where to send the form-data when a form is
submitted.
· The formaction attribute overrides the action attribute of the
<form>.
· It is used with type="submit" and type="image".

69
Example:
<form action="Form1.html">
First name: <input type="text" name="fname"><br>

Last name : <input type="text" name="lname"><br>


<input type="submit" value="Submit--open
Form1"><br> <input type="submit"
formaction="Form2.html" value="Submit--open
Form2">
</form>

6. formmethod attribute
It overrides a form's method (get or post) with the specified method.
Example:
<form action="/action_page.php" method="get">
First name: <input type="text" name="fname" ><br>
Last name : <input type="text" name="lname"><br>
<input type="submit" value="Submit using GET">
<input type="submit" formmethod="post" value="Submit using
POST"> </form>

7. formtarget attribute

· It specifies that where to display the response after


submitting the form.
· It overrides the target attribute of the <form> element.
70
Example:
<form action="page1.php">

First name: <input type="text" name="fname"><br>

Last name: <input type="text" name="lname"><br>

<input type="submit" value="Submit as normal">

<input type="submit" formtarget="_blank" value="Submit to a new tab">

</form>

8. formnovalidate attribute
Removes all validation of the <form>.
Example:
<form>
E-mail: <input type="email" name="userid"><br>

<input type="submit" value="Submit with validation"><br>

<input type="submit" formnovalidate value="Submit without validation">

</form>

9. height and width attributes

The height and width attributes are used with <input type=”image”>
Example:
<form action="/action_page.php">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>

71
<input type="image" src="arrow.png" alt="Submit" width="48"
height="48">
</form>

10.list attribute

The list attribute refers to a <datalist>. When page loads it looks like a
textbox.
After selecting, it will display a listbox.

Example:
<form>
<input list="browsers" name="browser">
<datalist id="browsers">
<option value="Internet Explorer" >
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
</form>

72
11. min and max attributes
· It specify the minimum and maximum values for an <input>
element.
· It works with the following input types:
number, range, date, datetime-local, month, time and week.
Example:

<form>
Enter a date after 1980-01-15:
<input type="date" name="bday" min="1980-01-15"><br>
Enter a month before january, 2015:

<input type="month" name="bday" max="2015-01"><br>


Quantity (between 1 and 20):
<input type=”number” name=”num” min=”1” max=”20”><br>
<input type="submit">
</form>

12.multiple attribute
· It allows user to enter more than one value in the <input>
element.
· It works with the following input types: email, and file.
Example:
<form>

Select images: <input type="file" name="img" multiple>


</form>

73
13.pattern attribute

· It works with the following input


types: text, search, url, tel, email,
and password.

· It allows us to define our own rule to validate the input value using
Regular Expressions (RegEx). Again, if the value does not match the
specified pattern, the input will throw an error.

Example:
<form>
Country code:
<input type="text" pattern="[A-Za-z]{3}" title="Three letter country code">
<input type=”password” pattern=”.{8}” title=”min 8 character password”>
<input type="submit">
</form>

14. placeholder attribute

It displays a hint that describes the expected value of an input field. (e.g.,
you click on the field, and you begin to type, the text simply disappears.)
Example:
<form>
<input type="text" name="fname" value="First name"><br>
<input type="password" name="pwd" placeholder="Password">
<input type="submit">
</form>

74
15. required attribute

The input field must be filled out before submitting the form.
Example:
<form>

Username: <input type="text" name="usrname" required>


<input type="submit">
</form>

16.step attribute

· It specifies the legal number intervals for an <input> element.


· It works with the following input types:
number, range, date, datetime-local, month, time and week.

Example: if step="5", legal numbers could be -5, 0, 5, 10, etc.


<form >

<input type="number" name="points" step="5">


<input type="month" name="mnth" step="3">
<input type="submit">
</form>

75
2.22.1 Web Form (HTML5 Input Types):

HTML5 added several new input types:

· color
· date
· time
· datetime-local
· week
· month
· number
· range
· email
· search
· tel
· url

1. Input Type Color

< input type="color"> allows user to select a


color. Example:

<form action="action.php">
Select your favourite colour:
<input type="color" name="favcolor" value="#ff0000">
<input type="submit">
</form>

76
2. Input Type Date

<input type = "date"> allows user to enter a date.

Example:

<form>
Birthdate:
<input type="date" name="bday">
<input type=”submit”>
</form>

3. Input Type Time

The <input type="time"> allows the user to select a time (no time zone).

Example:
<form>
Select a time:

77
<input type="time" name="usr_time" value="12:05”>
</form>

4. Input Type Datetime-local

The <input type="datetime-local"> allows user to enter date and time.

Based on browser supporting AM and PM will be displayed.

Example:

<form>
Birthday (date and time):

<input type="datetime-local" name="bdaytime">


<input type="submit" value="Send">
</form>

5. Input Type Week

<input type="week"> allows the user to select a week and year.

Example:
<form>
Select a week:

<input type="week" name="year_week">


</form>

78
6. Input Type Month

<input type="month"> allows the user to select a month and year.

Example:

<form>
Joining (month and year):

<input type="month"
name="jmonth"> </form>

7. Input Type Number

<input type="number"> defines a numeric input field.

Example:

<form>
Enter number:
<input type="number" name="num" ><br>
Between 1 to 100 :

<input type="number" name="quantity" min="1" max="100"><br>


<input type=”submit”>
</form>

79
8. Input Type Range

<input type="range"> allows user to enter a number using a slider control.


Default range is 0 to 100.

Example:

<form method="get">

Points:

<input type="range" name="points" min=”-30”


max=”30”> <input type="submit">

</form>

Output:

9. Input Type Email

<input type="email"> allows user to enter Email address.

It can be automatically validated when submitted.

Example:

<form>
E-mail : <input type="email" name="email">
<input type="submit">

80
</form>

10.Input Type Search

<input type="search"> is used for search fields (a search field behaves like a
regular text field).

<form>

Google Search : <input type="search">

</form>

11.Input Type Url

The <input type="url> allows user to enter a URL address.

Example:

<form>

Add your homepage:

<input type="url" name="homepage">

</form>

81
2.23 Cascading Style Sheet
 CSS stands for Cascading Style Sheets. It is a style sheet language which is
used to describe the look and formatting of a document written in markup
language. It provides an additional feature to HTML.
 It is generally used with HTML to change the style of web pages and user
interfaces. It can also be used with any kind of XML documents including
plain XML, SVG and XUL.
 CSS is used along with HTML and JavaScript in most websites to create user
interfaces for web applications and user interfaces for many mobile
applications.

2.24 What does CSS do ?


o You can add new looks to your old HTML documents.
o You can completely change the look of your website with only a few
changes in CSS code.

2.25 Why use CSS ?


These are the three major benefits of CSS:
1) Solves a big problem
Before CSS, tags like font, color, background style, element alignments, border
and size had to be repeated on every web page. This was a very long process. For
example: If you are developing a large website where fonts and color information
are added on every single page, it will be become a long and expensive process.
CSS was created to solve this problem.
2) Saves a lot of time
CSS style definitions are saved in external CSS files so it is possible to change
the entire website by changing just one file.
3) Provide more attributes
CSS provides more detailed attributes than plain HTML to define the look and feel of
the website.

2.26 CSS Comment


 Comments are used to explain your code, and may help you when you edit the
source code at a later date.

82
 Comments are ignored by browsers.
 It begins with a / (forward slash) and than an * (asterisks) then the comment,
then the closing tag will * (asterisks) then the / (forward slash).
 Example:
/*This Comment line*/
2.27 CSS Syntax
A CSS rule set contains a selector and a declaration block.

Selector: Selector indicates the HTML element you want to style. It could be any tag
like <h1>,<title> etc.

Declaration Block: The declaration block can contain one or more


declarations separated by a semicolon. For the above example, there are
two declarations:
1. color: yellow;

2. font-size: 11 px;

Each declaration contains a property name and value, separated by a colon.

Property: A Property is a type of attribute of HTML element. It could be color,


border etc.

Value: Values are assigned to CSS properties. In the above example, value
"yellow" is assigned to color property.

Selector{Property1: value1; Property2: value2;}

83
2.28 Types of CSS
There are three Types of CSS.
1. Inline CSS

2. Internal CSS

3. External CSS

1) Inline CSS
We can apply CSS in a single element by inline CSS technique.
The inline CSS is also a method to insert style sheets in HTML document. This
method mitigates some advantages of style sheets so it is advised to use this
method sparingly.
If you want to use inline CSS, you should use the style attribute to the relevant tag.
Example:
<p style="color:blue">Hello CSS</p>

2) Internal CSS
Internal CSS is used to apply CSS on a single document or page. It can affect all
the elements of the page. It is written inside the style tag within head section of
html.

Example:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: linen;
}
h1 {
color: red;
margin-left: 80px;
}
</style>
</head>

84
<body>
<h1>The internal style sheet is applied on this heading.</h1>
<p>This paragraph will not be affected.</p>
</body>
</html>

3) External CSS
The external style sheet is generally used when you want to make changes on
multiple pages. It is ideal for this condition because it facilitates you to change
the look of the entire web site by changing just one file.
It uses the <link> tag on every pages and the <link> tag should be put inside the head
section.
Example:
Index.html
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
<h1> Welcome </h1>
</body>

The external style sheet may be written in any text editor but must be saved
with a .css extension. This file should not contain HTML elements.
Let's take an example of a style sheet file named "mystyle.css".

File: mystyle.css
body {
background-color: lightblue;
}
h1 {
color: navy;
margin-left: 20px;
}

85
2.29 CSS Selector
CSS selectors are used to select the content you want to style. Selectors are
the part of CSS rule set. CSS selectors select HTML elements according to its id,
class, type, attribute etc.
There are several different types of selectors in CSS.
1. CSS Element Selector

2. CSS Id Selector

3. CSS Class Selector

4. Universal Selector

1) CSS Element Selector


The element selector selects the HTML element by name.
<!DOCTYPE html>
<html>
<head>
<style>
p{
text-align: center;
color: blue;
}
</style>
</head>
<body>
<p>This style will be applied on every paragraph.</p>
<p id="para1">Me too!</p>
<p>And me!</p>
</body>
</html>

2) CSS Id Selector

86
 The id selector selects the id attribute of an HTML element to select a
specific element. An id is always unique within the page so it is chosen
to select a single, unique element.
 It is written with the hash character (#), followed by the id of the element.
 Let’s take an example with the id "para1".
o Each element can have only one ID
o Each page can have only one element with that ID

<html>
<head>
<style>
#para1 {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<p id="para1">Hello</p>
<p>This paragraph will not be affected.</p>
</body>
</html>

3)CSS Class Selector


The class selector selects HTML elements with a specific class attribute. It is
used with a period character. (full stop symbol) followed by the class name.
Let's take an example with a class "center".

 You can use the same class on multiple elements.


 You can use multiple classes on the same element.

<!DOCTYPE html>
<html>
<head>

87
<style>
.center {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<h1 class="center">This heading is blue and center-aligned.</h1>
<p class="center">This paragraph is blue and center-aligned.</p>
</body>
</html>

 CSS Class Selector for specific element


If you want to specify that only one specific HTML element should be affected
then you should use the element name with class selector.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
p.center {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<h1 class="center">This heading is not affected</h1>
<p class="center">This paragraph is blue and center-aligned.</p>
</body>
</html>

4) CSS University Selector


The universal selector (*) selects all HTML elements on the page.

88
Example:
<html>
<head>
<style>
*{
text-align: center;
color: blue;
}
</style>
</head>
<body>
<h1>Hello world!</h1>
<p>Every element on the page will be affected by the style.</p>
<p id="para1">Me too!</p>
<p>And me!</p>
</body>
</html>

Difference between id and class attribute:


The only difference between them is that “id” is unique in a page and can only apply to
at most one element, while “class” selector can apply to multiple elements.

2.30 CSS Font


CSS Font property is used to control the look of texts. By the use of CSS font
property you can change the text size, color, style and more. You have
already studied how to make text bold or underlined. Here, you will also
know how to resize your font using percentage.

These are some important font attributes:


1. CSS Font color: This property is used to change the color of the text.
(standalone attribute)
2. CSS Font family: This property is used to change the face of the font.

3. CSS Font size: This property is used to increase or decrease the size of the font.

4. CSS Font style: This property is used to make the font bold, italic or oblique.

89
5. CSS Font variant: This property creates a small-caps effect.

6. CSS Font weight: This property is used to increase or decrease the


boldness and lightness of the font.

1) CSS Font Color


CSS font color is a standalone attribute in CSS although it seems that it is a
part of CSS fonts. It is used to change the color of the text.
There are three different formats to define a color:
o By a color name
o By hexadecimal value
o By RGB

SYNTAX color: <value1>


Possible value
 any color name
 any hexadecimal color value
 any RGB color value

Apply to All text base elements

In the above example, we have defined all these formats.


<!DOCTYPE html>
<html>
<head>
<style>
body {
font-size: 100%;
}
h1 { color: red; }
h2 { color: #9000A1; }
p { color:rgb(0, 220, 98); }
}
</style>

90
</head>
<body>
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<p>This is a paragraph.</p>
</body>
</html>

2) CSS Font Family


CSS font family can be divided in two types:
o Generic family: It includes Serif, Sans-serif, and Monospace.
o Font family: It specifies the font family name like Arial, Times New
Roman etc.
• Serif: Serif fonts include small lines at the end of characters. Example of
serif: Times new roman, Georgia etc.
• Sans-serif: A sans-serif font doesn't include the small lines at the end of
characters.
Example of Sans- serif: Arial, Verdana etc.

SYNTAX Font-family: <family-name>, <generic-family>

Example P {font-family: times new roman, Arial, serif;}

Apply To All text base element

<!DOCTYPE html>
<html>

91
<head>
<style>
body {
font-size: 100%;
}
h1 { font-family: sans-serif; }
h2 { font-family: serif; }
p { font-family: monospace; }
}
</style>
</head>
<body>
<h1>This heading is shown in sans-serif.</h1>
<h2>This heading is shown in serif.</h2>
<p>This paragraph is written in monospace.</p>
</body>
</html>

3) CSS Font Size


CSS font size property is used to change the size of the font. These are the possible values
that can be used to set the font size:

Font Size Value Description

xx-small use to display the extremely small text size.

x-small use to display the extra small text size.

Small use to display small text size.

Medium use to display medium text size.

Large use to display large text size.

x-large use to display extra large text size.

xx-large use to display extremely large text size.

92
Smaller use to display comparatively smaller text size.

Larger use to display comparatively larger text size.

size in pixels or % use to set value in percentage or in pixels.

SYNTAX Font-size:<value>

Apply to All text base elements


P {font-size: x-large}
Example
h1 { font-size: 40px;}

Example:
<html>
<head>
<title>Practice CSS font-size property</title>
</head>
<body>
<p style="font-size:xx-small;"> This font size is extremely small.</p>
<p style="font-size:x-small;"> This font size is extra small</p>
<p style="font-size:small;"> This font size is small</p>
<p style="font-size:medium;"> This font size is medium. </p>
<p style="font-size:large;"> This font size is large. </p>
<p style="font-size:x-large;"> This font size is extra large. </p>
<p style="font-size:xx-large;"> This font size is extremely large. </p>
<p style="font-size:smaller;"> This font size is smaller. </p>
<p style="font-size:larger;"> This font size is larger. </p>
<p style="font-size:200%;"> This font size is set on 200%. </p>
<p style="font-size:20px;"> This font size is 20 pixels. </p>
</body>
</html>

CSS Font Style


CSS Font style property defines what type of font you want to display. It may
be italic, oblique, or normal.

93
SYNTAX Font-style:<value>

Possible value  Normal


 italic
 oblique
default Value Normal
Apply to All elements
Example P {font-style: italic}

<!DOCTYPE html>
<html>
<head>
<style>
body {
font-size: 100%;
}
h2 { font-style: italic; }
h3 { font-style: oblique; }
h4 { font-style: normal; }
</style>
</head>
<body>
<h2>This heading is shown in italic font.</h2>
<h3>This heading is shown in oblique font.</h3>
<h4>This heading is shown in normal font.</h4>
</body>
</html>

4) CSS Font Variant


CSS font variant property specifies how to set font variant of an element. It
may be normal and small-caps.

SYNTAX Font-variant:<value>
Possible value  Normal

94
 small-caps

default Value Normal


Apply to All text base elements
Example P {font-variant: small-caps}

<!DOCTYPE html>
<html>
<head>
<style>
p { font-variant: small-caps; }
h3 { font-variant: normal; }
</style>
</head>
<body>
<h3>This heading is shown in normal font.</h3>
<p>This paragraph is shown in small font.</p>
</body>
</html>

5) CSS Font Weight


CSS font weight property defines the weight of the font and specifies that how bold a
font is. The possible values of font weight may be normal, bold, bolder, lighter or
number(100, 200...up to 900).

Syntax Font-weight:<value>

95
 Normal
Possible value
 bold
 bolder
 lighter
 100
 200
 300
 400
 500
 600
 700
 800
 900
default Value Normal
Apply to All text base elements

Example P {font-weight: 900}

<!DOCTYPE html>
<html>
<body>
<p style="font-weight:bold;">This font is bold.</p>
<p style="font-weight:bolder;">This font isbolder.</p>
<p style="font-weight:lighter;">This font is lighter.</p>
<p style="font-weight:100;">This font is 100 weight.</p>
<p style="font-weight:200;">This font is 200 weight.</p>
<p style="font-weight:300;">This font is 300 weight.</p>
<p style="font-weight:400;">This font is 400 weight.</p>
<p style="font-weight:500;">This font is 500 weight.</p>
<p style="font-weight:600;">This font is 600 weight.</p>
<p style="font-weight:700;">This font is 700 weight.</p>
<p style="font-weight:800;">This font is 800 weight.</p>
<p style="font-weight:900;">This font is 900 weight.</p>
</body>
</html>

96
6) Font:

The CSS font property is a shorthand property for setting font-family, font-
size, font- variant, font-style and font-weight. This saves time and space.

SYNTAX Font: <value1> <value2> …


Possible value  font-family
 font-size
 font-variant
 font-style
 font-weight
default Value None

Apply to All elements


Example P {font:italic small-caps bold 15px georgia;}

EXAMPLE:
<html>

<head>
<style>
P{
font-family:arial;

font-size:30px;
font-weight:300
}
h1 {font: italic 800}

2.31 CSS Text Properties

1. Color
The color property is used to set the color of the text. The color can be specified by:
Name - a color name, like "red"

97
RGB - an RGB value, like "rgb(255,0,0)" Hex - a hex value, like "#ff0000“
Example:
<p style="color:#00ff00;">text color property</p>

SYNTAX color: <value>;


Possible value  Color can be red, blue, green, etc.
 RGB value

Initial Value None


Apply to All text base elements
body{color:blue;} h1 {color: #00ff00;}
Example
h2 {color: rgb(255,0,0);}

2. Text-align
The text-align property is used to set the horizontal alignment of a text.
Example
<h1 style=”text-align:right”>text align property</h1>

SYANTAX text-align: <value>;


 Left
Possible value
 Right
 Center
 Justify
Default Value Normal
Apply to All elements

Example Td { text-align: right }

98
3. Text-transform
The text-transform property is used to specify uppercase and lowercase letters in a
text.
Example:
<h1 style=”text-transform:capitalize”>
text transform property
</h1>
SYANTAX text-transform: <value>;
Possible  None
Value  Capitalize- first character of each word is capital
 Uppercase
 Lowercase
Default Value None

Apply to All text base elements


Example p {text-transform: uppercase; }

4. Text-decoration
The text-decoration property is used to set or remove decorations from text.
Example
<h1 style=“text-decoration: underline”> text- decoration property
</h1>

SYANTAX text-decoration: <value>;


 None
Possible value
 Underline
 Overline
 Line-through

Default Value None


Apply to All text base elements
Example p {text-decoration: line-through; }

5. Text-indent
It is used for indenting the first line of text.
99
Example
<p style=“text-indent: 50px”>text indent property</p>

SYANTAX Text-indent: <value>;


 <length>
Possible value
 <percentage>
0
Default Value
All elements
Apply to
Td { text-indent: 10%; }
Example

6. Word-spacing
It is used to specify the space between each word.
Example
<h1 style=“word-spacing:10px”>Word Spacing property</h1>

SYANTAX word-spacing: <unit>;

Possible value  Normal


 <length>- eg: 10px
Default Value Normal
Apply to All elements
Example P{ word-spacing: 50;}

7. letter-spacing
It is used to specify the space between each letters of the words.
Example
<p style=“letter-spacing:10px”>letter Spacing property</p>

SYNTAX Letter-spacing: <unit>;


 Normal
Possible value
 <length>- eg: 10px
Default Value Normal

100
Apply to All elements
Example P{ letter-spacing: 50px;}

8.Line-height
It sets the distance between the line.
Example
<h1 style=“Line-height:10px”>line-height property</h1>

SYNTAX Line-height: <unit>;


 Normal
Possible value
 <length>- eg: 10px
 <number>
 <percentage>- eg: 120%
Default Value Normal
Apply to All elements
Example P{ line height: 180%;}

2.32 CSS Background Properties

1.Background-color:
You can specifically declare a color for the background of any
element. The background color can be specified by:
name - a color name, like "red"
RGB - an RGB value, like "rgb(255,0,0)"
Hex - a hex value, like "#ff0000“

Example
<body style=“background-color:#e0ffff”>

101
SYNTAX Background-color: <value>
Color can be red, blue, green, etc.
Possible value
RGB value
Initial Value None
Apply to All elements

Example body {background-color: red}

1. Background-image
The background-image property specifies an image to use as the background
of an element. By default, the image is repeated so it covers the entire
element.
Example
Body{background-image:url(‘Sunset.jpg’)}

SYNTAX Background-image: <value>


Possible value  url(file path)

Initial Value  None

Apply to All elements


Example body {background-image: url(“images/1.jpg ”)}

2. Background-repeat
You can set if an image set as a background of an element is to repeat
(across=x and/or down=y) the screen.

SYNTAX Background-repeat: <value>


Possible value  Repeat (background repeats horizontally and
vertically)
 Repeat-x (background repeats horizontally)
 Repeat-y (background repeats vertically)
 No-repeat (background is not repeated)
Initial Value Repeat

102
Apply to All elements

Example body { background-image: url(“ /images/1.jpg ”);


background-repeat: no-repeat}

3. Background-attachment
You can set whether the background scrolls with the page or is fixed when
the user scrolls down the page.

SYNTAX Background-attachment: <value>


Possible value  Scroll
 Fixed
Initial Value Scroll
Apply to All elements

Example body { background-image: url(“images/1.jpg”);


background-attachment: fixed}

4. Background-position
You can position an image used for the background of an element

SYNTAX Background-position: <value>


 xpos ypos(x & y co-ordinates values in
Possible value
pixels)(Note: If you only specify one value, the
other value will be 50px.)
 x% & y% (x & y co-ordinates values in
percentage)(Note: If you only specify one value, the
other value will be 50%.)
 left top
left center
left bottom
right top
right center
right bottom
center top

103
center center
center bottom (Note:If you only specify one
keyword, the other value will be "center")

Initial Value None


Apply to All elements
body { background-image: url(“images/1.jpg”) ;
Example
background-position: 100px;}

5. CSS background
The property is shorthand and used to specify Background-
attachment,Background-repeat, Background-color, Background-
image, Background-position values.

SYNTAX Background: <value1> <value2>…

Possible value  <Background-attachment>


 <Background-repeat>
 <Background-color>
 <Background-image>
 <background-position>
Initial Value For all described above
Apply to All elements

Example body{background: url(“ /images/1.jpg ”) fixed red no- repeat


right top}

2.33 CSS List Properties


The CSS list properties allow you to place the list item marker, change
between different list item markers, or set an image as the list item marker.

In HTML, there are two types of lists:


 unordered list - the list items are marked with bullets (typically circles or
squares)

 ordered list - the list items are marked with numbers or letters
104
1. List-style-image
It is used to specify an image for list item bullets.
You can create your own bullets to use within your lists.

SYNTAX list-style-image: <value>;

Possible value url(picture_file_path)


default Value None
Apply to List item elements(<ol> / <ul> / <li>)
Example <ul> { list-style-image: url(a.jpg)}

2. List-style-position
The list-style-position property specifies the indentation of a list. "outside" is the
default value. The "inside" value further indents the list.

SYNTAX list-style-position: <value>;


 Inside- the bullet appears inside the principle block box
Possible value
of the list
 Outside-- the bullet appears outside the principle block
box of the list
default Value Outside
Apply to List item elements(<ol> / <ul> / <li>)
Example <ul> { list-style-position: inside;}

3. List-style-type
• The list-style-type specifies the type of list-item marker in a list of
ordered and unordered lists.
• There are a lot of choices for values:
circle, disc, lower-greek, lower-alpha, upper-latin etc...

105
SYNTAX list-style-type: <value>;
 Disc
Possible value
 Circle
 Square
 decimal
 decimal leading zero
 lower-roman
 upper-roman
 lower-greek
 lower-alpha
 lower-latin
 upper-alpha
 upper-latin
 none
default Value Disc
Apply to List item elements(<ol> / <ul> / <li>)
Example <ul> { list-style-type: square;}

4. List-style
• The CSS list-style property is shorthand for specifying styles for list items.
Possible values list-style-type, list-style-position, list-style-image.
• Specify all the list properties in one declaration.

SYNTAX list-style: <value1> <value2>…;


Possible value  < list-style-type >
 < list-style-position >
 < list-style-image >
default Value None
Apply to List item elements(<ol> / <ul> / <li>)
Example <ul> { list-style: lower-roman inside;}

106
2.34 CSS Margin Properties
The margin clears an area around an element (outside the border).
The margin does not have a background color, and is completely transparent.
The top, right, bottom, and left margin can be changed independently
using separate properties.
Margin individual sides
 Margin-top:10px;
 Margin-right:15px;
 Margin-bottom:15px;
 Margin-left:10px

SYNTAX Margin-top: <value>;


Margin-right: <value>;
Margin-bottom: <value>;
Margin-left: <value>;
Possible value  Number
 Percentage(%)
default Value None
Apply to All elements
Example P{margin-top: 100px;}
P{margin-right: 100px;}
P{margin-bottom: 100px;}
P{margin-left: 100px;}

CSS margin property:


 To shorten the code, it is possible to specify all the margin properties in
one property.
 The margin property is a shorthand property for the following
individual margin properties.
 You can also declare all the margins of an element in a single property
as follows:

SYNTAX Margin: <value1> <value2> <value3>….;

107
 Number
Possible value
 Percentage(%)
 Auto
default Value None
Apply to All elements
Example H1{margin: 10px 10px 10px 10px;}

 If the margin property has four values:


The order of below values is top, right, bottom, left
 margin: 25px 50px 75px 100px;
o top margin is 25px
o right margin is 50px
o bottom margin is 75px

o left margin is 100px

 If the margin property has three values:


 margin: 25px 50px 75px;
o top margin is 25px
o right and left margins are 50px
o bottom margin is 75px

 If the margin property has two values:


 margin: 25px 50px;
o top and bottom margins are 25px
o right and left margins are 50px

 If the margin property has one value:


 margin: 25px;
o all four margins are 25px

108
2.35 CSS Padding Properties
 The CSS Padding property is used to define the space
between the element content and the element border.
 The CSS padding properties are used to generate space around
content.
 The padding clears an area around the content (inside the border)
of an element.
 CSS has properties for specifying the padding for each side of an
element

 Top, bottom, left and right padding can be changed


independently using separate properties. You can also change
all properties at once by using shorthand padding property.

Padding individual sides


 Padding -top:10px;
 Padding -right:15px;
 Padding -bottom:15px;
 Padding-left:10px

SYNTAX padding-right: <value>;


Possible value  Number
 Percentage(%)
default Value None
Apply to All elements
Example <p style=”padding-top: 60”> this is paragraph </p>
<p style=”padding-right: 60”> this is paragraph </p>
<p style=”padding-bottom: 60”> this is paragraph
</p>
<p style=”padding-left: 60”> this is paragraph </p>

 CSS padding shorten property:


To shorten the code, it is possible to specify all the padding properties in one
property.
109
The padding property is a shorthand property for the following individual
padding properties:
o padding-top
o padding-right
o padding-bottom
o padding-left

SYNTAX padding: <value1> <value2> <value3>….;


 Number
Possible value
 Percentage(%)
default Value None
Apply to All elements
Example P{padding: 100px 100px 100px 100px;}

So, here is how it works:


 If the padding property has four values:
 padding: 25px 50px 75px 100px;
o top padding is 25px
o right padding is 50px
o bottom padding is 75px
left padding is 100px
o
 If the padding property has three values:
 padding: 25px 50px 75px;
o top padding is 25px
o right and left padding are 50px
bottom padding is 75px
o
 If the padding property has two values:
 padding: 25px 50px;
o top and bottom padding are 25px
o right and left padding are 50px

 If the padding property has one value:


 padding: 25px;

110
o all four padding are 25px

2.36 CSS border-style propterty:


o The border-style property specifies what kind of border to
display.
o The border-style property can have from one to
four values (for the top border, right border,
bottom border, and the left border)

SYNTAX Border-style: <top/all-sides> , <right> , <bottom> ,


<left>
 None
Possible value
 Dotted
 Dashed
 Solid
 Double
 Groove
 Ridge
 Inset
 Outset
 Hidden
default Value None
Apply to All elements
Example P{border-style: dotted dashed solid double}

 If the border-style property has four values:


 border-style: dotted solid double dashed;
o top border is dotted
o right border is solid
o bottom border is double
o left border is dashed

 If the border-style property has three values:

111
 border-style: dotted solid double;
o top border is dotted
o right and left borders are solid
o bottom border is double

 If the border-style property has two values:


 border-style: dotted solid;
o top and bottom borders are dotted

o right and left borders are solid

 If the border-style property has one value:


 border-style: dotted;
o all four borders are dotted

Border - Individual Sides


 From the examples above you have seen that it is possible to specify a
different border for each side.
 In CSS, there is also properties for specifying each of the borders (top,
right, bottom, and left):

<style>
p{
border-top-style: dotted;
border-right-style: solid;
border-bottom-style: dotted;
border-left-style: solid;
}
</style>

Note: None of the OTHER CSS border properties described below will have
ANY effect unless the border-style property is set!

 CSS border-top color propterty:


T
o border-top color property allows you to set the color ofa top
border

112
SYNTAX Border-top: <value>
 Color codes
Possible value
 Rgb
default Value None
Apply to All elements
Example P{border-top: red}

 CSS border-right color propterty:


o The border-right color property allows you to set the color of
a right border

SYNTAX Border-right: <value>


Possible value  Color codes
 Rgb
default Value None
Apply to All elements
Example P{border-right: red}

 CSS border-bottom color propterty:


o The border-bottom color property allows you to set the color
of a bottom border
SYNTAX Border-bottom: <value>

Possible value  Color codes


 Rgb
default Value None
Apply to All elements
Example P{border-bottom: red}

 CSS border-left color propterty:


o The border-left color property allows you to set the color of a
left border.

SYNTAX Border-left: <value>

113
Possible value  Color codes
 Rgb
default Value None
Apply to All elements
Example P{border-left: red}

 CSS border-color propterty:


o The border-color property allows you to set the border color
of a box

o The "border-color" property does not work if it is usedalone.


Use the "border-style" property to set the borders first.

SYNTAX Border-color: <value>


Possible value  Color codes
 Rgb
default Value None
Apply to All elements
Example P{border-color: red}

 CSS border property:


To shorten the code, it is also possible to specify all the individual border
properties in one property.
The border property is a shorthand property for the following individual
border properties.
 border-width
 border-style (required)
 border-color

Example:
<style>
p { border: 5px solid red; }
</style>
114
CSS Border-width property

 The border-width property specifies the width of the four borders. The
width can be set as a specific size (in px,pt,cm etc.)
 The width can be set as a specific size (in px, pt, cm, etc) or by usingone
of the three pre-defined values: thin, medium, or thick.
 The border-width property can have from one to four values (top
border, right border, bottom border, left border)

SYNTAX Border-width: <value>;


 Number
Possible value
 Percentage

default Value None


Apply to All elements
Example P{border-width: 10px;}

Example:

<style>
p {border-style: dotted; border-width: 10px;}
</style>

2.37 HTML <DIV> Tag :


 The <div> tag defines a division or a section in an HTML document.
 The <div> tag is used as a container for HTML elements - which is then
styled with CSS or manipulated with JavaScript.
 The <div> tag is easily styled by using the class or id attribute.
 Any sort of content can be put inside the <div> tag!
Example:
<html>
<head>
<style>
.myDiv {
115
border: 5px outset red;
background-color: lightblue;
text-align: center;
}
</style>
</head>
<body>

<h1>The div element</h1>

<div class="myDiv">
<h2>This is a heading in a div element</h2>
<p>This is some text in a div element.</p>
</div>

<p>This is some text outside the div element.</p>

</body>
</html>

2.38 Navigation Bars


 Having easy-to-use navigation is important for any web site.
 With CSS you can transform boring HTML menus into good-looking
navigation bars.
Navigation Bar = List of Links
 A navigation bar needs standard HTML as a base.
 In our examples we will build the navigation bar from a standard HTML
list.
 A navigation bar is basically a list of links, so using the <ul> and <li>
elements makes perfect sense:
Example:
<html>
<head>
116
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
}
</style>
</head>
<body>

<p>In this example, we remove the bullets from the list, and its default
padding and margin.</p>

<ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>

</body>
</html>

Vertical Navigation Bar


To build a vertical navigation bar, you can style the <a> elements inside the list,
in addition to the code from the previous page:

<html>
<head>
<style>
ul {
117
list-style-type: none;
margin: 0;
padding: 0;
width: 200px;
background-color: #f1f1f1;
}

li a {
display: block;
color: #000;
padding: 8px 16px;
text-decoration: none;
}

/* Change the link color on hover */


li a:hover {
background-color: #555;
color: white;
}
</style>
</head>
<body>

<h2>Vertical Navigation Bar</h2>

<ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>

118
<li><a href="#about">About</a></li>
</ul>

</body>
</html>

Horizontal Navigation Bar


 There are two ways to create a horizontal navigation bar.
 Using inline or floating list items.
Inline List Items

One way to build a horizontal navigation bar is to specify the <li> elements as
inline, in addition to the "standard" code from the previous page:

Example:
<html>
<head>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
}

li {
float: left;
}

li a {
display: block;
padding: 8px;
119
background-color: #dddddd;
}
</style>
</head>
<body>

<ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>

</body>
</html>

2.39 Bootstrap
 Bootstrap is a free front-end framework for faster and easier web
development
 Bootstrap includes HTML and CSS based design templates for typography,
forms, buttons, tables, navigation, modals, image carousels and many
other, as well as optional JavaScript plugins.
 Bootstrap also gives you the ability to easily create responsive
designs.
Steps
1. Add the HTML5 doctype
<!DOCTYPE html>
2. Bootstrap 3 is mobile-first
<meta name="viewport" content="width=device-width, initial-scale=1">
3. Containers
 The .container class provides a responsive fixed width container
 The .container-fluid class provides a full width container, spanning the
entire width of the viewport.

Linking file
120
<linkrel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7
/css/bootstrap.min.css">

<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>

<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>

2.40 Grid System


Bootstrap's grid system allows up to 12 columns across the page.

Grid Classes
The Bootstrap grid system has four classes:

 xs (for phones - screens less than 768px wide)


 sm (for tablets - screens equal to or greater than 768px wide)
 md (for small laptops - screens equal to or greater than 992px wide)
 lg (for laptops and desktops - screens equal to or greater than 1200px
wide)
Ex.
<div class="container">
<div class="row">
<div class="col-sm-4" >.col-sm-4</div>
<div class="col-xs-4" >.col-xs-4</div>
<div class="col-md-4" >.col-md-4</div>
<div class="col-lg-4" >.col-lg-4</div>
</div>
</div>

2.41 Text classes


Bootstrap also has some textual classes that can be used to provide meaning
through colors.
classes for text colours are:
text-muted, text-primary, text-success, text-info, text-warning, text-danger.

121
Ex. <p class="text-muted">This text is muted.</p>

2.42 Table classes


A basic Bootstrap table has a light padding and only horizontal
dividers.The table class adds basic styling to a table:
Classes : .table-striped, .table-bordered, .table-hover, .table-condensed, .table-
responsive.
Ex. <table class="table table-hover">
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>

2.43 Image Shapes classes


The img-rounded class adds rounded corners to an image
The img-circle class shapes the image to a circle
The img-thumbnail class shapes the image to a thumbnail:
Ex: <img src="cinqueterre.jpg" class="img-thumbnail" alt="”>

2.44 Jumbotron
A jumbotron indicates a big box for calling extra attention to some special
content or information.
A jumbotron is displayed as a grey box with rounded corners. It also enlarges the
font sizes of the text inside it.
Ex :
<div class="jumbotron">
<p>Bootstrap is the most popular HTML, CSS, and JS framework for
developingresponsive, mobile-first projects on the web.</p>
</div>

122
2.45PageHeader
A page header is like a section divider.The .page-header class adds a horizontal
line under the heading
Ex:
<div class="page-header">
<h1>Example Page Header</h1>
</div>

2.46 Wells
The .well class adds a rounded border around an element with a gray
background colorand some padding. Change the size of the well by adding
the .well-sm class for small wells or .well-lg class for large wells
Ex: <div class="well">Basic Well</div>

2.47 Alerts
Bootstrap provides an easy way to create predefined alert messagesAlerts are
created with the .alert class, followed by one of the four contextual
classes .alert-success, .alert-info, .alert-warning or .alert-danger
Ex:
<div class="alert alert-success">
<strong>Success!</strong> Indicates a successful or positive action.
</div>
To close the alert message, add a .alert-dismissible class to the alert
container.

2.48 Buttons
To achieve the button styles above, Bootstrap has the following classes:
 .btn
 .btn-default
 .btn-primary
 .btn-success
 .btn-info
 .btn-warning
 .btn-danger
 .btn-link
The classes that define the different sizes are:
• .btn-lg
• .btn-md
• .btn-sm
123
• .btn-xs

Active/Disabled Buttons
A button can be set to an active (appear pressed) or a disabled (unclickable)
state:
The class .active makes a button appear pressed, and the class .disabled makes
a button unclickable:
Ex. <button type="button" class="btnbtn-default">Default</button>

Button Groups
Use a <div> element with class .btn-group to create a button group. Use the
class .btn-group-vertical to create a vertical button group
Ex:
<div class="btn-group">
<button type="button" class="btnbtn-primary">Apple</button>
<button type="button" class="btnbtn-primary">Samsung</button>
</div>

2.49 Glyphicons
Bootstrap provides 260 glyphicons from the Glyphicons Halflings set.Glyphicons
can be used in text, buttons, toolbars, navigation, forms, etc.
Ex .Envelope glyphicon: envelope ,Printglyphicon: print
<p>Print icon: <span class="glyphiconglyphicon-print"></span></p>

2.50 Badges
Badges are numerical indicators of how many items are associated with a link
Ex:
<a href="#">News <span class="badge">5</span></a><br>
<a href="#">Comments <span class="badge">10</span></a><br>

2.51 Labels
Use the .label class, followed by one of the six contextual classes .label-
default, .label-primary, .label-success, .label-info, .label-warning or .label-
danger, within a <span> element
Ex:
<span class="label label-default">Default Label</span>

124
2.52 Progress Bar
A progress bar can be used to show a user how far along he/she is in a process.
<div class="progress">
<div class="progress-bar progress-bar-striped active" role="progressbar" aria-
valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width:40%">
40%
</div>
</div>

2.53 Pagination
If you have a web site with lots of pages, you may wish to add some sort of
pagination to each page.
Ex. <ul class="pagination">
<li><a href="#">1</a></li>
<li class="active"><a href="#">2</a></li>
<li><a href="#">3</a></li>
</ul>

2.54 Breadcrumbs
Another form for pagination, is breadcrumbs:
<ul class="breadcrumb">
<li><a href="#">Home</a></li>
<li><a href="#">Private</a></li>
<li><a href="#">Pictures</a></li>
<li class="active">Vacation</li>
</ul>

2.55 Pager
Pager provides previous and next buttons (links).
<ul class="pager">
<li class="previous"><a href="#">Previous</a></li>
<li class="next"><a href="#">Next</a></li>
</ul>

2.56 Dropdown
A dropdown menu is a toggleable menu that allows the user to choose one value
from a predefined list
<div class="dropdown">
<button class="btnbtn-primary dropdown-
125
toggle" type="button" datatoggle="dropdown">Dropdown Example
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="#">HTML</a></li>
<li><a href="#">CSS</a></li>
<li><a href="#">JavaScript</a></li>
</ul>
</div>

2.57 Collapsible
Collapsibles are useful when you want to hide and show large amount of
content
Ex .
<button type="button" class="btnbtn-info" data-toggle="collapse" data-
target="#demo">Simple collapsible</button>
<div id="demo" class="collapse">
Lorem ipsum dolor sit amet, consecteturadipisicingelit, sed do
eiusmodtemporincididuntutlaboreetdolore magna aliqua. Utenim ad minim
veniam,quisnostrud exercitation ullamcolaboris nisi utaliquip ex
eacommodoconsequat.
</div>

2.58 Menus
Most web pages have some kind of a menu.
<ul class="nav nav-tabs">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">Menu 1</a></li>
<li><a href="#">Menu 2</a></li>
<li><a href="#">Menu 3</a></li>
</ul>

2.59 Navigation Bars using Bootstrap


A navigation bar is a navigation header that is placed at the top of the page.A
standard navigation bar is created with <nav class="navbar navbar-default">
Ex.
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">WebSiteName</a>
</div>
126
<ul class="navnavbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">Page 1</a></li>
<li><a href="#">Page 2</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="#"><span class="glyphiconglyphicon-user"></span>
Sign Up</a></li>
<li><a href="#"><span class="glyphiconglyphicon-
login">/span>Login</a></li> </ul>
</div>
</nav>
2.60 Forms
All textual <input>, <textarea>, and <select> elements with class .form
Control have a width of 100%.
Standard rules for all three form layouts:
 Wrap labels and form controls in <div class="form-group"> (needed for
optimum spacing)
 Add class .form-control to all textual <input>, <textarea>,
and <select> elements
Ex.
<form action="/action_page.php">
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>
<button type="submit" class="btnbtn-default">Submit</button>
</form>

2.61 Media Objects


Bootstrap provides an easy way to align media objects (like images or videos) to
the left or to the right of some content.

127
Use a <div> element with the .media class to create a container for media
objects.
Use the .media-left class to align the media object (image) to the left, or
the .media-right class to align it to the right.
Text that should appear next to the image, is placed inside a container with
class="media-body".class .media-heading for headings.
Ex.
<div class="media">
<div class="media-leftmedia-top">
<img src="img_avatar1.png" class="media-object" style="width:60px">
</div>
<div class="media-body">
<h4 class="media-heading">Media Top</h4>
<p>Lorem ipsum...</p>
</div>
</div>

2.62 Carousel Plugin


The Carousel plugin is a component for cycling through elements, like a carousel
(slideshow).
Ex.
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
</ol>

<!-- Wrapper for slides -->


<div class="carousel-inner">
<div class="item active">
<img src="la.jpg" alt="Los Angeles">
</div>
<div class="item">
<img src="chicago.jpg" alt="Chicago">
</div>
<div class="item">
<img src="ny.jpg" alt="New York">
</div>
128
</div>
<!-- Left and right controls -->
<a class="left carousel-control" href="#myCarousel" data-slide="prev">
<span class="glyphiconglyphicon-chevron-left"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" data-slide="next">
<span class="glyphiconglyphicon-chevron-right"></span>
<span class="sr-only">Next</span>
</a>
</div>

129
3.JAVASCRIPT

3.1 JavaScript
 JavaScript (js) is a light-weight object-oriented programming language
which is used by several websites for scripting the WebPages.
 It is an interpreter, full-fledged programming language that enables
dynamic interactivity on websites when applied to an HTML document. It
was introduced in the year 1995 for adding programs to the WebPages in
the Netscape Navigator browser.
 Since then, it has been adopted by all other graphical web browsers. With
JavaScript, users can build modern web applications to interact directly
without reloading the page every time.
 The traditional website uses JS to provide several forms of interactivity
and simplicity.
 Although, JavaScript has no connectivity with Java programming
language. The name was suggested and provided in the times when Java
was gaining popularity in the market.
 In addition to web browsers, databases such as CouchDB and MongoDB
uses JavaScript as their scripting and query language.

3.2 Features of JavaScript


There are following features of JavaScript:
1. All popular web browsers support JavaScript as they provide built-in
execution environments.
2. JavaScript follows the syntax and structure of the C programming
language. Thus, it is a structured programming language.
3. JavaScript is a weekly typed language, where certain types are implicitly
cast (depending on the operation).
4. JavaScript is an object-oriented programming language that uses
prototypes rather than using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including,
Windows, macOS, etc.
8. It provides good control to the users over the web browsers.

3.3 History of JavaScript

130
 In 1993, Mosaic, the first popular web browser, came into existence. In
the year 1994, Netscape was founded by Marc Andreessen. He realized
that the web needed to become more dynamic.
 Thus, a 'glue language' was believed to be provided to HTML to make web
designing easy for designers and part-time programmers.
 Consequently, in 1995, the company recruited Brendan Eich intending to
implement and embed Scheme programming language to the browser.
 But, before Brendan could start, the company merged with Sun
Microsystems for adding Java into its Navigator so that it could compete
with Microsoft over the web technologies and platforms.
 Now, two languages were there: Java and the scripting language. Further,
Netscape decided to give a similar name to the scripting language as
Java's. It led to 'Javascript'.
 Finally, in May 1995, Marc Andreessen coined the first code of Javascript
named 'Mocha'. Later, the marketing team replaced the name with
'LiveScript'.
 But, due to trademark reasons and certain other reasons, in December
1995, the language was finally renamed to 'JavaScript'. From then,
JavaScript came into existence.
3.4 Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:
o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box,
confirm dialog box and prompt dialog box),
o Displaying clocks etc.

3.5 JavaScript Example


<script>
document.write("Hello JavaScript by JavaScript");
</script>

3.6 JavaScript Variable


A JavaScript variable is simply a name of storage location.
There are two types of variables in JavaScript : local variable and global
variable.
There are some rules while declaring a JavaScript variable (also known as
identifiers).

131
1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar(
$ ) sign.
2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different
variables.

Correct JavaScript variables


var x = 10;
var _value="sonoo";

Incorrect JavaScript variables


var 123=30;
var *aa=320;

Example of JavaScript variable


Let’s see a simple example of JavaScript variable.
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>

Output
30

1.) JavaScript local variable


A JavaScript local variable is declared inside block or function. It is accessible
within the function or block only. For example:
<script>
function abc(){
var x=10;//local variable
}
</script>

2.) JavaScript global variable


A JavaScript global variable is accessible from any function. A variable i.e.
declared outside the function or declared with window object is known as
global variable.
132
For example: <script>
var data=200;//gloabal variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling JavaScript function
b();
</script>

3.7 JavaScript Operators


JavaScript operators are symbols that are used to perform operations on
operands.
For example:
var sum=10+20;
Here, + is the arithmetic operator and = is the assignment operator.
There are following types of operators in JavaScript.
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators

1. Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on the
operands. The following operators are known as JavaScript arithmetic
operators.

Operator Description Example

+ Addition 10+20 = 30

- Subtraction 20-10 = 10

* Multiplication 10*20 = 200

/ Division 20/10 = 2

133
% Modulus (Remainder) 20%10 = 0

++ Increment var a=10; a++; Now a = 11

-- Decrement var a=10; a--; Now a = 9

2. Comparison Operators
The JavaScript comparison operator compares the two operands. The
comparison operators are as follows:

Operator Description Example

== Is equal to 10==20 = false

!= Not equal to 10!=20 = true

!== Not Identical 20!==20 = false

> Greater than 20>10 = true

>= Greater than or equal to 20>=10 = true

< Less than 20<10 = false

<= Less than or equal to 20<=10 = false

3. Bitwise Operators
The bitwise operators perform bitwise operations on operands. The
bitwise operators are as follows:

Operator Description Example

& Bitwise AND (10==20 & 20==33) = false

| Bitwise OR (10==20 | 20==33) = false


134
^ Bitwise XOR (10==20 ^ 20==33) = false

~ Bitwise NOT (~10) = -10

<< Bitwise Left Shift (10<<2) = 40

>> Bitwise Right Shift (10>>2) = 2

Bitwise Right Shift with


>>> Zero (10>>>2) = 2

4. Logical Operators
The following operators are known as JavaScript logical operators.
Operator Description Example

&& Logical AND (10==20 && 20==33) = false

|| Logical OR (10==20 || 20==33) = false

! Logical Not !(10==20) = true

5. Assignment Operators
The following operators are known as JavaScript assignment operators.

Operator Description Example

= Assign 10+10 = 20

+= Add and assign var a=10; a+=20; Now a = 30

135
-= Subtract and assign var a=20; a-=10; Now a = 10

*= Multiply and assign var a=10; a*=20; Now a = 200

/= Divide and assign var a=10; a/=2; Now a = 5

%= Modulus and assign var a=10; a%=2; Now a = 0

6. Special Operators
The following operators are known as JavaScript special operators.

Operator Description
Conditional Operator returns value based on the condition. It
(?:) is like if- else.
Comma Operator allows multiple expressions to be evaluated
, as single statement.

delete Delete Operator deletes a property from the object.

In In Operator checks if object has the given property


instance
of checks if the object is an instance of given type

New creates an instance (object)


typeof checks the type of object.

Void it discards the expression's return value.


checks what is returned in a generator by the generator's
Yield iterator.

3.8 Conditional statement


There are three forms of if statement in JavaScript.
1. If Statement
2. If else statement
3. if else if statement

136
4. switch case statement

1. If statement
It evaluates the content only if expression is true. The signature of JavaScript if
statement is given below.
if(expression){
//content to be evaluated
}
Example
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
Output
value of a is greater than 10

2. If...else Statement
It evaluates the content whether condition is true of false. The syntax of
JavaScript if-else statement is given below.
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
Example
<script>
var a=20;
if(a%2==0){
document.write("a is even number");

137
}
else{
document.write("a is odd number");
}
</script>
Output
a is even number
3. If...else if statement
It evaluates the content only if expression is true from several expressions. The
signature of JavaScript if else if statement is given below.
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else{
//content to be evaluated if no expression is true
}
Example
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
138
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
Output
a is equal to 20

4. Switch Case
The JavaScript switch statement is used to execute one code from multiple
expressions. It is just like else if statement that we have learned in previous page. But
it is convenient than if..else..if because it can be used with numbers, characters etc.
The Syntax of JavaScript switch statement is given below.
switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......
default:
code to be executed if above values are not matched;
}
Example
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
139
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>
Output
B Grade

3.9 Looping Statements


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

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

140
}
</script>
Output:
1
2
3
4
5

2. JavaScript while loop


The JavaScript while loop iterates the elements for the infinite number of times. It
should be used if number of iteration is not known. The syntax of while loop is given
below.
while (condition)
{
code to be executed
}
Example
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
Output:
11
12
13
14
15
3. JavaScript do while loop
The JavaScript do while loop iterates the elements for the infinite number of times like
while loop. But, code is executed at least once whether condition is true or false. The
syntax of do while loop is given below.

141
do{
code to be executed
}while (condition);
Example
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
Output:
21
22
23
24
25

4. JavaScript for in loop


The for/in statement loops through the properties of an object.
The block of code inside the loop will be executed once for each property. The syntax
of do while loop is given below.
for (var in object) {
code block to be executed
}

example:
<script>
var person = {fname:"John", lname:"Doe", age:25};
var text = "";
var x;
for (x in person) {
text += person[x] + " ";
}
</script>

142
3.10 JavaScript Break and Continue
The break statement "jumps out" of a loop.
The continue statement "jumps over" one iteration in the loop.

1. The Break Statement


 You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch() statement.
 The break statement can also be used to jump out of a loop.
 The break statement breaks the loop and continues executing the code
after the loop (if any):
Example
for (i = 0; i < 10; i++) {
if (i === 3) { break; }
text += "The number is " + i + "<br>";
}
2. The Continue Statement
The continue statement breaks one iteration (in the loop), if a specified condition
occurs, and continues with the next iteration in the loop. This example skips the
value of 3:
Example
for (i = 0; i < 10; i++) {
if (i === 3) { continue; }
text += "The number is " + i + "<br>";
}

3. JavaScript Labels
To label JavaScript statements you precede the statements with a label name and a
colon:
label:
statements
The break and the continue statements are the only JavaScript statements that can
"jump out of" a code block.

Syntax:
break labelname;
continue labelname;
The continue statement (with or without a label reference) can only be used to
skip one loop iteration.

143
The break statement, without a label reference, can only be used to jump out of a
loop or a switch.
With a label reference, the break statement can be used to jump out of any code
block:
Continue Example
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var text = "";
var i;
for (i = 0; i < 5; i++) {
if (i === 3) {
continue;
}
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
</script>
Output:
The number is 0
The number is 1
The number is 2
The number is 4
Break Example
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var text = "";
var i;
for (i = 0; i < 5; i++) {
if (i === 3) {
break;
}
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;

144
}
</script>
Output:
The number is 0
The number is 1
The number is 2

3.11 Dialog boxes


There are three types of dialog boxes supported in JavaScript that are alert, confirm,
and prompt. These dialog boxes can be used to perform specific tasks such as raise an
alert, to get confirmation of an event or an input, and to get input from the user. Let's
discuss each dialog box.

1. Alert Dialog box


It is used to provide a warning message to users. It is one of the most widely used dialog
box in JavaScript. It has only one 'OK' button to continue and select the next task.
We can understand it by an example like suppose a textfield is mandatory to be filled
out, but the user has not given any input value to that text field, then we can display a
warning message by using the alert box.

Syntax
alert(message);

Example
<html>
<head>
<script type="text/javascript">
function show() {
alert("It is an Alert dialog box");
}
</script>
</head>

<body>
<center>
<h1>Hello Students</h1>
145
<h2>Welcome to World</h2>
<p>Click the following button </p>
<input type="button" value="Click Me" onclick="show();" />
</center>
</body>
</html>

2. Confirmation Dialog box


It is widely used for taking the opinion from the user on the specific option. It includes
two buttons, which are OK and Cancel. As an example, suppose a user is required to
delete some data, then the page can confirm it by using the confirmation box that
whether he/she wants to delete it or not.
If a user clicks on the OK button, then the method confirm() returns true. But if the
user clicks on the cancel button, then the confirm() method returns false.

Syntax
confirm(message);
Example
<html>
<head>
<script type="text/javascript">
function show() {
var con = confirm ("It is a Confirm dialog box");
if(con == true) {
document.write ("User Want to continue");
}
else {
document.write ("User does not want to continue");
}
}
</script>
</head>
<body>
<center>

146
<h1>Hello Students</h1>
<h2>Welcome to World</h2>
<p>Click the following button </p>
<input type="button" value="Click Me" onclick="show();" />
</center>
</body>
</html>

3. Prompt Dialog box


The prompt dialog box is used when it is required to pop-up a text box for getting the
user input. Thus, it enables interaction with the user.
The prompt dialog box also has two buttons, which are OK and Cancel. The user needs
to provide input in the textbox and then click OK. When a user clicks on the OK button,
then the dialog box reads that value and returns it to the user. But on clicking the Cancel
button, prompt() method returns null.
Syntax
prompt(message, default_string);
Example
<html>
<head>
<script type="text/javascript">
function show() {
var value = prompt("Enter your Name : ", "Enter your name");
document.write("Your Name is : " + value);
}
</script>
</head>
<body>
<center>
<h1>Hello Students</h1>
<h2>Welcome to World</h2>
<p>Click the following button </p>
<input type="button" value="Click Me" onclick="show();" />
</center>
147
</body>
</html>

3.12 JavaScript Array


JavaScript array is an object that represents a collection of similar type of
elements. There are 3 ways to construct array in JavaScript
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)

1. array literal
The syntax of creating array using array literal is given below:
var arrayname=[value1,value2.....valueN];

As you can see, values are contained inside [ ] and separated by ,


(comma).
Example
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
The .length property returns the length of an array.
Output
Sonoo
Vimal
Ratan
2. Array directly (new keyword)
The syntax of creating array directly is given below:
var arrayname=new Array();
Here, new keyword is used to create instance of array.
Example
<script>
var i;
var emp = new Array();

148
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
Output
Arun
Varun
John
3. array constructor (new keyword)
Here, you need to create instance of array by passing arguments in constructor so
that we don't have to provide value explicitly.
The example of creating object by array constructor is given below.
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
Output
Jai
Vijay
Smith

3.13 JavaScript Functions


JavaScript functions are used to perform operations. We can call JavaScript function
many times to reuse the code.

Advantage of JavaScript function


There are mainly two advantages of JavaScript functions.
1. Code reusability: We can call a function several times so it save coding.
2. Less coding: It makes our program compact. We don’t need to write many lines
of
code each time to perform a common task.
Syntax
149
function functionName([arg1, arg2, ...argN]){
//code to be executed
}
JavaScript Functions can have 0 or more arguments.

Function Example
Let’s see the simple example of function in JavaScript that does not has arguments.
Function Without Arguments
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>

Function With Arguments


We can call function by passing arguments. Let’s see the example of function that has
one argument.
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>

Function with Return Value


We can call function that returns a value and use it in our program. Let’s see the
example of function that returns value.
<script>
function getInfo(){
return "hello Students! How r u?";
}
150
</script>
<script>
document.write(getInfo());
</script>

3.14 Built in function

3.14.1 String Functions


The JavaScript string is an object that represents a sequence of
characters. There are 2 ways to create string in JavaScript
1. By string literal
2. By string object (using new keyword)

1. By string literal
The string literal is created using double quotes. The syntax of creating string using
string literal is given below:
var stringname="string value";

Example
<script>
var str="This is string literal";
document.write(str);
</script>
Output:
This is string literal
2. By string object (using new keyword)
The syntax of creating string object using new keyword is given below:
var stringname=new String("string literal");
Here, new keyword is used to create instance of
string.
Example
<script>
var stringname=new String("hello javascript string");
document.write(stringname);
</script>
Output:
151
hello javascript string

String Functions
1. charAt(index)
The JavaScript String charAt() method returns the character at the given index.
<script>
var str="javascript";
document.write(str.charAt(2));
</script>
Output:
V

2. concat(str)
The JavaScript String concat(str) method concatenates or joins two strings.
<script>
var s1="javascript ";
var s2="concat example";
var s3=s1.concat(s2);
document.write(s3);
</script>
Output:
javascript concat example

3. indexOf(str)
The JavaScript String indexOf(str) method returns the index position of the given
string.
<script>
var s1="javascript from Students indexof";
var n=s1.indexOf("from");
document.write(n);
</script>
Output:
11

4. lastIndexOf(str)
152
The JavaScript String lastIndexOf(str) method returns the last index position of the
given string.
<script>
var s1="javascript from Students indexof";
var n=s1.lastIndexOf("java");
document.write(n);
</script>
Output:
16

5. toLowerCase()
The JavaScript String toLowerCase() method returns the given string in lowercase
letters.
<script>
var s1="JavaScript toLowerCase Example";
var s2=s1.toLowerCase();
document.write(s2);
</script>
Output:
javascript tolowercase example

6. toUpperCase()
The JavaScript String toUpperCase() method returns the given string in uppercase
letters.
<script>
var s1="JavaScript toUpperCase Example";
var s2=s1.toUpperCase();
document.write(s2);
</script>
Output:
JAVASCRIPT TOUPPERCASE EXAMPLE

7. slice(beginIndex, endIndex)

153
The JavaScript String slice(beginIndex, endIndex) method returns the parts of string
from given beginIndex to endIndex. In slice() method, beginIndex is inclusive and
endIndex is exclusive.
<script>
var s1="abcdefgh";
var s2=s1.slice(2,5);
document.write(s2);
</script>
Output:
Cde

8. trim()
The JavaScript String trim() method removes leading and trailing whitespaces from the
string.
<script>
var s1=" javascript trim ";
var s2=s1.trim();
document.write(s2);
</script>
Output:
javascript trim

9. split()
It splits a string into substring array,then returns that newly created array.
<script>
var str="This is Students website";
document.write(str.split(" ")); //splits the given string.
</script>

10. valueOf()
valueOf() method is used to find out the primitive value of String object.
<script>
var str="Students";
document.writeln(str.valueOf());
</script>
154
Output:
Students

11. toString()
toString() method returns a string representing the calling object. In other words, this
method provides a string representation of the object and treats same as the valueof()
method.
<script>
var str="Students";
document.writeln(str.toString());
</script>
Output:
Students

3.14.2Math Functions
The JavaScript math object provides several constants and methods to perform
mathematical operation. Unlike date object, it doesn't have constructors.

1. sqrt(n)
The JavaScript math.sqrt(n) method returns the square root of the given number.
Example
Square Root of 17 is: <span id="p1"></span>
<script>
document.getElementById('p1').innerHTML=Math.sqrt(17);
</script>
Output:
Square Root of 17 is: 4.123105625617661
2. random()
The JavaScript math.random() method returns the random number between 0 to 1.
Example
Random Number is: <span id="p2"></span>
<script>
document.getElementById('p2').innerHTML=Math.random
(); </script>
Output:
Random Number is: 0.8503284715996762

155
3. pow(m,n)
The JavaScript math.pow(m,n) method returns the m to the power of n that is m n.
Example
3 to the power of 4 is: <span id="p3"></span>
<script>
document.getElementById('p3').innerHTML=Math.pow(3,4);
</script>
Output:
3 to the power of 4 is: 81

4. floor(n)
The JavaScript math.floor(n) method returns the lowest integer for the given number.
For example 3 for 3.7, 5 for 5.9 etc.
Example
Floor of 4.6 is: <span id="p4"></span>
<script>
document.getElementById('p4').innerHTML=Math.floor(4.6);
</script>
Output:
Floor of 4.6 is: 4

5. ceil(n)
The JavaScript math.ceil(n) method returns the largest integer for the given number.
For example 4 for 3.7, 6 for 5.9 etc.
Example
Ceil of 4.6 is: <span id="p5"></span>
<script>
document.getElementById('p5').innerHTML=Math.ceil(4.6);
</script>
Output:
Ceil of 4.6 is: 5

6. round(n)
The JavaScript math.round(n) method returns the rounded integer nearest for the
given number. If fractional part is equal or greater than 0.5, it goes to upper value 1
otherwise lower value 0. For example 4 for 3.7, 3 for 3.3, 6 for 5.9 etc.
Example
Round of 4.3 is: <span id="p6"></span><br>
156
Round of 4.7 is: <span id="p7"></span>
<script>
document.getElementById('p6').innerHTML=Math.round(4.3);
document.getElementById('p7').innerHTML=Math.round(4.7);
</script>
Output:
Round of 4.3 is: 4
Round of 4.7 is: 5

7. abs(n)
The JavaScript math.abs(n) method returns the absolute value for the given number.
For example 4 for -4, 6.6 for -6.6 etc.
Example
Absolute value of -4 is: <span id="p8"></span>
<script>
document.getElementById('p8').innerHTML=Math.abs(-4);
</script>
Output:
Absolute value of -4 is: 4

8. min()
min() method compares the given numbers and returns the minimum value.
Example
<script>
document.writeln(Math.min(22,34,12,15)+"<br>");
document.writeln(Math.min(-10,-24,-12,-20));
</script>
Output:
12
1.-24

9. max()
max() method compares the given numbers and returns the maximum value.
Example
<script>
document.writeln(Math.max(22,34,12,15)+"<br>");
document.writeln(Math.max(-10,-24,-12,-20));
157
</script>
Output:
34
-10

3.14.3 Array Functions

1. concat()
concat() method combines two or more arrays and returns a new string. This method
doesn't make any change in the original array.
Example
<script>
var arr1=["C","C++","Python"];

var arr2=["Java","JavaScript","Android"];
var result=arr1.concat(arr2);
document.writeln(result);
</script>
Output:
C,C++,Python,Java,JavaScript,Android

2. find()
find() method returns the first element of the given array that satisfies the provided
function condition.
Example
<script>
var arr=[5,22,19,25,34];
var result=arr.find(x=>x>20);
document.writeln(result)
</script>
Output:
22

3. findIndex()
findIndex() method returns the index of first element of the given array that satisfies
the provided function condition. It returns -1, if no element satisfies the condition.
Example
158
<script>
var arr=[5,22,19,25,34];
var result=arr.findIndex(x=>x>20);
document.writeln(result)
</script>
Output:
1

4. indexOf()
indexOf() method is used to search the position of a particular element in a given
array. This method is case-sensitive.
The index position of first element in an array is always start with zero. If an element
is not present in an array, it returns -1.
Example
<script>
var arr=["C","C++","Python","C++","Java"];
var result= arr.indexOf("C++");
document.writeln(result);
</script>
Output:
1

5. isArray()
isArray() method is used to test whether the value passed is an array. If it finds the
passed value is an array, it returns True. Otherwise, it returns False.
Example 1
<script>
document.write(Array.isArray(1,2,3,4)); //Testing the passed values.
</script>
Example 2
<script>
var arr=new Array(1,2,34,4,5);
document.write(Array.isArray(arr)); //It will return true.
</script>

159
6. join()
The JavaScript array join() method combines all the elements of an array into a string
and return a new string. We can use any type of separators to separate given array
elements.
Example
<script>
var arr=["AngularJs","Node.js","JQuery"]
var result=arr.join()
document.write(result);
</script>

7. lastIndexOf()
The JavaScript array lastIndexOf() method is used to search the position of a particular
element in a given array. It behaves similar to indexOf() method with a difference that
it start searching an element from the last position of an array.
The lastIndexOf() method is case-sensitive. The index position of first character in a
string is always start with zero. If an element is not present in a string, it returns -1.
Example
<script>
var arr=["C","C++","Python","C++","Java"];
var result= arr.lastIndexOf("C++");
document.writeln(result);
</script>

Output:
3

8. pop()
pop() method removes the last element from the given array and return that
element. This method changes the length of the original array.
Example
<script>
var arr=["AngularJS","Node.js","JQuery"];
document.writeln("Orginal array: "+arr+"<br>");
document.writeln("Extracted element: "+arr.pop()+"<br>");
document.writeln("Remaining elements: "+ arr);
160
</script>

Output:
Orginal array: AngularJS,Node.js,JQuery
Extracted element: JQuery
Remaining elements: AngulaJS,Node.js

9. push()
push() method adds one or more elements to the end of the given array. This method
changes the length of the original array.
Example
<script>
var arr=["AngularJS","Node.js"];
arr.push("JQuery");
document.writeln(arr);
</script>

Output:
AngularJS,Node.js,JQuery

10. reverse()
reverse() method changes the sequence of elements of the given array and returns the
reverse sequence. In other words, the arrays last element becomes first and the first
element becomes the last. This method also made the changes in the original array.
Example
<script>
var arr=["AngulaJS","Node.js","JQuery"];
var rev=arr.reverse();
document.writeln(rev);
</script>
Output:
JQuery,Node.js,AngulaJS

11. shift()
shift() method removes the first element of the given array and returns that element.
This method changes the length of the original array.
Example
<script>

161
var arr=["AngularJS","Node.js","JQuery"];
var result=arr.shift();
document.writeln(result);
</script>

Output:
AngularJS

12. slice()
slice() method extracts the part of the given array and returns it. This method doesn't
change the original array.
Example
<script>
var arr=["AngularJS","Node.js","JQuery","Bootstrap"]
var result=arr.slice(1,2);
document.writeln(result);
</script>
Output:
Node.js

13. sort()
sort() method is used to arrange the array elements in some order. By default, sort()
method follows the ascending order.
Example
<script>
var arr=["AngularJS","Node.js","JQuery","Bootstrap"]
var result=arr.sort();
document.writeln(result);
</script>

Output:
AngularJS,Bootstrap,JQuery,Node.js

14. unshift()
unshift() method adds one or more elements in the beginning of the given array and
returns the updated array. This method changes the length of the original array.

162
Example
<script>
var arr=["AngularJS","Node.js"];
var result=arr.unshift("JQuery");
document.writeln(arr);
</script>
Output:
JQuery,AngularJS,Node.js

3.15 Date Methods


1. getDate()
getDate() method returns the day for the specified date on the basis of local time.
Example
<script>
var date=new Date();
document.writeln("Today's day: "+date.getDate());
</script>

Output:
Today's day: 16

Example 2
<script>
var date=new Date("August 15, 1947 20:22:10");
document.writeln(date.getDate())
</script>

Output:
15

2. getDay()
getDay() method returns the value of day of the week for the specified date on the
basis of local time. The value of the day starts with 0 that represents Sunday.
Example
<script>
var day=new Date();
163
document.writeln(day.getDay());
</script>

Output:
1

3. getHours()
getHours() method returns the hour for the specified date on the basis of local time.
Example
<script>
var hour=new Date();
document.writeln(hour.getHours());
</script>
Output:
15

4. getMilliseconds()
getMilliseconds() method returns the value of milliseconds in specified date on the
basis of local time.
Example
<script>
var milli =new Date();
document.writeln(milli.getMilliseconds());
</script>
Output:
238

5. getMinutes()
getMinutes() method returns the minutes in the specified date on the basis of
local time.
Example
<script>
var min=new Date();
document.writeln(min.getMinutes());
</script>
Output:
164
9

6. getMonth()

getMonth() method returns the integer value that represents month in the specified
date on the basis of local time. The value returned by getMonth() method starts with 0
that represents January.
Example
<script>
var date=new Date();
document.writeln(date.getMonth()+1);
</script>
Output:
7

7. getSeconds()
getSeconds() method returns the seconds in the specified date on the basis of local
time.
Example
<script>
var sec=new Date();
document.writeln(sec.getSeconds());
</script>

Output:
56

8. setHours()

setHours() method is used to set the hour for the specified date on the basis of
local time.
Example
<script>
var hours=new Date();
document.writeln("Current Hour : "+hours.getHours()+"<br>");
hours.setHours(8);
document.writeln("Updated Hour : "+hours.getHours());
165
</script>

Output:
Current Hour : 13
Updated Hour : 8

9. setMilliseconds()
setMilliseconds() method is used to set the milliseconds for a specified date on the
basis of local time.
Example
<script>
var ms=new Date();
document.writeln("Current millisecond : "+ms.getMilliseconds()+"<br>");
ms.setMilliseconds(825);
document.writeln("Updated millisecond : "+ms.getMilliseconds());
</script>

Output:
Current millisecond : 750
Updated millisecond : 825

10. setMinutes()
setMinutes() method is used to set the minutes for a specified date on the basis of
local time.
Example
<script>
var minutes=new Date();
document.writeln("Current Minute : "+minutes.getMinutes()+"<br>");
minutes.setMinutes(32);
document.writeln("Updated Minute : "+minutes.getMinutes());
</script>

Output:
Current Minute : 57
Updated Minute : 32

166
11. toDateString()
toDateString() method returns the date portion of a Date object in the form of string.
Example
<script>
var date=new Date();
document.writeln(date.toDateString());
</script>
Output:
Tue Aug 07 2018

12. toISOString()
toISOString() method returns the string representation of the Date object. The
returned string is in the form of simplified extended ISO format, which is always 24 or
27 characters long.
Example
<script>
var date=new Date();
document.writeln(date.toISOString());
</script>
Output:
2018-08-09T13:01:38.116Z

13. toString()
toString() method returns a Date object in the form of string.
Example
<script>
var date=new Date();
document.writeln(date.toString());
</script>
Output:
Tue Aug 07 2018 16:57:22 GMT+0530 (India Standard Time)

14. toTimeString()
toTimeString() method returns the time portion of a Date object in the form of string.
Example
<script>
167
var time=new Date();
document.writeln(time.toTimeString());
</script>
Output:
10:19:29 GMT+0530 (India Standard Time)

3.16 JS Events

The change in the state of an object is known as an Event. In html, there are various
events which represents that some activity is performed by the user or by the
browser. When javascript code is included in HTML, js react over these events and
allow the execution. This process of reacting over the events is called Event
Handling. Thus, js handles the HTML events via Event Handlers.

For example, when a user clicks over the browser, add js code, which will execute
the task to be performed on the event.
Some of the JAVASCRIPTS events and their event handlers are:

1. Mouse events:

Event Event Handler Description


Performed

Click onclick When mouse click on an element

When the cursor of the mouse comes


mouseover onmouseover over the element

When the cursor of the mouse leaves an


mouseout onmouseout element

When the mouse button is pressed over


mousedown onmousedown the element

When the mouse button is released over


mouseup onmouseup the element

168
mousemove onmousemove When the mouse movement takes place.

2. Keyboard events:

Event Event
Performed Handler Description

Keydown & onkeydown & When the user press and then
Keyup onkeyup release the key

3. Form events:

Event
Performed Event Description
Handler

focus onfocus When the user focuses on an element

submit onsubmit When the user submits the form

When the focus is away from a form


Blur onblur element

When the user modifies or changes the


change onchange value of a form element

4. Window/Document events

Event Event Description


Performed Handler

When the browser finishes the loading of the


Load onload page
169
When the visitor leaves the current webpage,
unload onunload the browser unloads it

When the visitor resizes the window of the


resize onresize browser

Examples
1.Click Event
<html>
<head> Javascript Events </head> <body>
<script language="Javascript" type="text/Javascript">
function clickevent()
{
document.write("At College ");
}
</script>
<form>
<input type="button" onclick="clickevent()" value="Where are you?"/> </form>
</body>
</html>

2.MouseOver Event
<html>
<head>
<h1> Javascript Events </h1> </head>
<body>
<script language="Javascript" type="text/Javascript">
function mouseoverevent()
{
alert("Welcome to World College");
}
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>
3.Focus Event
<html>
<head> Javascript Events</head> <body>
<h2> Enter something here</h2>
170
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
function focusevent()
{
document.getElementById("input1").style.background=" aqua";
}
</script>
</body>
</html>

4.Keydown Event
<html>
<head> Javascript Events</head> <body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
function keydownevent()
{
document.getElementById("input1");
alert("Pressed a key");
}
</script>
</body>
</html>
5.Load event
<html>

<head>Javascript Events</head> </br>


<body onload="window.alert('Page successfully loaded');"> <script>
document.write("The page is loaded successfully"); </script>
</body>
</html>

6.MouseOut Event
<html>
<head>
<h1> Javascript Events </h1> </head>
<body>
<script language="Javascript" type="text/Javascript">
function mouseoutevent()
{
alert("Welcome to World College");
171
}
</script>
<p onmouseout="mouseoutevent()"> Keep cursor over me</p>
</body>
</html>

7.MouseDown Event
<html>
<head>
<h1> Javascript Events </h1> </head>
<body>
<script language="Javascript" type="text/Javascript"> function myfunction()
{
alert("Welcome to World College");
}
</script>
<p onmouseout="myfunction()"> Keep cursor over me</p> </body>
</html>

8.Mouseup Event
<html>
<head>
<h1> Javascript Events </h1> </head>
<body>
<script language="Javascript" type="text/Javascript">
function myfunction()
{
alert("Welcome to World College");
}
</script>
<p onmouseup="myfunction()"> Keep cursor over me</p>
</body>
</html>

9.MouseMove Event
<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script language="Javascript" type="text/Javascript">
function myfunction()
172
{
alert("Welcome to World College");
}
</script>
<p onmousemove="myfunction()"> Keep cursor over me</p>
</body>
</html>

10.KeyUp Event
<html>
<head> Javascript Events</head>
<body>

<h2> Enter something here</h2>


<input type="text" id="input1" onkeyup="myfunction()"/>
<script>
function myfunction()
{
document.getElementById("input1");
alert("Pressed a key");
}
</script>
</body>
</html>

11.Submit Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<form method="post" action="#" onsubmit="myFunction()">
<input type="text" id="input1" />
<input type="submit" value="press">
</form>
<script>
function myFunction()
{
document.getElementById("input1");
alert("Form submited");
}
</script>
</body>
173
</html>

12.Blur Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onblur="blurevent()"/>
<script>
function blurevent()
{
document.getElementById("input1").style.background=" red";
}
</script>
</body>
</html>

13.Change Event
<html>
<body>
select city: <select onchange="myFunction(this.value)">
<option>rajkot</option>
<option>surat</option>
<option>ahmedabad</option>
<option>vadodara</option>
</select>
<script>
function myFunction(val) {
alert("The value changed. The new value is: " + val);
}
</script>
</body>
</html>

14.Unload Event
<html>
<body onunload="myFunction()">
<h1>Welcome to my Home Page</h1>
<p>Close this window or press F5 to reload the page.</p> <p><strong>Note:</strong>
Due to different browser settings, this event may not always work as expected.</p>
<script>
function myFunction()
174
{ alert("Thank you ");
}
</script>
</body>
</html>

15.Resize Event
<html>
<body onresize="myFunction()">
<h1>Welcome to my Home Page</h1>
<script>
function myFunction()
{
alert("window resize");
}
</script>
</body>
</html>

3.17 Document Object Model


The document object represents the whole html document.
When html document is loaded in the browser, it becomes a document object. It is
the root element that represents the html document. It has properties and methods.
By the help of document object, we can add dynamic content to our web page. As
mentioned earlier, it is the object of window.
So window.document Is same as document

According to W3C - "The W3C Document Object Model (DOM) is a platform and
language-neutral interface that allows programs and scripts to dynamically access and
update the content, structure, and style of a document."
Properties of document object
Let's see the properties of document object that can be accessed and modified by
the document object.

Methods of document object


We can access and change the contents of document by its methods.
The important methods of document object are as follows:

Method Description
write("string") writes the given string on the doucment.

175
writes the given string on the doucment with
writeln("string") newline character at the end.

getElementById() returns the element having the given id value.


returns all the elements having the given name
getElementsByName() value.

returns all the elements having the given tag


getElementsByTagName() name.

getElementsByClassName returns all the elements having the given class


() name.

Accessing field value by document object

In this example, we are going to get the value of input text by user. Here, we are using
document.form1.name.value to get the value of name field. Here, document is the
root element that represents the html document.
form1 is the name of the form.
name is the attribute name of the input text.
value is the property, that returns the value of the input text.

Let's see the simple example of document object that prints name with welcome
message.
<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>

3.18 JavaScript Form Validation

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

1. JavaScript Form Validation Example


In this example, we are going to validate the name and password. The name can’t be
empty and password can’t be less than 6 characters long.
Here, we are validating the form on form submit. The user will not be forwarded to the
next page until given values are correct.

<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="abc.jsp" onsubmit="return
validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>

2. JavaScript Retype Password Validation


<script type="text/javascript">
function matchpass(){
var firstpassword=document.f1.password.value;
var secondpassword=document.f1.password2.value;
if(firstpassword==secondpassword)
{ return true;
177
}
else{
alert("password must be same!"); return false;
}
}
</script>
<form name="f1" action="register.jsp" onsubmit="return matchpass()">
Password:<input type="password" name="password" /><br/>
Re-enter Password:<input type="password" name="password2"/><br/>
<input type="submit">
</form>

3. JavaScript Number Validation


Let's validate the textfield for numeric value only. Here, we are using isNaN() function.
<script>
function validate(){
var num=document.myform.num.value;
if (isNaN(num)){
document.getElementById("numloc").innerHTML="Enter Numeric value only";
return false;
}else{
return true;
}
}
</script>
<form name="myform" onsubmit="return validate()" >
Number: <input type="text" name="num">
<span id="numloc"></span><br/>
<input type="submit" value="submit">
</form>

4. JavaScript validation with image


Let’s see an interactive JavaScript form validation example that displays correct and
incorrect image if input is correct or incorrect.
<script>
function validate(){
var name=document.f1.name.value;

178
var password=document.f1.password.value;
var status=false;
if(name.length<1){
document.getElementById("nameloc").innerHTML=

<img src='unchecked.gif'/> Please enter your name";


status=false;
}else{
document.getElementById("nameloc").innerHTML=" <img src='checked.gif'/>";
status=true;
}

if(password.length<6)
{ document.getElementById("passwordloc").innerHTML=
<img src='unchecked.gif'/> Password must be at least 6 char long";
status=false;
}else{
document.getElementById("passwordloc").innerHTML=" <img src='checked.gif'/>";
}

return status;
}
</script>
<form name="f1" action="#" onsubmit="return validate()">
<table>
<tr><td>Enter Name:</td><td><input type="text"
name="name"/> <span id="nameloc"></span></td></tr>
<tr><td>Enter Password:</td><td><input type="password"
name="password"/> <span id="passwordloc"></span></td></tr>
<tr><td colspan="2"><input type="submit" value="register"/></td></tr>
</table>
</form>

JavaScript email validation

We can validate the email by the help of JavaScript.


There are many criteria that need to be follow to validate the email id such as:
o email id must contain the @ and . character
o There must be at least one character before and after the @.
179
o There must be at least two characters after .
(dot). Let's see the simple example to validate the email
field.

<script>
function validateemail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n
dotposition:"+dotposition);
return false;
}
}
</script>

<body>
<form name="myform" method="post" action="#" onsubmit="return
validateemail();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register">
</form>

180
4.Introduction to PHP as Programming Language

4.1 Introduction to PHP


• PHP is a server scripting language and a powerful tool for making dynamic and
interactive web pages.
• PHP stands for "PHP: Hypertext Preprocessor",
• PHP is a widely-used, open source scripting language.
• PHP scripts are executed on the server.
• PHP is free to download and use.

4.2 A Brief History of PHP


 PHP was originally created by Rasmus Lerdorf in 1994. Programmer Rasmus
Lerdorf initially created a set of C scripts he called "Personal Home Page Tools" to
maintain his personal homepage.
 The scripts performed tasks such as displaying his resume and recording his web-
page traffic. These were released and extended to include a package called the
Form Interpreter (PHP/FI). While PHP originally stood for "Personal Home Page",
now it is known as "PHP: Hypertext Preprocessor".
 In 1997 Zeev Suraski and Andi Gutmans along with Rasmus rewrite PHP and
released PHP version 3.0 in June 1998. After this release PHP becomes so much
popular.
 The PHP version 4.0 was launched in May 2000. This version includes session
handling, output buffering and support for wide variety of web server platforms.
 The PHP 5.0 version released in 2004 with object oriented programming concept.

4.3 Open Source


 In general, open source refers to any program whose source code is made
available for use or modification. Open source software is usually developed as
a public collaboration and made freely available. It means can be used without
purchasing any license.
 Open Source is a certification mark owned by the Open Source Initiative (OSI).
Developers of software that is intended to be freely shared and possibly
improved and redistributed by others can use the Open Source trademark if
their distribution terms conform to the OSI's Open Source Definition. To
summarize, the Definition model of distribution terms require that:
o The software being distributed must be redistributed to anyone else without
181
any restriction.
o The source code must be made available (so that the receiving party will be
able to improve or modify it).
 Example of Open Source: Linux, Apache, MySQL, PHP.

4.4 How PHP Works?


• PHP sits between your browser and the web server. When you type in the URL of a
PHP website in your browser, your browser sends a request to the web server. The
web server then calls the PHP script on that page. The PHP module executes the script
which then sends the result in the form of HTML back to your browser which you seen
on the screen.

4.5 Relationship between Apache, MySQL and PHP (AMP Module)


• AMP stands for Apache MySQL PHP

PHP

• PHP is a server side scripting that was designed for creating dynamic websites.
• PHP script runs on a web server.
• PHP is loosely type language because it converts a data type of variable
automatically.
• PHP is powerful scripting language that can be run in the command line of any
computer with PHP installed.
• However, PHP alone isn't enough in order to build dynamic web sites.

182
Apache
• To use PHP on a web site, you need a server that can process PHP scripts. Apache is
a free web Server that, once installed on a computer, allows developers to test PHP
scripts locally; this makes it an invaluable piece of your local development
environment.
• Like all web servers, Apache accepts an HTTP request and serves an HTTP response.
• Apache is open source free software distributed by the Apache Software
Foundation.
MySQL
• Additionally, dynamic websites are dependent on stored information that can be
modified quickly and easily; this is the main difference between a dynamic site and a
static HTML site.
• However, PHP doesn't provide a simple, efficient way to store data. This is where a
relational database management system like MySQL comes into play.
• PHP provides native support for it and the database is free, open-source project. •
MySQL is a relational database management system (DBMS). Essentially, this means
that MySQL allows users to store information in a table-based structure, using rows
and columns to organize different pieces of data.

4.6 Creating and Saving a PHP File


• A PHP script is executed on the server, and the plain HTML result is sent back to the
browser.
• A PHP script starts with <?php and ends with ?>
• A PHP script can be placed anywhere in the document.
Syntax:
<?php
// PHP code goes here
?>
• 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. <html>
183
<head>
<title>PHP</title>
</head>
<body>
<?php
echo "Hello World";
?>
</body>
</html>
Output: Hello World

4.7 PHP Start and End Tags


• There are four different pairs of opening and closing tags which can be used in php.
• Below, we have an example of a simple PHP script which sends the text "Hello
World" to the browser:
1. Standard PHP tags
<?php
echo "Hello World";
?>
2. Short tags
<?
echo "Hello World";
?>
Short tags are only available when they are enabled via the short_open_tag php.ini
configuration file directive, or if php was configured with the enable-short-tags
option.
3. Script tags
<script language="php">
echo "Hello World";

184
</script>
This syntax is removed after PHP 7.0.0.
4. ASP style tags
<%
echo "Hello World";
%>
This syntax is removed after PHP 7.0.0.

4.8 Comments in PHP


• PHP also supports comment like a C, C++, Java languages.
• PHP supports two types of comments:
Single line comment
• Single line comment started with symbol //.
<?php // this is the single line comment ?>
• If you have a single line comment, another option is to use a # sign. Here is an
example of this:
<?php # this is a single line comment ?>
Multiline comment
• Multiline comment started with symbol /* and end with symbol */.
• So, the multiline comment starts with one line and can be expand to more than one
line.
<?php /* this is the Multiline Comment */ ?>

4.9 PHP Echo and Print Statements


• They are both used to output data to the screen.

Echo

• The simplest use of echo is to print a string as argument, for example:


echo "Hello World";
• or equivalently: echo ("Hello World");
185
• You can also give multiple arguments to the unparenthesized version of echo,
separated by commas: echo "Hello", "World";
• The parenthesized version, however, will not accept multiple arguments:
echo("Hello", "World");

INPUT OUTPUT
echo(“Hello World”); Hello World
echo "Hello World"; Hello World
echo "Hello", "World"; Hello World
echo("Hello", "World"); Invalid Argument

Print

• The command print is very similar to echo, with two important differences:
o print can accept only one argument.
o print returns a value, which represents whether the print statement succeeded.
• The value returned by print will be 1 if the printing was successful and 0 if
unsuccessful.
For example, the following two lines will print exactly the same thing: print("3.14159
"); //print a string
print(3.14159); //print a number

4.10 PHP Variable and Variable Rules


• Variables are "containers" for storing information.
• Declaring Variables: $var_name=value;
Rules for PHP variables:
 A variable starts with the $ sign, followed by the name of the variable.
 A variable name must start with a letter or the underscore character.
 A variable name cannot start with a number. O A variable name can only
contain alpha-numeric character and underscore (A-Z, 0-9, and_ ).
 Variable names are case-sensitive ($age and $AGE are two different variables).
 Example:
 $txt = "Hello world!"; // variable $txt will hold the value Hello world!
186
 $x = 5; // variable $x will hold the value 5
 $y = 10.5; // variable $y will hold the value 10.5

4.11 Data Types


 PHP supports following data types:
Scalar data
 Scalar data means data that contains only a single value.

Compound data
 Compound data is data that can contain more than one value.

Special data
• Finally, PHP supports two special data types, so called because they don't contain
scalar or compound data as such, but have a specific meaning:

4.12 Type Casting:

Gettype
• This function is use to get the type of the variable that means this function will
return the type of the PHP variable.
• Syntax: gettype(arg)
• The above function will return a string representing the type of arg: integer, float,
187
string, array, and object, NULL or unknown type.
Example:
<?php
$a=10;
echo gettype($a);
$b="rahul";
echo gettype($b);
?>
Output:
integer string

settype
• The settype() function is used to set the type of a variable.
• Syntax: settype(var_name, var_type)
• var_name: The variable being converted.
• var_type: Type of the variable. Possible values: boolean, integer, float, string, array,
object, null.
Example:
$a=65;
settype($a, "string");
casting
• If you want to change type temporary, i.e., want to use inside an expression, you
can use type casting.
• Syntax: (type)$variable
• Where type is a type of variable you wish to cast to.
Example:
$var1= 10; //integer

188
$var2= (string) $var1; // Svarl is now set to 10 (string)

4.13 PHP Operators


• Operators are used to perform operations on variables and values.
Arithmetic Operators
• The PHP arithmetic operators are used with numeric values to perform common
arithmetical operations, such as addition, subtraction, multiplication etc.

Logical Operators
• The PHP logical operators are used to combine conditional statements.

Assignment Operators
• The PHP assignment operators are used with numeric values to write a value to a
variable. The basic assignment operator in PHP is "=". It means that the left operand
set to the value of the assignment expression on the right.

String Operators
• PHP has two operators that are specially designed for strings.
189
Increment / Decrement Operators
• The PHP increment operators are used to increment a variable's value.
• The PHP decrement operators are used to decrement a variable's value.

Conditional Operator
• There is one more operator called conditional operator. This first evaluates an
expression for a true or false value and then execute one of the two given statements
depending upon the result of the evaluation. The conditional operator has this syntax:

Example:
<?php
$number = 21;
$result= ($number % 2 == 0) ? "Number is Even" : "Number is Odd";
echo $result;
?>

Output:
Number is Odd
Comparison Operators
• The PHP comparison operators are used to compare two values (number or string):

190
Bitwise Operators
• Bitwise operators allow evaluation and manipulation of specific bits within an
integer.

4.14 PHP Constants


• A constant is an identifier (name) for a simple value. The value cannot be changed
during the script.
• A valid constant name starts with a letter or underscore (no $ sign before the
constant name).
• To create a constant, use the define() function.
Syntax: define(name, value, case-insensitive)
o name: Specifies the name of the constant
o value: Specifies the value of the constant
o case-insensitive: Specifies whether the constant name should be case-insensitive.

191
Default is false.
Example 1:
o The example below creates a constant with a case-sensitive name.
<?php
define("GREETING", "PHP is a scripting language");
echo GREETING;
?>
Output: PHP is a scripting language
Example 2:
o The example below creates a constant with a case-insensitive name.
<?php
define("GREETING", "PHP is a scripting language ", true);
echo greeting;
?>
Output:
PHP is a scripting language
constant() function
• The constant() function returns the value of a constant.
• Syntax: constant(constant)
o Constant: Required. Specifies the name of the constant.
Example:
<?php
define("GREETING", "Hello you! How are you today?");
echo constant("GREETING");
?>
Output: Hello you! How are you today?

192
4.15 Flow control statements
• Conditional statements are used to perform different actions based on different
conditions.
• In PHP we have the following conditional statements:
o if statement - executes some code only if a specified condition is true
o if...else statement - executes code if a condition is true and another code if the
condition is false
o if...elseif....else statement - specifies a new condition to test, if the first condition is
false
o switch statement - selects one of many blocks of code to be executed

4.15.1 if Statement
• The if statement is used to execute some code only if a specified condition is true.
• Syntax:
if (condition)
{
code to be executed if condition is true;
}
• Example:
<?php
$number = 20;
if ($number % 2 == 0)
echo "Number is Even";
if ($number % 2 != 0)
echo "Number is Odd";
?>
Output: Number is Even

4.15.2 if...else Statement


• Use the if....else statement to execute some code if a condition is true and another
code if the condition is false
• Syntax:
if (condition)
{
code to be executed if condition is true;

193
}
else
{
code to be executed if condition is false;
}
• Example:
<?php
$number = 20;
if ($number % 2 == 0)
echo "Number is Even";
else
echo "Number is Odd";
?>
Output:
Number is Even

4.15.3 if...elseif....else Statement


• Use the if....elseif...else statement to specify a new condition to test, if the first
condition is false.
• Syntax:
if (condition)
{
code to be executed if condition is true;
}
elseif (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}
• Example:
<?php
$a=10; $b=12; $c=30;
if ($a > $b && $a > $c)
echo "a is max";
elseif ($b > $c)
echo "b is max";
194
else
echo "c is max";
?>
Output: c is max

4.15.4 switch Statement


• The switch statement is used to perform different actions based on different
conditions.
• Use the switch statement to select one of many blocks of code to be executed.
• Syntax:
switch (n)
{
case label1: code to be executed if n=label1; break;
case label2: code to be executed if n=label2; break;
case label3: code to be executed if n=label3; break;

default: code to be executed if n is different from all labels;
}
• How it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for
each case in the structure.
• If there is a match, the block of code associated with that case is executed.
• Use break to prevent the code from running into the next case automatically.
• The default statement is used if no match is found.

Example: <?php
$a=6;
switch($a)
{
case 1: echo "Monday"; break;
case 2: echo "Tuesday"; break;
case 3: echo "Wednesday"; break;
case 4: echo "Thursday"; break;
case 5: echo "Friday"; break;
case 6: echo "Saturday"; break;
case 7: echo "Sunday"; break;
default: echo "Wrong Choice";
}
Output: Saturday
195
4.16 Loops
• You want the same block of code to run over and over again. Instead of adding
several almost equal code-lines in a script, we can use loops to perform a task like
this.
• Loops execute a block of code while the specified condition is true.
In PHP, we have the following looping statements:
o while - loops through a block of code as long as the specified condition is true.
o do...while - loops through a block of code once, and then repeats the loop as long
as the specified condition is true.
o for - loops through a block of code a specified number of times.
o foreach - loops through a block of code for each element in an array.

4.16.1 while Loop


• The while loop executes a block of code as long as the specified condition is true.
• Syntax:
while (condition is true)
{
code to be executed;
}
Example:
<?php
$x = 1;
while($x<= 5)
{
echo "The number is: $x <br>";
$x++;
}
?>
Output:
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5

4.16.2 do..while Loop


• The do...while loop will always execute the block of code once, it will then check the

196
condition, and repeat the loop while the specified condition is true.
• Syntax:
do
{
code to be executed;
} while (condition is true);
• Example:
<?php
$x = 1;
do
{
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
Output:
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5

4.16.3 for Loop


• PHP for loops execute a block of code a specified number of times.
• The loop is used when you know in advance how many times the script should run.
• Syntax:
for (init counter; test counter; increment counter)
{
code to be executed;
}
• Parameters:
o init counter: Initialize the loop counter value.
o test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop
continues. If it evaluates to FALSE, the loop ends.
o increment counter: Increases the loop counter value.
• Example:
<?php
for ($x = 0; $x <= 10; $x++)
{
197
echo $x.""';
}
?>
Output:
012 3 4 5 6 7 8 9 10

4.16.4 foreach Loop


• The foreach loop works only on arrays, and is used to loop through each key/value
pair in an array.
• Syntax:
foreach ($array as $value)
{
code to be executed;
}
• For every loop iteration, the value of the current array element is assigned to $value
and the array pointer is moved by one, until it reaches the last array element.
• Example:
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value)
{
echo "$value <br>";
}
Output:
red
green
blue
yellow

4.17 Break and Continue


• The standard way to exit from a looping structure is for the main test condition to
become false.
• The special commands break and continue offer an optional side exit from all the
looping constructs, including while, do-while, and for.
• The break command exits the innermost loop construct that contains it.
• The continue command skips to the current iteration of the loop that contains it.
• Example (Break):
The following code prints the number 0 to 5.

198
<?php
$i = 0;
while ($i<100)
{
if ($i > 5)
break;
echo $i." ";
$i=$i+1;
}
?>
Output: 0 1 2 3 4 5 6

• Example (Continue):
The following code prints the number 0 to 9, except 5.
<?php
for ($i = 0; $i<10; $i++)
{
if ($i == 5)
{
continue;
}
echo $i." ";
}
?>
Output: 012346789

199
5.PHP CONCEPTS
5.1 Arrays
• An array is a single variable that can hold more than one value at once.
• You can think of an array as a list of values.
• Each value within an array is called an element, and each element is referenced by
its own index, which is unique to that array.
• To access an elements value – whether you are creating, reading, writing, or
deleting the element you use that elements index.

5.1.1 Types of Array


• In PHP, there are three types of arrays:
1) Indexed arrays (Numeric arrays) - Arrays with a numeric index.
2) Associative arrays - Arrays with named keys.
3) Multidimensional arrays (Nested arrays) - Arrays containing one or more arrays.

1) Indexed arrays (Numeric arrays)


• In numeric array each element having numeric key associated with it that is starting
from 0.
Creating Arrays
• You can use array() function to create array.
• Syntax: $array_name=array ( value1, value2 ...valueN);
• There are two ways to create indexed arrays.
• The index can be assigned automatically (index always starts at 0), like this: $cars =
array("Volvo", "BMW", "Toyota");
•The index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";

200
5.1.2 Functions of array:

Length of an Array
•The count() function is used to return the length (the number of elements) of an
array.
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
Output: 3

Accessing Array Elements


• The print_r() function is used to print information about a variable.
Example:
<?php
$myarray=array("A","B","C");
print_r($myarray);
?>
Output: Array ( [0] => A [1] => B [2] => C)
• You can refer to individual element of an array in PHP script using its key value as
shown below:
Example:
<?php
$myarray=array("A","B","C");
echo $myarray[1];
?>

Output: B

201
• In Numeric Array you can use for, while or do while loop to iterate through each
element in array because in numeric array key values are consecutive.

Changing Elements
• You can also change value of element using index.
Example:
<?php
$myarray=array("Apache", "MySQL", "PHP");
$myarray[1]="Oracle";
for($i=0; $i<3; $i++)
{
echo $myarray[$i]."<br>";
}
?>
Output: Apache Oracle PHP
Add Elements to Array
• The array_push() function inserts one or more elements to the end of an array.
Syntax: array_push(array,value1, value2...)
o array: Required. Specifies an array.
o value1: Required. Specifies the value to add.
o value2: Optional. Specifies the value to add.
Example:
<?php
$myarray=array("Apache", "MySQL", "PHP");
print_r($myarray);
echo '<br>";
$myarray[]="Oracle";
print_r($myarray);

202
echo "<br>";
array_push($myarray,"Java",".Net");
print_r($myarray);
?>
Output: Array ( [0] => Apache [1] => MySQL [2] =>PHP)
Array ( [0] => Apache [1] => MySQL [2] => PHP [3] => Oracle )
Array ( [0] => Apache [1] => MySQL [2] => PHP (3] => Oracle [4] => Java [5] =>.Net)

 Removing Elements from Arrays


• Unset() is used to destroy a variable in PHP. It can be used to remove a single
variable, multiple variables, or an element from an array.
Syntax: unset (var1, var2....)
o var1, var2: The variable to be unset.
Example:
<?php
$a = "Hello world!";
echo "The value of variable 'a' before unset:" . $a . "<br>";
unset($a);
echo "The value of variable 'a' after unset: ".$a;
?>
Output:
The value of variable 'a' before unset: Hello world!
The value of variable 'a' after unset:
You can remove the last element of an array using array_pop(). This will also return
that element:
Example:
<?php
$a=array("red","green","blue");
203
array_pop($a);
print_r($a);
?>

Output:
Array ( [0] => red [1] => green)
 Searching Element
• The array_search() function search an array for a value and returns the key.
• Syntax: array_search(value,array,strict)
o value: Required. Specifies the value to search for.
o array: Required. Specifies the array to search in.
o strict: Optional. If this parameter is set to TRUE, then this function will search for
identical elements in the array.
Example: <?php
$a=array("A"=>"5","B"=>5);
echo array_search(5,$a);
echo array_search(5,$a,true);
?>
Output:
A
B
• The in_array() function searches an array for a specific value.
• Syntax: in_array(search,array, type)
o search: Required. Specifies the what to search for
o array: Required. Specifies the array to search
o type: Optional. If this parameter is set to TRUE, the in_array() function searches for
the specific type in the array.
Example:
204
<?php
$people=array("Peter", "Joe", "Glenn", 23);
if (in_array("23",$people))
{
echo "Match found<br>";
}
else
{
echo "Match not found<br>";
}
if (in_array("23", $people, TRUE))
{
echo "Match found<br>";
}
else
{
echo "Match not found<br>";
}
?>
Output:
Match found
Match not found
 Sorting Array
• sort() - sort arrays in ascending order
• rsort() - sort arrays in descending order
• asort() - sort associative arrays in ascending order, according to the value
• ksort() - sort associative arrays in ascending order, according to the key

205
• arsort() - sort associative arrays in descending order, according to the value
• krsort() - sort associative arrays in descending order, according to the key
Example: <?php
$srtArray=array(2,8,9,5,6,3);
for ($i=0; $i<count($srtArray); $i++)
{
for ($j=0; $j<count($srtArray); $j++)
{
if ($srtArray[$j] > $srtArray[$i])
{
$tmp = $srtArray[$i];
$srtArray[$i] = $srtArray[$j];
$srtArray[$j] = $tmp;
}
}
}
foreach($srtArray as $item)
{
echo $item."<br>\n";
}
?>
Output: 235 6 8 9

Sort array using function. Example: <?php


$srtArray=array(2,8,9,5,6,3); sort($srtArray); foreach($srtArray as $item) {
echo $item."<br>\n";

206
Output: 235689

2) Associative Array
• The associative part means that arrays store element values in association with key
values rather than in a strict linear index order.
• If you store an element in an array, in association with a key, all you need to retrieve
it later from that array is the key value.
• Key may be either numeric or string.
• You can use array() function to create associative array.
• Syntax: $array_name=array(key1=>value1, key2=>value2...... keyN => valueN);
• There are two ways to create an associative array:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
OR
$age["Peter"] = "35";
$age["Ben"] = "37";
$age["Joe"] = "43";
You can refer to individual element of an array in PHP using its key value. Example:
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Ben:"$age["Ben");
?>
Output: Ben:37
• In associative array you cannot use for, while or do...while loop to iterate through
each element in array because in Associative array key value are not consecutive.
• So you have to use foreach loop.

Example: <?php
$myarray=array("Name"=>"James", "Age"=>25, "Gender"=>"Male");
foreach($myarray as $item) {

207
echo $item."<br>";

?>
Output: James
25

Male

3) Multidimensional Array
• Earlier, we have described arrays that are a single list of key/value pairs.
• However, sometimes you want to store values with more than one key.
• This can be stored in multidimensional arrays.
• A multidimensional array is an array containing one or more arrays.
• PHP understands multidimensional arrays that are two, three, four, five, or more
levels deep.
• First, take a look at the following table:

Example:
<?php
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
);
for ($row = 0; $row < 3; $row++)
{
echo "<br>";
for ($col = 0; $col < 3; $col++)
{
echo $cars($row][$col]." ";
}

208
}
5.2 User Defined Functions
• Besides the built-in PHP , we can create our own .
• A function is a block of statements that can be used repeatedly in a program.
• A function will not execute immediately when a page loads.
• A function will be executed by a call to the function.
 Create a User Defined Function
• A user defined function declaration starts with the word "function".
• Syntax:
function functionName()
{
Code to be executed;
}
Example: <?php
function write Msg()
{
echo "Hello world!";
}
writeMsg(); // call the function
?>
Output: Hello world!

 Function arguments and returning values from function


• Information can be passed to through arguments. An argument is just like a
variable.
• Arguments are specified after the function name; inside the parentheses separate
with comma.
Example:
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2; return $sum;
$result=addFunction (10, 20);
}
echo "Addition=".$result;
Output:
Addition=30
 Default values for arguments
• You can specify default values for arguments.
209
• If the argument is omitted from the function call the default is used.
• The default value must be a constant expression such as a string, integer or NULL.
• You can have multiple arguments with default values. Default values assign from
right to left.
Example:
<?php
function addFunction($num1, $num2=5)
{
$sum = $num1 + $num2;
return $sum;
}
$result=addFunction(10,20);
echo "Addition=".$result."<br>";
$result=addFunction(10);
echo "Addition=".$result;
Output:
Addition=30
Addition=15

 Call-by-Value (Pass-by-Value)
• The default behavior for user-defined in PHP is call-by-value.
• Call by value means passing the value directly to a function. The called function uses
the value in a local variable; any changes to it do not affect the source variable.
Example:
<?php
function swap($num1, $num2)
{
$temp = $num1;
$num1=$num2;
$num2=$temp;
}
$num1=10;
$num2=20;
echo "Before Swap"."<br>";
echo "num1="$num1.'<br>";
echo "num2=".$num2."<br>";
swap($num1,$num2);
echo "After Swap","<br>";
echo "num1=".$num1.'<br>";
210
echo "num2="$num 2.5<br>";
Output:
Before Swap num1=10 num2=20
After Swap num1=10 num2=20

 Call-by-Reference (Pass-by-Reference)
• Call by reference means passing the address of a variable where the actual value is
stored.
• The called function uses the value stored in the pass address; any changes to it do
affect the source variable.
Example:
<?php
function swap(&$num1, &$num2)
{
$temp = $num1;
$num1=$num2;
$num2=$temp;
}
$num1=10;
$num2=20;
echo "Before Swap"."<br>";
echo "num1="$num1.'<br>";
echo "num2="$num2."<br>";
swap($num1,$num2);
echo "After Swap"."<br>";
echo "num1="$num1."<br>";
echo "num2="$num 2."<br>";
?>
Output:
Before Swap num1=10 num2=20
After Swap num1=20 num2=10

5.3 Variables Scope


• In PHP, variables can be declared anywhere in the script.
• The scope of a variable is the part of the script where the variable can be
referenced/used.
• PHP has three different variable scopes:
211
o local
o global
ostatic
Local
• A variable declared within a function has a local scope and can only be accessed
within that function.
Example:
<?php
function myTest()
{
$x = 5; // local scope
echo "Variable x inside function is: $x";
}
myTest();
?>
Output:
Variable x inside function is: 5

Global Variable :
• A variable declared outside a function has a global scope and can only be accessed
outside a function.
• The global keyword is used to access a global variable from within a function.
• To do this, use the global keyword before the variables (inside the function). global
$x;
Example:
<?php
$x = 5; // global scope
function myTest()
{
}
myTest();
echo "Variable x outside function is: $x";
?>
Output:
Variable x outside function is: 5

Static Variable
212
• Normally, when a function is completed/executed, all of its variables are deleted.
• However, sometimes we want a local variable not to be deleted. We need it for a
further job.
To do this, use the static keyword when you first declare the variable.
Example:
<?php
function myTest()
{
static $x = 0;
echo $x;
$x++;
}
myTest();
echo "<br>";
myTest();
echo "<br>";
myTest();
?>
Output:
0
1
2
• Then, each time the function is called, that variable will still have the information it
contained from the last time the function was called.

5.4 String Function


chr
• Returns a character from a specified ASCII value.
• Syntax: chr(ascii)
Example:
<?php
echo chr(52). "<br>"; // Decimal value
echo chr(052). "<br>"; // Octal value
echo chr(0x52); // Hex value
Output:
213
4
*
R

ord

• Returns the ASCII value of the first character of a string.


• Syntax: ord(string)
• Example:
<?php
echo ord("A").'<br />";
echo ord("And");
?>
Output: 65 65

strtolower
• Converts a string to lowercase letters.
• Syntax: strtolower(string)
Example:
<?php
echo strtolower("HELLO");
?>
Output:
hello

strtoupper
• Converts a string to uppercase letters.
• Syntax: strtoupper(string)
Example:
<?php
echo strtoupper("hello");

214
?>
Output: HELLO

strlen
• Returns the length of a string.
• Syntax: strlen(string)
Example:
<?php
echo strlen("hello hi");
?>
Output: 8

Itrim
• Removes whitespace or other predefined characters from the left side of a string.
• Syntax: Itrim(string,charlist)
o charlist: Optional. Specifies which characters to remove from the string. o If
omitted, all of the following characters are removed:"\0" - NULL, "\t" – tab, "\n" - new
line,
"\XOB" - vertical tab, "\r" - carriage return, "" - white space. Example: <?php
$str="Hello"; echo Itrim($str, "H").'<br>"; $str=" Hello";
echo Itrim($str); ?> Output: ello Hello
rtrim
• Removes whitespace or other predefined characters from the right side of a string.
• Syntax: rtrim(string, charlist)
o charlist: Optional. Specifies which characters to remove from the string.
o If omitted, all of the following characters are removed:
"10" - NULL,
"\t" – tab,
"\n" - new line,
"\XOB" - vertical tab,
"\r" - carriage return,
"" - white space.
Example:
<?php
$str="Hello";
echo rtrim($str,"o").'<br>";
$str="Hello";
echo rtrim($str);
215
?>
Output: Hell Hello

trim
• Removes whitespace and other predefined characters from both sides of a string.
• Syntax: trim(string,charlist)
o charlist: Optional. Specifies which characters to remove from the string.
o If omitted, all of the following characters are removed:"\0" – NULL, "\t" – tab, "\n" –
new line, "\XOB" - vertical tab, "\r" - carriage return,"" - white space. Example:
<?php
$str="Hello";
echo trim($str,"o").'<br>";
$str=" Hello ";
echo trim($str);
?>
Output: Hell Hello

substr
• Returns a part of a string.
• Syntax: substr(string,start,length)
o start: Required. Specifies where to start in the string.
 A positive number - Start at a specified position in the string.
 A negative number - Start at a specified position from the end of the string.
 0- Start at the first character in string.
o length: Optional. Specifies the length of the returned string.
 Default is to the end of the string.
 A positive number - The length to be returned from the start parameter.
 Negative number - The length to be returned from the end of the string.
Example:
<?php
// Positive numbers:
216
echo substr("Hello world",0,10)."<br>";
echo substr("Hello world",1,8)."<br>";
echo substr("Hello world",0,5).'<br>";
echo substr("Hello world",6,6).'<br>";
echo "<br>";
// Negative numbers:
echo substr("Hello world",0,-1).'<br>";
echo substr("Hello world",-10,-2).'<br>";
echo substr("Hello world",0,-6).'<br>";
?>
Output:
Hello worl
ello wor
Hello
world
Hello worl
ello wor
Hello

strcmp
• Compares two strings (case-sensitive).
• strcmp function returns 0 - if the two strings are equal, negative - if string1 is less
than string2 and positive - if string1 is greater than string2.
• Syntax: strcmp(string1, string2)
Example:
<?php
echo strcmp("Hello world!","Hello world!").'<br>"; // the two strings are equal echo
strcmp("Hello world!","Hello")."<br>"; // string1 is greater than string2 echo
strcmp("Hello world!","Hello world! Hello!"); // string1 is less than string 2
Output:
0
7
-7

strcasecmp
• Compares two strings (case-insensitive)
• strcasecmp function returns: 0 - if the two strings are equal, negative - if string1 is
less than string2 and positive - if string1 is greater than string2.
• Syntax: strcasecmp(string1, string2)
217
Example:
<?php
echo strcasecmp("Hello world!","HELLO WORLD!").'<br>";
// The two strings are equal
echo strcasecmp("Hello world!", "HELLO")."<br>";
// String1 is greater than string 2
echo strcasecmp("Hello world!","HELLO WORLD! HELLO!");
// String1 is less than string2 ?>
Output:
0
7
-7
strpos
• Finds the position of the first occurrence of a string inside another string. (case-
sensitive)
• Syntax: strpos(string,find,start)
o string: Required. Specifies the string to search.
o find: Required. Specifies the string to find.
o start: Optional. Specifies where to begin the search.
Example:
<?php
echo strpos("hello","e");
echo strpos("hello","1");
echo strpos("hellohello","T",5);
?>
Output:
1
2
7
218
strrpos
• Finds the position of the last occurrence of a string inside another string. (case-
sensitive)
• Syntax: strrpos(string, find,start)
o string: Required. Specifies the string to search.
o find: Required. Specifies the string to find.
o start: Optional. Specifies where to begin the search.
Example:
<?php
echo strrpos("hello","l");
echo strrpos("hellohello","I", 5);
?>
Output:
3
5
strrpos
• Finds the position of the first occurrence of a string inside another string. (case-
insensitive)
• Syntax- stripos(string, find, start)
o string: Required. Specifies the string to search.
o find: Required. Specifies the string to find.
o start: Optional. Specifies where to begin the search.
Example:
<?php
echo stripos("hello","L");
echo stripos("hellohello", "L",4); ?>
Output:
2
219
7
strripos
• Finds the position of the last occurrence of a string inside another string. (case-
insensitive)
• Syntax:- strrpos(string, find,start)
o string: Required. Specifies the string to search.
o find: Required. Specifies the string to find.
o start: Optional. Specifies where to begin the search.
Example:
<?php
echo strripos("hello", "L");
echo strripos("hellohello","L",4);
?>
Output:
3
8
strstr
• Searches for the first occurrence of a string inside another string. (case-sensitive)
• Syntax: strstr(string,search, before_search)
o string: Required. Specifies the string to search.
o search: Required. Specifies the string to search for. If this parameter is a
number, it will search for the character matching the ASCII value of the number.
o before_search: Optional. A boolean value whose default is "false". If set to
"true", it returns the part of the string before the first occurrence of the search
parameter.
Example:
<?php
echo strstr("Hello world!",111);

220
echo strstr("Hello world!","wo");
echo strstr("Hello world!","world", true);
?>
Output:
o world!
world!
Hello
stristr
• Searches for the first occurrence of a string inside another string. (case-insensitive)
• Syntax: stristr(string,search)
o string: Required. Specifies the string to search.
o search: Required. Specifies the string to search for. If this parameter is a
number, it will search for the character matching the ASCII value of the number.
o before_search: Optional. A boolean value whose default is "false". If set to
"true", it returns the part of the string before the first occurrence of the search
parameter.
Example:
<?php
echo stristr("Hello world!",87);
echo stristr("Hello world!","WO");
echo stristr("Hello world!","WORLD", true);
?>
Output: world! world! Hello
str_replace
• Replaces some characters in a string (case-sensitive).
• Syntax: str_replace(find,replace,string,count)
o find: Required. Specifies the value to find
o replace: Required. Specifies the value to replace the value in find

221
o string: Required. Specifies the string to be searched
o count: Optional. A variable that counts the number of replacements Example:
<?php
echo str_replace("world","Peter","Hello world!");
?>
Output: Hello Peter!
strrev
• Reverses a string.
• Syntax: strrev(string)
Example:
<?php
echo strrev("hello");
?>
Output: olleh

5.5 Math Function


abs
• Returns the absolute (positive) value of a number.
Syntax: abs(number)
Example: <?php
echo abs(-6.7).'<br>";
echo abs(-3);
?>
Output:
6.7
3
ceil
• Rounds a number UP to the nearest integer, if necessary.

222
Syntax: ceil(number)
Example: <?php
echo ceil(0.60).'<br>";
echo ceil(5)."<br>";
echo ceil(-4.9);
?>
Output:
1
5
-4
floor
• Rounds a number DOWN to the nearest integer, if necessary.
• Syntax: floor(number)
Example:
<?php
echo floor(0.60)."<br>";
echo floor(5).'<br>";
echo floor (4.9);
?>
Output:
0
5
4
round
• Rounds a floating-point number.
• Syntax: round(number,precision)
o precision: Optional. The number of digits after the decimal point

223
Example: <?php
echo round(5.335,2).'<br>";
echo round(0.49);
?>
Output:
5.34
0
fmod
• Returns the remainder (modulo) of x/y.
Syntax: fmod(x,y)
Example: <?php
echo fmod(5,2);
?>
Output: 1
min
• Returns the number with the lowest value from specified numbers.
• Syntax: min(x1,x2,X3...) Or min(array_values)
Example:
<?php
echo min(-2,4,-6,8,10). "<br>";
echo min(array(4,6,8,10));
?>
Output:
-6
4
max
• Returns the number with the highest value from specified numbers.

224
• Syntax: max(x1,x2,X3...) Or max(array_values)
Example:
<?php
echo max(-2,4,-6,8,10). "<br>";
echo max(array(4,6,8,10));
?>
Output:
10
10
pow
• Returns the value of x to the power of y.
Syntax: pow(x,y) Example: <?php
echo pow(5,2);
?>
Output:
25
sqrt
• Returns the square root of a number x.
• Syntax: sqrt(number)
Example: <?php
echo sqrt(25);
Output: 5
rand
• Returns a random integer.
• Syntax: rand() or rand(min, max)
o min: Optional. Specifies the lowest number to be returned. Default is 0.
o max: Optional. Specifies the highest number to be returned. Default is

225
getrandmax().
Example:
<?php
echo rand().'<br>";
echo rand(40,500); ?>
Output:
18269
417

5.6 Date Function


date
• Formats a local date and time, and returns the formatted date string.
• Syntax: date(format, timestamp)
o format: Required. Specify the format of date and time to be returned.
 d - The day of the month (from 01 to 31)
 m - A numeric representation of a month (from 01 to 12)
 M-A short textual representation of a month (three letters)
 Y - A four digit representation of a year
 y - A two digit representation of a year
o timestamp: Optional. Specifies the time in Unix time format. Default is the
current local time (time()).
Example:
<?php
echo date('d/m/y")."<br>";
echo date("d M, Y");
?>
Output:
11/08/15
11 Aug, 2015
getdate
226
• Returns date/time information of a timestamp or the current local date/time.
• The returning array contains ten elements with relevant information needed when
formatting a date string:
[seconds] – seconds,
[minutes] – minutes,
[hours] – hours,
[mday] - day of the month,
[wday] - day of the week,
[year] – year,
[yday] - day of the year,
[weekday] - name of the weekday,
[month] - name of the month.
Syntax: getdate(timestamp)
o timestamp: Optional. Specifies the time in Unix time format. Default is the current
local time (time()).
Example:
<?php
print_r (getdate());
?>
Output:
Array ( [seconds] => 3 [minutes] => 49 [hours] =>17 [mday] => 11 [wday] => 2 [mon]
=> 8 [year] => 2015 [yday] => 222 [weekday] => Tuesday [month] => August [0] =>
1439308143 )
checkdate
• The checkdate() function accepts the month, day, year of a date as parameters and,
verifies whether it is a Gregorian date or not.
• Syntax: checkdate(month,day, year)
o month, day, year: Required. Specifies the month, day and year.
o A date is valid if: month is between 1 to 12 , day is within the allowed number of
227
days for the particular month, year is between 1 to 32767.
Example:
<?php
var_dump(checkdate(12,31,-400)); echo "<br>"; var_dump(checkdate(2,29,2003));
echo "<br>";
var_dump(checkdate(2,29,2004));
?>
Output:
bool(false)
bool(false)
bool(true)
time
• Returns the current time in the number of seconds (since January 1 1970 00:00:00
GMT).
Syntax: time()
Example:
<?php
echo time();
?>
Output: 1439309922
mktime
• The mktime() function returns the Unix timestamp for a date.
• This timestamp contains the number of seconds between the Unix Epoch (January 1
1970 00:00:00 GMT) and the time specified.
• Syntax: mktime (hour, minute,second,month,day, year,is_dst)
o hour, minute, second, month, day, year: Optional. Specifies the hour, minute,
second, month, day, year.
o is_dst: Optional. Set this parameter to 1 if the time is during daylight savings time
(DST), O if it is not, or -1 (the default) if it is unknown. This parameter is removed in
PHP 7.0.
228
Example:
<?php
echo(date("M-d-Y", mktime(0,0,0,12,36,2001)). "<br />");
echo(date("M-d-Y",mktime(0,0,0,1,1,99)));
?>
Output: Jan-05-2002 Jan-01-1999

5.7 File Function


fopen0
• The fopen() function opens a file or URL.
• If fopen() fails, it returns FALSE and an error on failure.
• Syntax: fopen(filename,mode)
o filename: Required. Specifies the file or URL to open
o mode: Required. Specifies the type of access you require to the file/stream.
 "r" (Read only. Starts at the beginning of the file)
 "r+" (Read/Write. Starts at the beginning of the file)
 "w" (Write only. Opens and clears the contents of file; or creates a new file if it
doesn't exist)
 "w+" (Read/Write. Opens and clears the contents of file; or creates a new file if
it doesn't exist)
 "a" (Write only. Opens and writes to the end of the file or creates a new file if it
doesn't exist)
 "a+" (Read/Write. Preserves file content by writing to the end of the file)
Example:
<?php
$file = fopen("test.txt","r");
?>

fwrite()
• The fwrite() writes to an open file.
229
• The function will stop at the end of the file or when it reaches the specified length,
whichever comes first.
• This function returns the number of bytes written, or FALSE on failure.
•Syntax: fwrite(file,string, length)
o file: Required. Specifies the open file to write to
o string: Required. Specifies the string to write to the open file
o length: Optional. Specifies the maximum number of bytes to write
Example:
<?php
$file = fopen("test.txt","w");
echo fwrite($file, "Hello World. Testing!");
fclose($file);
?>

fread()
• The fread() reads from an open file.
• Syntax: fread(file, length)
o file: Required. Specifies the open file to read from
o length: Required. Specifies the maximum number of bytes to read
Example:
<?php
$file = fopen("test.txt","r");
fread($file,"10");
fclose($file);
?>
fclose()
• The fclose() function is used to close an open file.

230
• The fclose() requires the name of the file (or a variable that holds the filename).
Syntax: fclose(file)
Example: <?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>

231
6.Advanced PHP
6.1 $_GET and $_POST method
• There are two ways the browser client can send information to the web server.
o The GET Method
o The POST Method
• Both GET and POST create an array (e.g. array ( key => value, key2 => value2, key3
=> value3, ...)).
• This array holds key/value pairs, where keys are the names of the form controls and
values are the input data from the user.
• Both GET and POST are treated as $_GET and $_POST. These are superglobals,
which means that they are always accessible, regardless of scope - and you can access
them from any function, class or file without having to do anything special.
• $_GET is an array of variables passed to the current script via the URL parameters.
• $_POST is an array of variables passed to the current script via the HTTP POST
method.

The GET Method


 Information sent from a form with the GET method is visible to everyone (all
variable names and values are displayed in the URL).
 GET also has limits on the amount of information to send. The limitation is
about 2000 characters.
 However, because the variables are displayed in the URL, it is possible to
bookmark the page. This can be useful in some cases.
 GET may be used for sending non-sensitive data.
 GET can't be used to send binary data, like images or word documents, to the
server.
 It is not secure but fast and quick.
 When you are using GET method in the form collection element the
information will be send to the destination file through URL using the concept
of Query String.
 Collection of names and value pairs is called query string. Name and value
separated by ampersand (&) sign.
name1=value1&name2=value2&name3=value3

232
 Every query string starts with in URL.
 Data is limited to max length of query string.
 Note: GET should NEVER be used for sending passwords or other sensitive
information!
Submitting and accessing form value using GET
OR Passing variable through URL
Example
<html>
<body>
<form action="welcome_get.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
welcome_get.php
<html>
<body>
<?php
$name=$_GET['name'];
$email= $_GET['email'];
echo "welcome "$name."<br>";
echo "Your email address is: ".$email;
?>
</body>
</html>
The output could be something like this: Welcome Peter

233
Your email address is: [email protected]
The POST Method
 Information sent from a form with the POST method is invisible to others (all
names/values are embedded within the body of the HTTP request).
 POST has no limits on the amount of information to send.
 However, because the variables are not displayed in the URL, it is not possible
to bookmark the page.
 The POST method can be used to send ASCII as well as binary data.
 POST may be used for sending sensitive data.
 It is more secured but slower as compared to GET.
 It can post unlimited form variables.
Submitting and accessing form value using POST
Example
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
 When the user fills out the form above and clicks the submit button, the form
data is sent for processing to a PHP file named "welcome.php".
 The form data is sent with the HTTP POST method.
 To display the submitted data you could simply echo all the variables. The
"welcome.php" looks like this:
welcome.php
<html>
<body>
<?php

234
$name=$_POST['name'];
$email= $_POST['email'];
echo "welcome ".$name."<br>";
echo "Your email address is: ".$email;
?>
</body>
</html>
The output could be something like this: Welcome Peter
Your email address is: [email protected]

6.2 The $ REQUEST variable


 The PHP $_REQUEST variable contains the contents of both $_GET, $_POST,
and $_COOKIE.
 The PHP $_REQUEST variable can be used to get the result from form data sent
with both the GET and POST methods.
 Example
<html>
<body>
<form action = "ProcessRequest.php" method = "POST">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>
ProcessRequest.php
<?php
echo "Welcome ". $_REQUEST['name'). "<br />";
echo "You are". $_REQUEST['age'). " years old.";
235
?>
Output: Welcome Peter You are 31 years old.

6.3 PHP Cookie


 A cookie is a small text file that lets you store a small amount of data on the
user's computer.
 They are typically used to keeping track of information such as username that
the site can retrieve to personalize the page when user visit the website next
time.
 Each time the browser requests a page to the server, all the data in the cookie
is automatically sent to the server within the request.
Creating Cookie
 In PHP you can create cookie using setcookies() function.
 Syntax: setcookie(name, value, expire time, path, domain, secure, httponly) o
Name - specify name of cookie that you want to create.
o Value - value that is associated with the cookie created by you.
o Expire time - Expire time is time when cookie will expire and deleted. It is an
optional.
o Path - this specifies the directories for which the cookie is valid.
o Domain - The domain represents the Internet domain from which cookie-
based communication
o Secure - This can be set to 1 to specify that the cookie should only be sent by
secure transmission using HTTPS otherwise set to o which mean cookie can be
sent by regular HTTP.
 Note: The setcookie() function must appear BEFORE the <html> tag.
Example
CreateCookies.php
<?php
setcookiel'cookiename','cookievalue', time()+60*60*24*5);
echo "Cookie is set";
?>
Retrieve Cookie/ Accessing Cookies Values
 The PHP $_COOKIE variable is used to retrieve a cookie value.
 In the example below, we retrieve the value of the cookie named "username"
and display it on a page.

236
Example
Retrieve Cookies.php
<?php
$cookiename =$_COOKIE['cookiename'];
echo "Cookie named:".$cookiename;
?>
In the following example we use the isset() function to find out if a cookie has been
set.
Retrieve Cookies.php
<?php
if(isset($_COOKIE['cookiename ']))
echo " Cookie ".$_COOKIE[' cookiename '). " is not set!" ;
else
echo " Cookie".$_COOKIE['cookiename ']." is set!";
?>
Removing Cookie/ Delete Cookie
• When deleting a cookie you should assure that the expiration date is in the past.
Delete Cookies.php
<?php
setcookies' cookiename '' cookievalue', time()-60*60*24*5);
echo "Cookie is deleted";
?>

6.4 PHP Session

 A PHP session variable is used to store information about, or change settings


for a user session.
 Session variables hold information about one single user, and are available to
all pages in one application.

237
PHP Session Variables
 When you are working with an application, you open it, do some changes and
then you close it.
 This is much like a Session. The computer knows who you are. It knows when
you start the application and when you end.
 But on the internet there is one problem: the web server does not know who
you are and what you do because the HTTP address doesn't maintain state.
 A PHP session solves this problem by allowing you to store user information on
the server for later use (i.e. username, shopping items, etc). However, session
information is temporary and will be deleted after the user has left the website.
If you need a permanent storage you may want to store the data in a database.
 Sessions work by creating a unique id (UID) for each visitor and store variables
based on this UID. The UID is either stored in a cookie or is propagated in the
URL.

Starting Session
 Before you can store user information in your PHP session, you must first start
up the session.
 A session is started with the session_start() function.
 The session_start() function must appear BEFORE the <html> tag.
<?php
session_start();
?>
<html>
<body>
</body>
</html>
 The code above will register the user's session with the server, allow you to
start saving user information, and assign a UID for that user's session.

Creating session variable


 The correct way to store and retrieve session variables is to use the PHP
$_SESSION variable.
 Syntax: $_SESSION['variableName"]=Value;
 Example
Session Demo.php
<html>

238
<head>
<title>Session Demo</title>
</head>
<body>
<form name="formname" method="POST" action="SessionDemo Process.php">
User Name:<input type="text" name="username"/><br/>
Password:<input type="password" name="pass"/><br/>
<input type="submit" name="submit" value="Save"/>
</form>
</body>
</html>
SessionDemo Process.php
<?php
Session_start();
$uname = $_POST['username'];
$pwd = $_POST['pass'];
if($uname=="admin" and $pwd=="123")
{
$_SESSION['username']=$uname;
header(“location:Welcome.php?un=”$_SESSION[‘ username’]);
}
else
{
echo "enter correct username and password";
}
?>
Welcome.php
<?php
Session_start();
if(isset($_SESSION['username']))
echo "Welcome:".$_SESSION['username'];
else
header("location:SessionDemo.php");
239
?>
<html>
<head>
<title>Session Demo</title>
</head>
<body>
<a href="Logout.php">Logout</a>
</body>
</html>

Destroying a Session
 If you wish to delete some session data, you can use the unset() or the
session_destroy() function.
 The unset() function is used to free the specified session variable.
 You can also completely destroy the session by calling the session_destroy()
function.
 Note: session_destroy() will reset your session and you will lose all your stored
session data.
 Example Logout.php
<?php
Session_start();
session_destroy();
header("location:Session Demo.php");
?>
6.5 MySQL
- MySQL is a database system used on the web
- MySQL is a database system that runs on a server
- MySQL is ideal for both small and large applications
- MySQL is very fast, reliable, and easy to use
- MySQL uses standard SQL
- MySQL compiles on a number of platforms
- MySQL is free to download and use
- MySQL is developed, distributed, and supported by Oracle Corporation

The data in a MySQL database are stored in tables. A table is a collection of


related data, and it consists of columns and rows.

Databases are useful for storing information categorically. A company may have
a database with the following tables:

Employees
240
Products
Customers
Orders

6.6 PHP + MySQL Database System


PHP combined with MySQL are cross-platform (you can develop in Windows
and serve on a Unix platform)

Database Queries
 A query is a question or a request.
 We can query a database for specific information and have a recordset
returned. Look at the following query (using standard SQL):
 SELECT LastName FROM Employees
 The query above selects all the data in the "LastName" column from the
"Employees" table.

SQL DML Statements (insert, select, update, delete) commands

DML is short name of Data Manipulation Language which deals with data
manipulation and includes most common SQL statements such SELECT, INSERT,
UPDATE, DELETE, etc., and it is used to store, modify, retrieve, delete and
update data in a database.

6 SELECT - retrieve data from a database


7 INSERT - insert data into a table
8 UPDATE - updates existing data within a table
9 DELETE - Delete all records from a database table

9.3 Select statement


A select statement is used for select one or more records form table.
Syntax:
SELECT column_name(s) FROM table_name;
Ex1.
Select id, name from students;
This statement returns all students record with id and name fields.
Ex2.
Select * from students;
This statement returns all students record with all fields.
Ex3.
Select * from students where city=”Rajkot”;
241
This statement returns all students record who are belong from rajkot.

9.4 Insert Statement


This statement is used for insert new record in table.
Syntax:
INSERT INTO table_name (column, column1, column2,
column3, ...) VALUES (value, value1, value2, value3 ...)
Ex1.
Insert into students(id,name) values(002,”Rohan”);
This statement insert new record in students table with id=002 and name=rohan.
Ex2.
Insert into students values(220,”rohit”,”mvr”,124567);
This statement insert new record in students table with all fields.
Note: while we cannot declare fields name before VALUES keyword we need
to give all fields values inside VALUES().

9.5 update statement


This statement is used to update table record.
Syntax:
UPDATE table_name SET column=value,
column1=value1,...WHERE someColumn=someValue

Ex1. Update students set id=02 where id=002

9.6 delete Statement


This statement is used to delete record from
table. Syntax:
DELETE FROM tableName
WHERE someColumn = someValue
Ex1.
Delete from students;
This statement deletes all record from students table.

Ex2.
Delete from students where id=02
This statement delete all record with id=02

6.7 Database
A database is a separate application that stores a collection of data.
Other kinds of data stores can be used, such as files on the file system or large
hash tables in memory but data fetching and writing would not be so fast and
easy with those types of systems.

242
So nowadays, we use relational database management systems (RDBMS) to
store and manage huge volume of data. This is called relational database
because all the data is stored into different tables and relations are established
using primary keys or other keys known as foreign keys.
A Relational DataBase Management System (RDBMS) is a software that −
 Enables you to implement a database with tables, columns and indexes.
 Guarantees the Referential Integrity between rows of various tables.
 Updates the indexes automatically.
 Interprets an SQL query and combines information from various tables.

6.8 RDBMS Terminology


Before we proceed to explain MySQLi database system, let's revise few
definitions related to database.
 Database − A database is a collection of tables, with related data.
 Table − A table is a matrix with data. A table in a database looks like a
simple spreadsheet.
 Column − One column (data element) contains data of one and the
same kind, for example the column postcode.
 Row − A row (= tuple, entry or record) is a group of related data, for
example the data of one subscription.
 Primary Key − A primary key is unique. A key value cannot occur twice
in one table. With a key, you can find at most one row.
 Foreign Key − A foreign key is the linking pin between two tables.
 Compound Key − A compound key (composite key) is a key that
consists of multiple columns, because one column is not sufficiently
unique.

6.9 MySQLi

MySQLi is a Relational SQL database management system. MySQLi is used


inside the PHP programming language to give an interface with MySQL
databases.

6.9.1 MySQLi Database


MySQLi is a fast, easy-to-use RDBMS being used for many small and big
businesses. MySQLi Extension is developed, marketed, and supported by
243
MySQL. MySQL is becoming so popular because of many good reasons −
 MySQLi is released under an open-source license. So you have nothing
to pay to use it.
 MySQLi is a very powerful program in its own right. It handles a large
subset of the functionality of the most expensive and powerful database
packages.
 MySQLi uses a standard form of the well-known SQL data language.
 MySQLi works on many operating systems and with many languages
including PHP, PERL, C, C++, JAVA, etc.
 MySQLi works very quickly and works well even with large data sets.
 MySQLi is very friendly to PHP, the most appreciated language for web
development.
 MySQLi supports large databases, up to 50 million rows or more in a table.
The default file size limit for a table is 4GB, but you can increase this (if
your operating system can handle it) to a theoretical limit of 8 million
terabytes (TB).
 MySQLi is customizable. The open-source GPL license allows
programmers to modify the MySQL software to fit their own specific
environments.
6.9.1 MySQLi Functions:

1)mysqli_connect()
PHP provides mysqli_connect() function to open a database connection. This
function takes five parameters and returns a MySQLi link identifier on success or
FALSE on failure.
Syntax:
connection mysqli_connect(server, user, passwd, new_link, client_flag);

Parameters & description


- 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.
- passwd: Optional - The password of the user accessing the database. If not
specified, then default is an empty password.
- new_link: Optional - If a second call is made to mysqli_connect() with the
same arguments, no new connection will be established; instead, the
identifier of the already opened connection will be returned.
- client_flags: Optional - A combination of the following
244
constants – MYSQLI_CLIENT_SSL - Use SSL encryption
MYSQLI_CLIENT_COMPRESS - Use compression protocol
MYSQLI_CLIENT_IGNORE_SPACE - Allow space after function
names
MYSQLI_CLIENT_INTERACTIVE - Allow interactive timeout seconds of inactivity
before closing the connection
You can disconnect from MySQLi database anytime using another PHP function

2)mysqli_close().
This function takes a single parameter, which is a connection returned by
mysqli_connect() function.
mysqli_close() Function closes a previously opened database connection.
Syntax:
bool mysqli_close ( resource $connection );

Example:
<?php
$servername = "localhost:3306";
$username = "root";
$password = "";
$dbname = "hvcdb";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(!$conn )
{
die('Could not connect: ' . mysqli_error($conn));
}
else
{
echo 'Connected successfully';
}
mysqli_close($conn);
?>
3)mysqli_select_db()
This function is used to change the default database for the connection.

Syntax:
mysqli_select_db(connection, dbname);
245
Parameter & Description
- connection: Required. Specifies the MySQL connection to use
- dbname: Required. Specifies the default database to be used

Example
<?php
$con=mysqli_connect("localhost","root","","hvcdb");
// ...some PHP code for database " hvcdb "...
// Change database to "test"
mysqli_select_db($con,"test");
// ...some PHP code for database "test"...
mysqli_close($con);
?>
4)mysqli_query()
This function performs a query against the database.

Syntax:
mysqli_query(connection, query, resultmode);

Parameter & Description


- connection: Required. Specifies the MySQL connection to use
- query: Required. Specifies the query string
- resultmode: Optional. A constant. Either:
MYSQLI_USE_RESULT (Use this if we have to retrieve large amount of data)
MYSQLI_STORE_RESULT (This is default)

Example:
<?php
$con=mysqli_connect("localhost","root","","hvcdb");
// Perform queries
mysqli_query($con,"INSERT INTO students (FirstName,LastName,Age)
VALUES ('Karan','Chauhan',22)");
mysqli_close($con);
?>

5)mysqli_affected_rows()
This function returns the number of affected rows in the previous SELECT,
246
INSERT, UPDATE, REPLACE, or DELETE query.

Syntax:
mysqli_affected_rows(connection);

Parameters & description


- connection: Required. Specifies the MySQL connection to use

Example:
<?php
$con=mysqli_connect("localhost","root","","hvcdb");
// Perform queries and print out affected rows
mysqli_query($con,"SELECT * FROM students");
echo "Affected rows: " . mysqli_affected_rows($con);
mysqli_query($con,"DELETE FROM students WHERE Age > 22");
echo "Affected rows: " . mysqli_affected_rows($con);
mysqli_close($con);
?>

6)mysqli_num_rows()
This function returns the number of rows in a result set.

Syntax:
mysqli_num_rows(result);
Parameter & Description
- result: Required. Specifies a result set identifier returned by mysqli_query()

Example:
<?php
$con=mysqli_connect("localhost","root","","hvcdb");
$sql="SELECT Lastname,Age FROM students ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set

247
$rowcount = mysqli_num_rows($result);
echo "total record =".$rowcount;
}
mysqli_close($con);
?>

7)mysqli_fetch_array()
This function fetches a result row as an associative array, a numeric array,
or both. Note: Fieldnames returned from this function are case-sensitive.

Syntax:
mysqli_fetch_array(result,resulttype);

Parameter & Description


- result Required. Specifies a result set identifier returned by mysqli_query()
- resulttype Optional. Specifies what type of array that should be produced.
Can be one of the following values:
MYSQLI_ASSOC
MYSQLI_NUM
MYSQLI_BOTH

Example:
<?php
$con=mysqli_connect("localhost","root","","hvcdb");
$sql="SELECT Firstname,Age FROM students";
$result=mysqli_query($con,$sql);
// Numeric array
$row=mysqli_fetch_array($result,MYSQLI_NUM);
echo "Result by using MYSQLI_NUM : ".$row[0]."(".$row[1].")<br>";
// Associative array
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
echo "Result by using MYSQLI_ASSOC :".$row["Firstname"]."(".$row["Age"].")<br>";

248
// Both way : Associative array & Numeric Array
$row=mysqli_fetch_array($result,MYSQLI_BOTH);
echo "Result by using MYSQLI_BOTH : ".$row["Firstname"]."(".$row[1].")";
mysqli_close($con);
?>

8)mysqli_fetch_assoc()
The mysqli_fetch_assoc() function fetches a result row as an associative array.
Note: Fieldnames returned from this function are case-sensitive.

Syntax:
mysqli_fetch_assoc(result);

Parameter & Description


- result: Required. Specifies a result set identifier returned by mysqli_query().

Example:
<?php
$con=mysqli_connect("localhost","root","","hvcdb");
$sql="SELECT Lastname,Age FROM students ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))
{
while ($row=mysqli_fetch_assoc($result))
echo "Result by using mysqli_fetch_assoc :
".$row["Lastname"]."(".$row["Age"].")<br>";
}
mysqli_close($con);
?>
9)mysqli_fetch_object()
The mysqli_fetch_object() function returns the current row of a result set, as
an object. Note: Fieldnames returned from this function are case-sensitive.

Syntax:
mysqli_fetch_object(result, classname, params);

249
Parameter & Description:
- result: Required. Specifies a result set identifier returned by mysqli_query().
- classname: Optional. Specifies the name of the class to instantiate, set the
properties of, and return
- params: Optional. Specifies an array of parameters to pass to the
constructor for classname objects

Example:
<?php
$con=mysqli_connect("localhost","root","","hvcdb");
$sql="SELECT Lastname,Age FROM students ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))
{
while ($obj = mysqli_fetch_object($result))
echo "Result by using mysqli_fetch_object() : ".$obj->Lastname."(".$obj->Age.")<br>";
}
mysqli_close($con);
?>
10)mysqli_fetch_row()
This function fetches one row from a result-set and returns it as an enumerated
array.

Syntax:
mysqli_fetch_row(result);

Parameter & Description


- result: Required. Specifies a result set identifier returned by mysqli_query().

Example:
<?php
$con=mysqli_connect("localhost","root","","hvcdb");
$sql="SELECT Lastname,Age FROM students ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))

250
{ // Fetch one and one row
while ($row=mysqli_fetch_row($result))
echo "Result by using mysqli_fetch_row() : ".$row[0]."(".$row[1].")<br>";
}
mysqli_close($con);
?>

11)mysqli_prepare()
Prepares an SQL statement for execution

Syntax:
mysqli_prepare ( mysqli $connection , string $query )

Example:
<?php
$con=mysqli_connect("localhost","root","","hvcdb");
$stmt = $con->prepare("INSERT INTO students (FirstName,LastName,Age)
VALUES(?,?,?);");
$fname="kishan";
$lname = "raval";
$age = 32;
$stmt->bind_param("ssi",$fname,$lname,$age);
$stmt->execute()or die("error".mysqli_error($con));
echo "New record created successfully";
$stmt->close();
mysqli_close($con);
?>

12)mysqli_fetch_field()
It returns an array of objects containing column in a result set

Syntax:
mysqli_fetch_field(result)

251
Parameter & Description
Result - It specifies the result set identifier returned by mysqli_query

Example
<?php
$con=mysqli_connect("localhost","root","","hvcdb");
$sql = "SELECT Firstname,Lastname FROM students";
if ($result = mysqli_query($con,$sql))
{
$fieldinfo = mysqli_fetch_fields($result);
foreach ($fieldinfo as $val)
{
echo "first field=".$val->name; echo "<br>";
echo "second field=".$val->max_length; echo "<br>";
}
}
mysqli_close($con);
?>
13)mysqli_num_fields()
It returns the number of fields in a result set.

Syntax:
mysqli_num_field(mysqli_result $result)

Parameter & Description


Result - It is a result set identifier returned by mysqli_query().

Example
<?php
$con=mysqli_connect("localhost","root","","hvcdb");
$sql = "SELECT * FROM students";
if ($result = mysqli_query($con,$sql))

252
{
$fieldcount = mysqli_num_fields($result);
echo “total fields in result is=”.$fieldcount;
}
mysqli_close($con);
?>

14)mysqli_data_seek()
It is used to move internal result pointer.

Syntax:
mysqli_data_seek(result, row_number)

Parameter & Description


Result - It specifies result set of identifiers
Offset- It specifies the field offset. It should be between 0 and the total number
of rows - 1

Example
<?php
$con=mysqli_connect("localhost","root","","hvcdb");
$sql = "SELECT * FROM students";
$result = mysqli_query($con,$sql);
mysqli_data_seek($result,2);
print_r(mysqli_fetch_row($result));
mysqli_close($con);
?>

15)mysqli_error()
It returns a list of errors from the last connection

Syntax:
mysqli_data_seek(connection)

Parameter & Description


connection- It specifies the MySQL connection to use

Example
<?php
253
$con=mysqli_connect("localhost","root","","hvcdb”);
$sql = "SELECT * FROM students";
$result = mysqli_query($sql,$con) or die(“error is=”.mysqli_error($con));
mysql_close($connection_mysql);
?>

16)mysqli_errno()
It returns the error code for the most recent function call.

Syntax:
mysqli_errno(connection)

Parameter & Description


connection- It specifies the MySQL connection to use

Example
<?php
$con=mysqli_connect("localhost","root","","hvcdb");
$sql = "SELECT * FROM students";
$result = mysqli_query($con,$sql) or die("error is=".mysqli_errno($con));
mysql_close($connection_mysql);
?>

6.10 PHP Regular Expressions


 Regular expression means the formula or the general format of any string, or
expression. It is used for pattern matching.
 It is also known as regexis. It check any characters or digits which are
specified in the format. It is used generally for the validation on server-side
scripting.

 Advantages:
- it prevents the data to be entered in invalid format.
- it is a portable languages as it has general format.
- it is easy to learn and use.

 Disadvantages:
- the validation which is provided using server side scripting is
disadvantages, as the web page is refreshed again and again.
254
- one can easily create a binary image file from the file having PERL regular
expression.
- one has to verify whether the PERL is installed for PERL regular expression or
not.

6.10.1 Types of regular expressions


There are two types of regular expression in php
1. POSIX Extended Regular Expression.
2. Perl Compatible Expression.

1. POSIX Extended Regular Expression


When this type of regular expression is used then the function ereg() is required to
be used for pattern matching. The function ereg is abbreviated as extended regular
expression. It is the oldest type of regular expression in use.

There are different symbols used which are given below.


Symbol Description
^ For starting the format string
$ For ending the format string
[a-z] Only lower case alphabets
[A-Z] Only upper case alphabets
[a-z A-Z] Only alphabets in any case
[0-9] Only digits
[a-z A-Z 0-9] Alphanumeric character
\ Used when any special characters are to be used in the string
() Used when more than one value is to be checked
| For or condition
{n} Is used when the lengths of the digits are known. Where n is
an integ value
{n,m} N for minimum value and m for maximum value

Above shown are the general symbols, the other symbols used in the format are as
shown below.
* One or more times.
+ Zero or more times
? Zero or one time

When the format which is matched is not found, then it returns as false otherwise it
would have returned as true value.

Syntax:
boolean ereg(“format”, variable/ value to be checked)

255
Example:
Lets take the validation for date having the format dd/mm/yyyy format.
<?php
$date="13/02/2020";
$indate="13/02/20";
if(ereg("^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$",$date))
{
echo "valid date";
}
else
{
echo "invalid date";
}
if(ereg("^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$",$indate))
{
echo "valid date";
}
else
{
echo "invalid date";
}
?>

256
2. Perl Compatible Regular Expression
 This type of regular expression is developed using the perl language. The
function which is used for the given regular expression is preg_match() that
is perl regular expression.
 The symbols are used as the above ones only. It also return the Boolean
value. If the format is matched, then it returns true value otherwise will
return false value.
 There are different symbols used which are given as below.
Symbol Description
\d Any number
\D Fir anything other than a number
\s Any kind of whitespace
\S Anything other than whitespace
\W Any word character (including the underscore character)
\w Anything other than word character
\A Beginning of string
\b Word boundary
\B Not a word boundary
\Z End of string (matches before final new line or at end of string)
\z End of string (matches only at the very end of the string)

Syntax:
Boolean preg_match(“format”, variable/value to be checked)

Example:
<?php
$date="13/02/2020";
$indate="13/02/20";
if preg_match(('^\d{2}\/\d{2}\/\d{4}^',$date))
{
Echo”valid date”
}
Else
{
Echo “invalid date”
}
?>

General format using ereg function


- Email address
^[0-9 a-z A-Z]+(.|_)? [0-9 a-z A-Z]*\@(yahoo|gmail|co|in|rediff)\.(com|in)$
- Pin-code
^[0-9]{5,6}$
- mobile number starting with +91
^\+91[0-9]{10}$
- Land line number
^]0-9]{4,5}\-[0-9]{7}$

General format using preg_match function


- Email address
^\S+(.|_)? \S*\@(yahoo|gmail|co|in|rediff)\.(com|in)$
- Pin-code
^\d{5,6}$
- mobile number starting with +91
^\+91\d{10}$
- Land line number
^\d{4,5}\-\d{7}$

Email address validation example:


<?php
$email="[email protected]";
if(preg_match('^\S+(.|_)?\S*\@(yahoo|gmail|co|in|rediff)\.(com|in)^',$date))
{
echo”valid email address”
}
else
{
echo”invalid email address”

258
}
?>

6.11File Uploading
 A PHP script can be used with a HTML form to allow users to upload files
to the server. Initially files are uploaded into a temporary directory and
then relocated to a target destination by a PHP script.
 Information in the phpinfo.php page describes the temporary directory
that is used for file uploads as upload_tmp_dir and the maximum
permitted size of files that can be uploaded is stated as
upload_max_filesize. These parameters are set into PHP configuration file
php.ini
 The process of uploading a file follows these steps −
 The user opens the page containing a HTML form featuring a text files, a
browse button and a submit button.
 The user clicks the browse button and selects a file to upload from the local
PC.
 The full path to the selected file appears in the text filed then the user
clicks the submit button.
 The selected file is sent to the temporary directory on the server.
 The PHP script that was specified as the form handler in the form's action
attribute checks that the file has arrived and then copies the file into an
intended directory.
 The PHP script confirms the success to the user.
 As usual when writing files it is necessary for both temporary and final
locations to have permissions set that enable file writing. If either is set to
be read-only then process will fail.
 An uploaded file could be a text file or image file or any document.

 Creating an upload form


The following HTML code below creates an uploader form. This form is
having method attribute set to post and enctype attribute is set to
multipart/form-data

Example
259
<?php
if(isset($_FILES['ima
ge'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));

$extensions=

array("jpeg","jpg","png");
if(in_array($file_ext,$extensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}

if($file_size > 2097152){


$errors[]='File size must be excately 2 MB';
}

if(empty($errors)==true){ move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}else{ print_r($errors);
}
}
?>
<html>
<body>

<form action="" method="POST" enctype="multipart/form-data">


<input type="file" name="image" />
<input type="submit"/>
</form>

</body>
</html>
260
6.11 Sending Mail

PHP mail is the built in PHP function that is used to send emails from PHP
scripts.

The mail function accepts the following parameters;


- Email address
- Subject
- Message
- CC or BC email addresses

It’s a cost effective way of notifying users on important events.


Let users contact you via email by providing a contact us form on the website
that emails the provided content.
- Developers can use it to receive system errors by email
- You can use it to email your newsletter subscribers.
- You can use it to send password reset links to users who forget their
passwords
- You can use it to email activation/confirmation links. This is useful
when registering users and verifying their email addresses

Sending mail using PHP


The PHP mail function has the following basic syntax:

mail($to,$subject,$message,[$headers],[$parameters]);

HERE,
“$to” is the email address of the mail
recipient “$subject” is the email

261
subject
“$message” is the message to be sent.
“[$headers]” is optional, it can be used to include information such as CC, BCC

CC is the acronym for carbon copy. It’s used when you want to send a copy to
an interested person i.e. a complaint email sent to a company can also be sent
as CC to the complaints board.
BCC is the acronym for blind carbon copy. It is similar to CC. The email addresses
included in the BCC section will not be shown to the other recipients.

Simple Mail Transmission Protocol (SMTP)


 PHP mailer uses Simple Mail Transmission Protocol (SMTP)
to send mail. On a hosted server, the SMTP settings would
have already been set.
 The SMTP mail settings can be configured from “php.ini” file in the PHP
installation folder.
 Configuring SMTP settings on your localhost Assuming you are using
xampp on windows, locate the “php.ini” in the directory “C:\xampp\php”.
 Open it using notepad or any text editor. We will use notepad in this
example. Click on the edit menu

Click on Find… menu

262
The find dialog menu will appear

Click on Find Next button

Locate the entries [mail function]


; XAMPP: Don’t remove the semi column if you want to work with an SMTP Server
like Mercury
263
; SMTP = localhost
; smtp_port = 25

Remove the semi colons before SMTP and smtp_port and set the SMTP to your
smtp server and the port to your smtp port. Your settings should look as follows
SMTP =
smtp.example.com
smtp_port = 25
Note the SMTP settings can be gotten from your web hosting providers.
If the server requires authentication, then add the following lines. auth_username
= [email protected]
auth_password = example_password
Save the new changes.
Restart Apache server.

Php Mail Example


<?php
$to_email = 'name @ company . com';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail function';
$headers = 'From: noreply @ company . com';
mail($to_email,$subject,$message,$headers);
?>
Sending HTML email
When you send a text message using PHP then all the content will be treated as
simple text. Even if you will include HTML tags in a text message, it will be
displayed as simple text and HTML tags will not be formatted according to HTML
syntax. But PHP provides option to send an HTML message as actual HTML
message.

While sending an email message you can specify a Mime version, content type
and character set to send an HTML email.

Example

264
Following example will send an HTML email message to [email protected]
copying it to [email protected]. You can code this program in such a way
that it should receive all content from the user and then it should send an email.
<?php
$to = "[email protected]";
$subject = "This is subject";

$message = "<b>This is HTML message.</b>";


$message .= "<h1>This is headline.</h1>";

$header = "From:[email protected] \r\n";


$header .= "Cc:[email protected] \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retval = mail

($to,$subject,$message,$header); if(

$retval == true ) {
echo "Message sent successfully...";
}else {
echo "Message could not be sent...";
}
?>
6.13 AJAX
AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique
for creating better, faster, and more interactive web applications with the
help of XML, HTML, CSS and Java Script.

Conventional web application transmit information to and from the sever


using synchronous requests. This means you fill out a form, hit submit, and
get directed to a new page with new information from the server.

With AJAX when submit is pressed, JavaScript will make a request to the
server, interpret the results and update the current screen. In the purest sense,
265
the user would never know that anything was even transmitted to the server.

AJAX allows web pages to be updated asynchronously by exchanging data


with a web server behind the scenes. This means that it is possible to
update parts of a web page, without reloading the whole page.

How AJAX Works

1. An event occurs in a web page (the page is loaded, a button is clicked)


2. An XMLHttpRequest object is created by JavaScript
3. The XMLHttpRequest object sends a request to a web server
4. The server processes the request
5. The server sends a response back to the web page
6. The response is read by JavaScript
7. Proper action (like page update) is performed by JavaScript

AJAX - The XMLHttpRequest Object


All modern browsers support the XMLHttpRequest object.

The XMLHttpRequest object can be used to exchange data with a server


behind the scenes. This means that it is possible to update parts of a web
266
page, without reloading the whole page
Create an XMLHttpRequest Object
Syntax
variable = new XMLHttpRequest();
Example
var xhttp = new XMLHttpRequest();

XMLHttpRequest Object Methods


Method Description
new XMLHttpRequest() Creates a new XMLHttpRequest object
abort() Cancels the current request
getAllResponseHeaders() Returns header information
getResponseHeader() Returns specific header information
open(method,url,async,user,p Specifies the request
sw) method: the request type GET or
POST url: the file location
async: true (asynchronous) or false
(synchronous) user: optional user name
psw: optional password
send() Sends the request to the
server Used for GET
requests
send(string) Sends the request to the server.
Used for POST requests
setRequestHeader() Adds a label/value pair to the header to be
sent

XMLHttpRequest Object Properties

Property Description
Onreadystatechange Defines a function to be called
when the readyState property
changes

267
readyState Holds the status of the
XMLHttpRequest. 0: request not
initialized
1: server connection
established 2: request
received
3: processing request
4: request finished and response is
ready
responseText Returns the response data as a string
responseXML Returns the response data as XML data
Status Returns the status-number of a
request 200: "OK"
403: "Forbidden"
404: "Not Found"
statusText Returns the status-text (e.g. "OK" or
"Not Found")

AJAX - Send a Request To a Server


The XMLHttpRequest object is used to exchange data with a server.
To send a request to a server, we use the open() and send()
methods of the XMLHttpRequest object:
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();

The onreadystatechange Property


With the XMLHttpRequest object you can define a function to be executed
when the request receives an answer.

The function is defined in the onreadystatechange property of the


XMLHttpResponse object:

268
Example
<html>
<body>
<div id="demo">
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt",
true); xhttp.send();
}
</script>
</body>
</html>

AJAX PHP Example


The following example demonstrates how a web page can communicate with a
web server while a user types characters in an input field:
<html>
<head>
<script>
Function showHint(str) { if (str.length == 0) {
document.getElementById("txtHint").innerHTML = ""; return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
269
}
};
xmlhttp.open("GET", "gethint.php?q=" + str, true); xmlhttp.send();
}
}
</script>
</head>
<body>

<p><b>Start typing a name in the input field below:</b></p>


<form>
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>

The PHP File - "gethint.php"


The PHP file checks an array of names, and returns the corresponding
name(s) to the browser:
<?php
// Array with names
$a=array("bhavesh","rohit","kamlesh","jayesh","ronak","bhavin","bharat","sava
n");
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different
from "" if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as
$name) {
270
if (stristr($q, substr($name, 0,
$len))) { if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
// Output "no suggestion" if no hint was found or output correct
values echo $hint === "" ? "no suggestion" : $hint;
?>
PHP - AJAX and MySQL
AJAX can be used for interactive communication with a database.

AJAX Database Example


The following example will demonstrate how a web page can fetch information
from a database with AJAX:
<html>
<head>
<script>
function showUser(str) { if (str == "") {
document.getElementById("txtHint").innerHTML = ""; return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true); xmlhttp.send();
}
271
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="bhavesh">bhavesh</option>
<option value="rohan">rohan</option>
<option value="rohit">rohit</option>
<option value="bhavin">bhavin</option>
<option value="bhavik">bhavik</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
</body>
</html>
getuser.php
<?php
$q = $_GET['q'];
$con = mysqli_connect('localhost','root','','exam_bscit'); if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}

272
$sql="SELECT * FROM stud_reg WHERE fname = '".$q."'";
$result = mysqli_query($con,$sql); echo "<table>
<tr>
<th>fullname</th>
<th>username</th>
<th>city</th>
</tr>";
while($row = mysqli_fetch_array($result)) { echo "<tr>";
echo "<td>" . $row['fname'] . "</td>";
echo "<td>" . $row['uname'] . "</td>";
echo "<td>" . $row['city'] . "</td>"; echo "</tr>";
}
echo "</table>"; mysqli_close($con);
?>

273

You might also like