Professional Documents
Culture Documents
UNIT – 1
Introduction: How the Web Works - Introduction to HTML - Introduction to CSS - HTML Tables and Forms -
Advanced CSS: Layout - JavaScript: Client-Side Scripting
History of Internet
The Internet is simply a wire that runs underground and allows two computers to communicate with each other. A
server is a particular computer that is connected directly to the Internet. When we talk about specific web pages,
they are simply files that are stored on the server‟s hard drive. Every server has a unique protocol address or an IP
address. IP addresses are essential for computers to find each other.
If we put the right address on a packet and send it to any computer which is connected as part of the internet, each
computer would figure out which cable to send it down next so that it would get to its destination. With several
computers on a network, it may create confusion even with unique addresses. This transfer of messages is handled
by the Packet Routing Network, and hence a router is required to set up.
The Transfer Control Protocol is another system that makes sure no packet is lost or left behind because it might
create a disrupted message at the receiving end.
The below are the steps for how the message is transferred.
1. First, Computer1 sends a message by IP address to Computer2
2. The message sent by Computer1 is broken into small pieces- packets.
3. These small pieces- packets are transferred concerning Transfer Protocol so that the quality is
maintained.
4. Finally, these small pieces- packets reach Computer2 and are reassembled at their IP address.
The Internet works in a more complex manner than these above-given steps, but this might give a basic idea of how
the internet works.
Tim Berners-Lee, Vinton Cerf is also named as an internet daddy other than Tim Berners-Lee. After being out for 10
years from high school, he began co-designing and co-developing the protocols and structure of what became the
internet.
History of HTML
In 1945, Vannevar Bush first introduced the basics of hypertext. In 1990, Tim Berners-Lee invented the World Wide
Web, HTML (hypertext markup language), HTTP (HyperText Transfer Protocol) and URLs (Universal Resource
Locators. Along with his colleagues at CERN (an international scientific organization based in Geneva, Switzerland),
Tim Berners-Lee was the primary author of HTML (hypertext markup language).
There has been a dramatic growth in the number of internet users since its inception. As a result, the number of
computer networks that are connected has grown exponentially too. It started with only connecting less than ten
computers initially. Today, 440 million computers can be connected directly, making life easier for people across the
globe. Sharing information and knowledge has become extremely easy for those that have access to the Internet.
The country with the highest number of internet users is China, with 1.4 billion users, followed by India with 1.3
billion and the United States of America with a little over 0.3 billion users.
Local Area Network: This is a group of devices such as computers, servers, switches, and printers that are located
in the same building. These are near each other. The most common use of LAN is in houses or offices. A common
type of LAN is an Ethernet LAN, where two or more computers are connected to the Internet through switches.
Wireless Local Area Network: This is a local area network that uses wireless communication instead of wired
communication. In WLAN, two computers use wireless communication to form a local area network. A wifi router is
very common in this case. There are no cables involved in this case.
Advantages of Internet
The internet has become a popular name since the introduction of its easy installation and setup. The Internet was
first invented for only military and government uses. But now, it is found in every house across the world. The
following are the advantages of the internet.
The most powerful motivator for the Internet to work is the fact that knowledge and information have to be shared
amongst people. The article provided useful information about the internet such as its history, working and evolution
etc.
Internet Protocols
It is a set of rules that governs the communication and exchange of data over the internet. Both the sender and
receiver should follow the same protocols in order to communicate the data. In order to understand it better, let‟s
take an example of a language. Any language has its own set of vocabulary and grammar which we need to know
if we want to communicate in that language. Similarly, over the internet whenever we access a website or
exchange some data with another device then these processes are governed by a set of rules called the internet
protocols.
Working of internet protocol: The internet and many other data networks work by organizing data into small
pieces called packets. Each large data sent between two network devices is divided into smaller packets by the
underlying hardware and software. Each network protocol defines the rules for how its data packets must be
organized in specific ways according to the protocols the network supports.
Why do we need protocols?
It may be that the sender and receiver of data are parts of different networks, located in different parts of the
world having different data transfer rates. So, we need protocols to manage the flow control of data, access
control of the link being shared in the communication channel. Suppose there is a sender X who has a data
transmission rate of 10 Mbps. And, there is a receiver Y who has a data receiving rate of 5Mbps. Sin ce the rate of
receiving the data is slow so some data will be lost during transmission. In order to avoid this, the receiver Y
needs to inform sender X about the speed mismatch so that the sender X can adjust its transmission rate.
Similarly, the access control decides the node which will access the link shared in the communication channel at a
particular instant of time. If not the transmitted data will collide if many computers send data simultaneously
through the same link resulting in the corruption or loss of data.
Types of internet protocol
The Internet Protocols are of different types having different uses:-
1. TCP/IP(Transmission Control Protocol/ Internet Protocol): These are a set of standard rules that allows
different types of computers to communicate with each other. The IP protocol ensures that each computer that is
connected to the Internet is having a specific serial number called the IP address. TCP specifies how data is
exchanged over the internet and how it should be broken into IP packets. It also makes sure that the packets
have the information about the source of the message data, the destination of the message data, the sequence in
which the message data should be re-assembled, and checks if the message has been sent correctly to the
specific destination.
The functionality of TCP/IP is divided into 4 layers with each one having specific protocols:
1. Application Layer: The application layer makes sure that the data from the sending end is received in a
format that is acceptable and supported at the receiving end.
2. Transport Layer: The transport layer is responsible for the smooth transmission of data from one end to the
other. It is also responsible for reliable connectivity, error recovery, and flow control of the data.
3. Internet Layer: This Internet Layer moves packets from source to destination by connecting independent
networks.
4. Network Access Layer: The Network Access Layer sees how a computer connects to a network.
2. SMTP(Simple Mail Transfer Protocol): These protocols are important for sending and distributing outgoing
emails. This protocol uses the header of the mail to get the email id of the receiver and enters the mail into the
queue of outgoing mails. And as soon as, it delivers the mail to the receiving email id, it removes the e mail from
the outgoing list.
3. PPP(Point to Point Protocol): It is a communication protocol that is used to create a direct connection
between two communicating devices. This protocol defines the rules using which two devices will authenticate
with each other and exchange information with each other. For example, A user connects his PC to the server of
an Internet Service Provider also uses PPP. Similarly, for connecting two routers for direct communication it uses
PPP.
4. FTP (File Transfer Protocol): This protocol is used for transferring files from one system to the other. This
works on a client-server model. When a machine requests for file transfer from another machine, the FTO sets up
a connection between the two and authenticates each other using their ID and Password. And, the desired file
transfer takes place between the machines.
5. SFTP(Secure File Transfer Protocol): SFTP which is also known as SSH FTP refers to File Transfer Protocol
(FTP) over Secure Shell (SSH) as it encrypts both commands and data while in transmission. SFTP acts as an
extension to SSH and encrypts files and data then sends them over a secure shell data stream. This protocol is
used to remotely connect to other systems while executing commands from the command line.
6. HTTP(HyperText Transfer Protocol): This protocol is used to transfer hypertexts over the internet and it is
defined by the www(world wide web) for information transfer. This protocol defines how the information needs to
be formatted and transmitted. And, it also defines the various actions the web browsers should take in response
to the calls made to access a particular web page. Whenever a user opens their web browser, the user will
indirectly use HTTP as this is the protocol that is being used to share text , images, and other multimedia files on
the World Wide Web.
7. HTTPS(HyperText Transfer Protocol Secure): HTTPS is an extension of the Hypertext Transfer Protocol
(HTTP). It is used for secure communication over a computer network with the SSL/TLS protoc ol for encryption
and authentication. So, generally, a website has an HTTP protocol but if the website is such that it receives some
sensitive information such as credit card details, debit card details, OTP, etc then it requires an SSL certificate
installed to make the website more secure. So, before entering any sensitive information on a website, we should
check if the link is HTTPS or not. If it is not HTTPS then it may not be secure enough to enter sensitive
information.
8. TELNET(Terminal Network): TELNET is a standard TCP/IP protocol used for virtual terminal service given by
ISO. This enables one local machine to connect with another. The computer which is being connected is called a
remote computer and which is connecting is called the local computer. TELNET operation lets us display anything
being performed on the remote computer in the local computer. This operates on the client/server principle. The
local computer uses the telnet client program whereas the remote computer uses the telnet server program.
9. POP3(Post Office Protocol 3): POP3 stands for Post Office Protocol version 3. It has two Message Access
Agents (MAAs) where one is client MAA (Message Access Agent) and another is server MAA(Message Access
Agent) for accessing the messages from the mailbox. This protocol helps us to retrieve and manage emails from
the mailbox on the receiver mail server to the receiver‟s computer. This is implied between the receiver and
receiver mail server.
The client-server model describes how network devices like workstations, laptops, and IoT devices — known as
clients — make requests to network machines or software capable of completing the request, known as servers.
Though servers historically have been physical appliances like rack servers, data center trends show administrators
increasingly deploy virtual servers for a range of workloads.
Clients
Enterprises once relied on workstations that shared a single operating system, but today‟s IT environment strives for
interoperability between systems, devices, applications, and products.
Because network clients are increasingly heterogeneous device and OS types, administrators have the added
responsibility of ensuring compatibility.
Servers
The hyper-focused machines delivering IT resources to clients are the physical, virtual, and cloud-based servers
housed in modern data centers. Servers are the central authority for several essential digital processes that
enterprise organizations rely on.
Networking Devices
The framework calls for physical or wireless networking devices like hubs, switches, and routers to connect servers,
clients, and resources.
With the connection between clients and servers established, administrators can configure how client devices make
requests and designate servers to complete specific tasks.
Though simple, the client-server model is widely applicable and relevant to anyone seeking to understand content
delivery networks (CDN) or the mechanics of edge networking. As server capabilities move closer to the network
edge, the client-server process is physically closer to end-users.
Facilitating Email
Communication is essential to enterprise organizations, and snail mail can‟t compete with the speed and reliability of
electronic mail. The hosting of email communications for an organization or network by a specific server has been the
longtime industry choice to control particular email accounts and activity.
Through protocols like IMAP, POP3, and SMTP, administrators can establish a system that facilitates, secures, and
maintains email communications.
When using their email accounts, staff are the clients making requests to send emails, upload attachments, and store
contacts to an email server.
Central access and control of data Less control of some network devices
Load balancing for optimal performance Technical expertise for ongoing maintenance
3-Tier: Middleware
To further protect and enrich the 2-Tier architecture, this framework incorporates middleware between the client tier
(presentation layer) and the server tier (database layer).
This application layer provides a third tier, enabling more complex management of business logic. Examples of
middleware like web application servers offer load balancing, increased storage, and security.
Peer-to-Peer vs Client-Server
Though the client-server framework is the most popular distributed architecture, the most common alternative
mentioned is peer-to-peer (P2P) networks.
Unlike the client-server architecture, which offers a centralized flow from an organization‟s servers to staff,
stakeholders, and clients, a peer-to-peer network is decentralized. Network devices don‟t align with a specific,
dedicated server. Instead, P2P networks include network devices (clients) known as nodes that submit and service
requests between each other.
Because P2P networks like blockchains work in a distributed fashion, connectivity is critical to operations. Relative to
traditional networks, nodes tend to be more heterogeneous and share less data across the network.
The client-server model is more expensive to set up and maintain, but the reliability and scalability of the centralized
framework consistently outweigh the downfalls of peer-to-peer frameworks.
When compared to P2P networks, it‟s easy to see why the client-server model scaled digital operations for networks
to this point. As organizations grow, adopting additional tiers of client-server architecture is necessary to maintain IT
infrastructure and secure data integrity properly.
To serve millions of customers and stakeholders globally, enterprises need a robust distributed framework that only
the client-server model provides.
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 such as 192.168.1.1 (in IPv4), or more complex
newer alphanumeric IP addresses such as 2400:cb00:2048:1::c629:d7a2 (in IPv6).
In order to understand the process behind the DNS resolution, it‟s important to learn about the different hardware
components a DNS query must pass between. For the web browser, the DNS lookup occurs "behind the scenes" and
requires no interaction from the user‟s computer apart from the initial request.
DNS recursor - The recursor can be thought of as a librarian who is asked to go find a particular book
somewhere in a library. The DNS recursor is a server designed to receive queries from client machines
through applications such as web browsers. Typically the recursor is then responsible for making
additional requests in order to satisfy the client‟s DNS query.
Root nameserver - The root server is the first step in translating (resolving) human readable host
names into IP addresses. It can be thought of like an index in a library that points to different racks of
books - typically it serves as a reference to other more specific locations.
TLD nameserver - The top level domain server (TLD) can be thought of as a specific rack of books in
a library. This nameserver is the next step in the search for a specific IP address, and it hosts the last
portion of a hostname (In example.com, the TLD server is “com”).
Authoritative nameserver - This final nameserver can be thought of as a dictionary on a rack of
books, in which a specific name can be translated into its definition. The authoritative nameserver is the
last stop in the nameserver query. If the authoritative name server has access to the requested record,
it will return the IP address for the requested hostname back to the DNS Recursor (the librarian) that
made the initial request.
What's the difference between an authoritative DNS server and a recursive DNS resolver?
Both concepts refer to servers (groups of servers) that are integral to the DNS infrastructure, but each performs a
different role and lives in different locations inside the pipeline of a DNS query. One way to think about the difference
is the recursive resolver is at the beginning of the DNS query and the authoritative nameserver is at the end.
What is a URL?
A URL (Uniform Resource Locator) is a unique identifier used to locate a resource on the Internet. It is also referred
to as a web address. URLs consist of multiple parts -- including a protocol and domain name -- that tell a web
browser how and where to retrieve a resource.
End users use URLs by typing them directly into the address bar of a browser or by clicking a hyperlink found on a
webpage, bookmark list, in an email or from another application.
Look past the protocol (identified as HTTPS) and the permalink (www.techtarget.com) and we see the file path
includes two paths (searchnetworking and definition) and the title of the definition (URL).
Additionally, some URL designers choose to put the date of the post, typically, as (YYYY/MM/DD).
Parts of a URL
Using the URL https://whatis.techtarget.com/search/query?q=URL as an example, components of a URL
can include:
The protocol or scheme. Used to access a resource on the internet. Protocols include http, https, ftps, mailto
and file. The resource is reached through the domain name system (DNS) name. In this example, the protocol is
https.
Host name or domain name. The unique reference the represents a webpage. For this example,
whatis.techtarget.com.
Port name. Usually not visible in URLs, but necessary. Always following a colon, port 80 is the default port for
web servers, but there are other options. For example, :port80.
Path. A path refers to a file or location on the web server. For this example, search/query.
Query. Found in the URL of dynamic pages. The query consists of a question mark, followed by parameters. For
this example, ?.
Parameters. Pieces of information in a query string of a URL. Multiple parameters can be separated by
ampersands (&). For this example, q=URL.
Fragment. This is an internal page reference, which refers to a section within the webpage. It appears at the
end of a URL and begins with a hashtag (#).Other examples of parts of a URL can include:
The URL mailto:president@whitehouse.gov initiates a new email addressed to the mailbox president in the
domain whitehouse.gov.
The URL ftp://www.companyname.com/whitepapers/widgets.ps specifies the use of the FTP protocol
to download a file.
HTTPS is vital to protecting sensitive information, such as passwords, credit card numbers and identity data, from
unauthorized access.
HTTPS uses TCP/IP port number 443 by default, whereas HTTP uses port 80.
URL shorteners
URL shortening is a technique in which an URL may be made substantially shorter in length and still direct to the
required page. A shortener achieves this using a redirect on a domain name that is short.
There are many URL shortener services available. While many are free, those that offer capabilities such as Web
analytics, charge a fee. Companies that offer URL shorteners include Rebrandly, Bitly, Ow.ly, clicky.me and
Budurl.com.
Some Web site hosts, such as GoDaddy.com, offer URL shorteners. Other service providers, including search engines,
have begun turning away from URL shorteners because they are often subject to abuse by spammers, who
hide malware inside shortened URLs.
URL history
The retention of data related to Web usage has become a huge privacy concern. There has been increased public
demand for search engine and application service providers to be transparent in what information they collect, retain
and sell.
HyperText Protocol
The Hypertext Transfer Protocol (HTTP) is an application-level protocol for distributed, collaborative, hypermedia
information systems. This is the foundation for data communication for the World Wide Web (i.e. internet) since
1990. HTTP is a generic and stateless protocol which can be used for other purposes as well using extensions of its
request methods, error codes, and headers.
Basically, HTTP is a TCP/IP based communication protocol, that is used to deliver data (HTML files, image files,
query results, etc.) on the World Wide Web. The default port is TCP 80, but other ports can be used as well. It
provides a standardized way for computers to communicate with each other. HTTP specification specifies how
clients' request data will be constructed and sent to the server, and how the servers respond to these requests.
Basic Features
There are three basic features that make HTTP a simple but powerful protocol:
HTTP is connectionless: The HTTP client, i.e., a browser initiates an HTTP request and after a request is
made, the client waits for the response. The server processes the request and sends a response back after
which client disconnect the connection. So client and server knows about each other during current
request and response only. Further requests are made on new connection like client and server are new to
each other.
HTTP is media independent: It means, any type of data can be sent by HTTP as long as both the client
and the server know how to handle the data content. It is required for the client as well as the server to
specify the content type using appropriate MIME-type.
HTTP is stateless: As mentioned above, HTTP is connectionless and it is a direct result of HTTP being a
stateless protocol. The server and client are aware of each other only during a current request. Afterwards,
both of them forget about each other. Due to this nature of the protocol, neither the client nor the browser
can retain information between different requests across the web pages.
HTTP/1.0 uses a new connection for each request/response exchange, where as HTTP/1.1 connection may be used
for one or more request/response exchanges.
Basic Architecture
The following diagram shows a very basic architecture of a web application and depicts where HTTP sits:
The HTTP protocol is a request/response protocol based on the client/server based architecture where web
browsers, robots and search engines, etc. act like HTTP clients, and the Web server acts as a server.
Client
The HTTP client sends a request to the server in the form of a request method, URI, and protocol version, followed
by a MIME-like message containing request modifiers, client information, and possible body content over a TCP/IP
connection.
Server
The HTTP server responds with a status line, including the message's protocol version and a success or error code,
followed by a MIME-like message containing server information, entity meta information, and possible entity-body
content.
Web Server
Web pages are a collection of data, including images, text files, hyperlinks, database files etc., all located on some
computer (also known as server space) on the Internet. A web server is dedicated software that runs on the server-
side. When any user requests their web browser to run any web page, the webserver places all the data materials
together into an organized web page and forwards them back to the web browser with the help of the Internet.
Therefore, we can conclude that: -
A web server is a dedicated computer responsible for running websites sitting out on those computers
somewhere on the Internet. They are specialized programs that circulate web pages as summoned by
the user. The primary objective of any web server is to collect, process and provide web pages to the
users.
This intercommunication of a web server with a web browser is done with the help of a protocol named HTTP
(Hypertext Transfer Protocol). These stored web pages mostly use static content, containing HTML documents,
images, style sheets, text files, etc. However, web servers can serve static as well as dynamic contents. Web
Servers also assists in emailing services and storing files. Therefore it also uses SMTP (Simple Mail Transfer
Protocol) and FTP (File Transfer Protocol) protocols to support the respective services. Web servers are mainly used
in web hosting or hosting the website's data and running web-based applications.
The hardware of the web servers are connected to the Internet that manages the data exchange facility within
different connected devices. In contrast, the software of web server software is responsible for controlling how a
user accesses delivered files. Typically, web server management is an ideal example of the client/server model.
Therefore, it is compulsory for all computers that host websites (whether with state or dynamic web
page content) to have web server software.
How do web servers work?
The term web server can denote server hardware or server software, or in most cases, both hardware
and software might be working together.
1. On the hardware side, a web server is defined as a computer that stores software and another website
raw data, such as HTML files, images, text documents, and JavaScript files. The hardware of the web
servers are connected to the web and supports the data exchange with different devices connected to the
Internet.
2. On the software side, a web server includes server software accessed through website domain names. It
controls how web users access the web files and ensures the supply of website content to the end-user. The
web server contains several components, including an HTTP server.
Whenever any web browser, such as Google Chrome, Microsoft Edge or Firefox, requests for a web page hosted on a
web server, the browser will process the request forward with the help of HTTP. At the server end, when it receives
the request, the HTTP server will accept the request and immediately start looking for the requested data and
forwards it back to the web browser via HTTP.
Let's discover the step-by-step process of what happens whenever a web browser approaches the web server and
requests a web file or file. Follow the below steps:
1. First, any web user is required to type the URL of the web page in the address bar of your web
browser.
2. With the help of the URL, your web browser will fetch the IP address of your domain name either by
converting the URL via DNS (Domain Name System) or by looking for the IP in cache memory. The IP
address will direct your browser to the web server.
3. After making the connection, the web browser will request for the web page from the web
server with the help of an HTTP request.
4. As soon as the web server receives this request, it immediately responds by sending back the
requested page or file to the web browser HTTP.
5. If the web page requested by the browser does not exist or if there occurs some error in the
process, the web server will return an error message.
6. If there occurs no error, the browser will successfully display the webpage.
Examples of web server uses
Web servers are mostly used for:
o sending and receiving mails on Internet by using SMTP (Simple Mail transfer Protocol);
o fetching requests for File Transfer Protocol (FTP) files; and
o designing, developing, and publishing websites.
Many Web servers, even the basic one, also support the server-side scripting technique. Server-side scripting is a
web development method used to employ scripts on a web server that produces a customized response for each
user. This technique operates on the server machine and consists of an extensive feature set, including database
access. The server-side scripting process will have various scripting languages
such ASP, PHP, Java, JavaScript, Python, ruby and many more. This technique also enables the HTML files to be
created dynamically.
1 Static web servers refer to the servers, which Dynamic web servers refer to the servers where the
serve only the static content i.e., the content is content of the page can be updated and altered.
fixed and being shown as it is.
2 A static web server includes a computer and A dynamic web server also includes a computer with
the HTTP (Hyper Text Transfer Protocol) plenty of other software, unlike an application server and
software. database model.
3 It is called static; the web pages content won't It is called dynamic because the application server is
change unless the user manually changes it, used to update the web pages files at the server-side,
and the server will deliver web files as is to the and due to which, it can change on every call requested
web browser. by the web browser.
4 Static web servers take less time to load the The Dynamic web server can only produce the data when
data. it is requested from the database. Therefore, it is time
consuming and more complicated when compared to
static web servers.
Introduction to HTML
HTML stands for Hypertext Markup Language. It is a standard markup language used to design the
documents that will be displayed in the browsers as a web-page. This language can become more interactive and
attractive by using CSS ( Cascading Style Sheet) and JS (JavaScript) within it. The HTML word defin es some
specific meaning within it. Hypertext comes from the Hyperlink that means connections between several
pages, Markup means the defined elements will be the page layout and elements within the page.
The language combines both the feature and makes it Hypertext Markup Language.
Initially, the HTML was released in the year of 1993 developed by Tim Berners-Lee in 1990. Currently,
the WHATWG community working on the development of the HTML. The current HTML5 version gains so much
popularity because of newly added features in it. All the websites skeleton are made of HTML and each browser
performing on that and makes that visible and user-friendly to the user.
HTML Structure:
The structure of HTML document are given below:
<!DOCTYPE html>
<html>
<head>
<title> <!-- title bar --> </title>
<!-- header for the website -->
</head>
<body>
<!-- body section of the website -->
</body>
</html>
Characteristics of HTML:
Easy to understand: It is the easiest language you can say, very easy to grasp this language and easy to
develop.
Flexibility: This language is so much flexible that you can create whatever you want, a flexible way to design
web pages along with the text.
Linkable: You can make linkable text like users can connect from one page to another page or website
through these characteristics.
Limitless features: You can add videos, gifs, pictures or sound anything you want that will make the
website more attractive and understandable.
Support: You can use this language to display the documents on any platform like Windows, Linux or Mac.
Advantages of HTML:
HTML is an easy to learn, easy to apply and it‟s totally free you will just need a text editor and a browser.
HTML is supported by all the browsers and it is the most friendly search engine.
HTML can easily integrate with other languages and easy to develop.
It is the basic of all programming languages and the lightest language ever.
In HTML the display change frequently depending the window size or the device size make it comfortable to
read by the user.
HTML Element
The opening tag: This consists of the name of the element (in this example, p for paragraph), wrapped in
opening and closing angle brackets. This opening tag marks where the element begins or starts to take
effect. In this example, it precedes the start of the paragraph text.
The content: This is the content of the element. In this example, it is the paragraph text.
The closing tag: This is the same as the opening tag, except that it includes a forward slash before the
element name. This marks where the element ends. Failing to include a closing tag is a common beginner
error that can produce peculiar results.
HTML Attributes
Attributes contain extra information about the element that won't appear in the content. In this example,
the class attribute is an identifying name used to target the element with style information.
A space between it and the element name. (For an element with more than one attribute, the attributes
should be separated by spaces too.)
The attribute name, followed by an equal sign.
An attribute value, wrapped with opening and closing quote marks.
CSS
What is CSS
CSS stands for Cascading Style Sheets. It is the language for describing the presentation of Web pages,
including colours, layout, and fonts, thus making our web pages presentable to the users.
CSS is designed to make style sheets for the web. It is independent of HTML and can be used with any XML -
based markup language. Now let‟s try to break the acronym:
Cascading: Falling of Styles
Style: Adding designs/Styling our HTML tags
Sheets: Writing our style in different documents
CSS History
1994: First Proposed by Hakon Wium Lie on 10th October
1996: CSS was published on 17th November with influencer Bert Bos
Later he became co-author of CSS
1996: CSS became official with CSS was published in December
1997: Created CSS level 2 on 4th November
1998: Published on 12th May
CSS Syntax
Selector {
Property 1 : value;
Property 2 : value;
Property 3 : value;
}
For example:
h1
{
Color: red;
Text-align: center;
}
#unique
{
color: green;
}
Internal CSS
With the help of style tag, we can apply styles within the HTML file
Redundancy is removed
But the idea of separation of concerns still lost
Uniquely applied on a single document
Example:
< style>
h1{
color:red;
}
</style>
<h3> Have a great day </h3>
External CSS
With the help of <link> tag in the head tag, we can apply styles
Reference is added
File saved with .css extension
Redundancy is removed
The idea of separation of concerns is maintained
Uniquely applied to each document
Example:
<head>
<link rel="stylesheet" type="text/css" href="name of the Css file">
</head>
h1{
color:red; //.css file
}
Implementation of all the three types of CSS:
<!DOCTYPE html>
<html>
<head>
<title>HTML</title>
<link rel="stylesheet" type="text/css" href="first.css">
<style>
h1
{
color:green;
}
</style>
</head>
<body>
</body>
</html>
#center {
text-align: center;
color:pink;
}
CSS Selectors
The selector is used to target elements and apply CSS
Three simple selectors
o Element Selector
o Id Selector
o Class Selector
Priority of Selectors
Id > Class>Element
Element Selector
Used to select HTML elements by its name
How we do it
h1
{
Color: red;
}
We selected the heading tag and then changed the color property i.e text color to red. Now whatever is written
in this tag (content) will have the text color as red
ID Selector
The id attribute is used to select HTML element
Used to target specific or unique element
How we do it
#unique
{
Color: red;
}
<h1 id=”unique”> Hi </p>
We selected the id and then changed the color property i.e text color to red. Now whatever is written in this tag
(content) will have the text color as red
Class Selector
The class attribute is used to select HTML element
Used to target a specific class of the element
How we do it
group
{
Color: red;
}
<h1 class=”group”> Hi </p>
We selected the class and then changed the color property i.e text color to r ed. Now whatever is written in this
tag (content) will have the text color as red
Implementation of all the three selectors in CSS:
<!DOCTYPE html>
<html>
<head>
<title>HTML</title>
<link rel="stylesheet" type="text/css" href="first.css">
<style>
#center1 {
text-align: center;
color:pink;
}
.center2 {
text-align: center;
color:red;
}
h1
{
text-align:center;
color:green;
}
</style>
</head>
<body>
</body>
</html>
Javascript
What is JavaScript?
JavaScript is a very powerful client-side scripting language. JavaScript is used mainly for enhancing the
interaction of a user with the webpage. In other words, you can make your webpage more lively and interactive, with
the help of JavaScript. JavaScript is also being used widely in game development and Mobile application
development.
Javascript History
JavaScript was developed by Brendan Eich in 1995, which appeared in Netscape, a popular browser of that time.
The language was initially called LiveScript and was later renamed JavaScript. There are many programmers who
think that JavaScript and Java are the same. In fact, JavaScript and Java are very much unrelated. Java is a
very complex programming language whereas JavaScript is only a scripting language. The syntax of
JavaScript is mostly influenced by the programming language C.
To start with, you need a text editor to write your code and a browser to display the web pages you develop. You
can use a text editor of your choice including Notepad++, Visual Studio Code, Sublime Text, Atom or any other text
editor you are comfortable with. You can use any web browser including Google Chrome, Firefox, Microsoft Edge,
Internet Explorer etc.
You should place all your JavaScript code within <script> tags (<script> and </script>) if you are keeping your
JavaScript code within the HTML document itself. This helps your browser distinguish your JavaScript code from the
rest of the code. As there are other client-side scripting languages (Example: VBScript), it is highly recommended
that you specify the scripting language you use. You have to use the type attribute within the <script> tag and set
its value to text/javascript like this:
<html>
<head>
<title>My First JavaScript code!!!</title>
<script type="text/javascript">
alert("Hello World!");
</script>
</head>
<body>
</body>
</html>
UNIT – 2
Introduction to Server-Side Development with PHP - PHP Arrays and Superglobals - PHP Classes and Objects
Working with Databases Error Handling and Validation
Now let's look at the code that goes into server side scripting vs client side scripting. The code is notably different in
each case:
They serve distinct objectives and are concerned about different things.
They don't utilise the same programming languages in most cases (the exception being JavaScript, which can be
used on the server- and client-side).
They work in a variety of operating system situations.
Client-side code is code that runs in the browser and is focused on enhancing the appearance and functionality of
a displayed web page. This comprises UI component selection and style, layout creation, navigation, form validation,
and so forth.
Server side website development, on the other hand, typically entails deciding which content is delivered to the
browser in response to requests. Validating provided data and requests, using databases to store and retrieve data,
and transmitting the right data to the client are all duties handled by the server side code.
Client-side code is written in HTML, CSS, and JavaScript and runs within a web browser, with little or no access to
the operating system (including limited access to the file system).
Server side code can be developed in a variety of computer languages, including PHP, Python, Ruby, C#, and
JavaScript (NodeJS). The server side code has complete access to the operating system, and the developer can use
whichever programming language (and version) they choose.
Web frameworks are commonly used by developers while writing code. Web frameworks are sets of functions,
objects, rules, and other code structures that are meant to address common issues, accelerate development, and
simplify the various sorts of activities that are encountered in a certain area.
While frameworks are used in both client and server side programmes, the domains are highly diverse, and therefore
the frameworks are as well.
Client-side web frameworks make layout and presentation duties easier, whereas server side web frameworks include
a lot of "standard" web server functionality that you would have to develop yourself otherwise (e.g. support for
sessions, support for users and authentication, easy database access, templating libraries, etc.).
What can you do on the server side?
Server side scripting language is extremely beneficial since it allows us to send information customised to individual
users quickly and effectively, resulting in a much improved user experience.
Server side programming languages are used by companies like Amazon to generate product search results, offer
targeted product suggestions based on client preferences and historical buying behaviour, streamline transactions,
and so on.
Banks utilise server side programming languages to store account information and restrict access to just authorised
users. Server side programming is used by other services such as Facebook, Twitter, Instagram, and Wikipedia to
highlight, distribute, and regulate access to interesting material.
The following are some of the most popular uses and benefits of server side programming.
Consider how many things are offered on Amazon and how many Facebook postings have been made. It would be
impossible to create a separate static page for each product or article.
Instead of storing the information in a database, server side programming languages allows us to dynamically
generate and return HTML and other sorts of files (e.g. PDFs, images, etc.). Data (JSON, XML, etc.) can also be
returned for rendering by appropriate client-side web frameworks (this reduces the processing burden on the server
and the amount of data that needs to be sent).
The server isn't restricted to providing data from databases; it might also return the results of software tools or data
from communications services. Even the sort of client device that receives the material can be targeted.
Because the data is stored in a database, it can be shared and updated with other business systems more simply (for
example, when products are sold either online or in a shop, the shop might update its database of inventory).
Server side uses
Server side scripting runs scripts on the server, reducing the burden on the user's machine.
Database web applications may be created using server side scripting.
Even if users access the source code, server side scripting is used to hide scripts from them; only client side scripts
are shown.
Server side scripting is used to quickly create dynamic websites with content that can be changed at any moment by
the site administrator.
Because server side scripts are not browser-dependent, we don't have to worry about browser versions.
Complex activities may be completed in a few stages thanks to server side scripting.
It's simple to understand and utilise.
What PHP?
PHP is an recursive acronym for "PHP: Hypertext Preprocessor"
PHP is a widely-used, open source (free to download, use, modify and rerelease) scripting
language
PHP scripts are executed on the server.so,it is server side scripting language
PHP History
PHP was developed by Rasmus Lerdorf for monitoring his online resume in 1995. It slowly became popular.
This first version PHP/F1 has some basic functions.
PHP/F1 2.0 was released and was quickly replaced by PHP 3.0 in 1997
PHP 3.0 was interesting. It was developed by and Andi Gutmans and Zeev suraski. It includes support for
wider range of data bases (Oracle and My SQL). This version had greater portability. It was used by
thousands of web servers.
PHP 4.0 was released in 2003. It used a new engine and provided better performance, greater reliability
and scalability and support for web servers other than Apache. It also supports OOP features and built-in
session management.
PHP 5.0 offers a complete object oriented program models. It also includes better exception handling, a
more consistent XML tool kit, improved My SQL support and a better memory manager. PHP 5.0 was the
best in the languages 10 year history. A survey was conducted by net craft in April 2004. It showed that
PHP was in use for over 15 million websites.
Features of PHP
PHP as a programming language for the web has many adv ntages than JSP, ASP and VB.NET. Because of
its simplicity and open source availability it is the widely used scripting language for websites. The features of PHP
that are listed below makes PHP the most enjoyable language for the developer community.
Simplicity
Even a beginner can easily to learn PHP because it has
Clearly written manual
Consistent and logical syntax
It may take only two hours for a programmer to learn PHP and write scripts.
It can also access c library and take advantage of that code.
Portability
The PHP scripts can be made to work on different platformsfrom PHP 3.0 This is because PHP code is
interpreted not compiled.The meaning of this portability is developer can write code on windows and deploy on Unix
with interpreter for PHP. PHP scripts can be run on Microsoft windows, Unix, Mac OS and OS/2.
Speed
PHP scripts run faster that most scripting languages like ASP, JSP and Perl. when PHP was released it had
new parsing engine which made it faster. PHP 5.0 was even faster through the use of optimized memory manager
and object handler.
Open source
Since PHP is open source, its source code is freely available on the web. We need not pay any license. So
cost of developed website application is reduced but reliability and performance is not affected. This open-source
approach also makes the application to fix bug easily.
Extensible
The language is set to be extensible, it can support new technology and add new methods to it. PHP create
has built-in architecture which allows developers easily add new technologies and modules.
Example of add on modulus:-
A PHP script consists of one or more statements, with each statement ending with a semicolon. Blank lines
within the script are ignored by the parser. Everything outside the tags is also ignored by the parser, and returned as
it; only the code between the tags is read and executed. The semicolon can be omitted on the last line of a PHP block,
because the closing ?> includes an implicit semicolon.
For greater readability, we should add comments to our PHP code.
Variables
Variables are the building blocks of any programming language. A variable can be thought of as a
programming construct used to store both numeric and nonnumeric data. The contents of a variable can be altered
during program execution, and variables can be compared and manipulated using operators.
PHP supports a number of different variable types—Booleans, integers, floating point numbers, strings,
arrays, objects, resources, and NULLs—and the language can automatically determine variable type by the context in
which it is being used. Variables need not be declared. Every variable has a name, which is preceded by a dollar ($)
symbol, and it must begin with a letter or underscore character, optionally followed by more letters, numbers, and
underscores. For example, $popeye, $one_day, and $INCOME are all valid PHP variable names, while $123 and
$48hrs are invalid variable names.
Variable names in PHP are case-sensitive; $count is different from $Count or $COUNT. Saving form input in
variable
PHP can be used for creating dynamic websites. In a dynamic website, user can interact with website by
providing text or by selecting options. Form is one of the quickest and easiest ways to add interactivity to our website.
Through forms we can read user data into PHP variables.
Sample form Home.html
< html>
< head></ head>
< body>
< form action=" message . PHP" method =" post">
Enter your message:< input type=" text" name=" MSG"=" 30">
< input type=" submit" value=" send ">
</ form>
</ body>
</ html>
Output
Message. php
<? PHP
// retrieve form data in a variable
$input=$- post[" MSG"];
// print it
echo " you said <i> $input </i>”
?>
Output
You said: Hello
We use two files (html and PHP files) for retrieving a single text data got from a user in a web form into
php variable $input. The web page is displayed with the message Enter yourmessage: In the text box near the
message, the user will type some message in few words after the text box there will be a submit button. After
entering the message in the text box user will click submit bottom. When submit button is clicked the PHP script
message.php is executed and the message displayed will be the text entered by the user.
Working
Here we have used HTML coding for displaying the input box. The <form> tag of html is used with input
option. The form tag also contains two main attributes action and method. The action attribute specifies the
name of the script. Here the name is message.php. The script will process the message entered into the form. The
method attribute of the < form> tag specifies the manner in which form data will be submitted. Here it is POST
method.
We have to run the home.html file in a browser. This is a client side script. On running this file a form is
displayed in the webpage with a line.
When we click the submit button the server side script in the action attribute will be called for execution.
That script will display another webpage that prints the string we have entered.The $_POST variable would have
stored the string we have entered. It will be stored in$_POST[„msg‟]. Then it will be assigned to php variable
$input.We can display it using echo statement.
PHP has a total of eight data types which we use to construct our variables:
PHP Keywords
PHP has a set of keywords that are reserved words which cannot be used as function names, class names
or method names. Prior to PHP 7, these keywords could not be used as class property names either:
Keyword
abstract and as break callable case
catch class clone const continue declare
default do echo else elseif empty
enddeclare endfor endforeach endif endswitch endwhile
extends final finally fn for foreach
function global goto if implements include
PHP Operators
Operators are used to perform operations on variables and values.
PHP divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
Conditional assignment operators
PHP Arithmetic Operators
The PHP arithmetic operators are used with numeric values to perform common arithmetical operations, such as
addition, subtraction, multiplication etc.
Operator Name Example Result
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
** Exponentiation $x ** $y Result of raising $x to the $y'th power
x -= y x = x -y Subtraction
x *= y x = x *y Multiplication
x /= y x = x /y Division
x %= y x = x %y Modulus
Output "Have a good day!" if the current time is less than 20, and "Have a good night!" otherwise:
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
PHP - The if...elseif...else Statement
The if...elseif...else statement executes different codes for more than two conditions.
Syntax
if (condition)
{
code to be executed if this condition is true;
} elseif(condition)
{
code to be executed if first condition is false and this condition is true;
} else {
code to be executed if all conditions are false;
}
Example
Output "Have a good morning!" if the current time is less than 10, and "Have a good day!" if the current time is less
than 20. Otherwise it will output "Have a good night!":
<?php
$t = date("H");
if ($t < "10")
{
echo "Have a good morning!";
} elseif ($t < "20")
{
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
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;
}
This is 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.
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
PHP Loops
Often when you write code, you want the same block of code to run over and over again a certain number
of times. So, instead of adding several almost equal code-lines in a script, we can use loops.
Loops are used to execute the same block of code again and again, as long as a certain condition is true.
In PHP, we have the following loop types:
while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as the specified condition
is true
for - loops through a block of code a specified number of times
foreach - loops through a block of code for each element in an array
The PHP 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
The example below displays the numbers from 1 to 5:
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
Example Explained
• $x = 1; - Initialize the loop counter ($x), and set the start value to 1
• $x <= 5 - Continue the loop as long as $x is less than or equal to 5
• $x++; - Increase the loop counter value by 1 for each iteration
The PHP do...while Loop
The do...while loop will always execute the block of code once, it will then check the condition, and repeat
the loop while the specified condition is true.
Syntax
do {
code to be executed;
} while (condition is true);
Example
The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will write some output,
and then increment the variable $x with 1. Then the condition is checked (is $x less than, or equal to 5?), and
the loop will continue to run as long as $x is less than, or equal to 5:
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
Note: In a do...while loop the condition is tested AFTER executing the statements within the loop. This means
that the do...while loop will execute its statements at least once, even if the condition is false. See example
below.
The PHP for Loop
The for 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 for each iteration;
}
Parameters:
• init counter: Initialize the loop counter value
• test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to
FALSE, the loop ends.
• increment counter: Increases the loop counter value
Example
The example below displays the numbers from 0 to 10:
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
Example Explained
• $x = 0; - Initialize the loop counter ($x), and set the start value to 0
• $x <= 10; - Continue the loop as long as $x is less than or equal to 10
• $x++ - Increase the loop counter value by 1 for each iteration
The PHP 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
The following example will output the values of the given array ($colors):
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
PHP Break
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.
This example jumps out of the loop when x is equal to 4:
Example
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
?>
PHP Continue
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 4:
Example
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}
?>
Break and Continue in While Loop
You can also use break and continue in while loops:
Break Example
<?php
$x = 0;
while($x < 10) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
$x++;
}
?>
Continue Example
<?php
$x = 0;
PHP Arrays
An array can store one or more values in a single variable name.
What is an array?
When working with PHP, sooner or later, you might want to create many similar variables.
Instead of having many similar variables, you can store the data as elements in an array.
Each element in the array has its own ID so that it can be easily accessed. There are three different
kind of arrays:
Numeric array - An array with a numeric ID key
Associative array - An array where each ID key is associated with a value
Multidimensional array - An array containing one or more arrays
Numeric Arrays
A numeric array stores each element with a numeric ID key. There are different ways to create a numeric
array.
Example 1
In this example the ID key is automatically assigned:
$names = array("Peter","Quagmire","Joe");
Example 2
In this example we assign the ID key manually:
$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";
Multidimensional Arrays
In a multidimensional array, each element in the main array can also be an array. And each element in
the sub-array can be an array, and so on.
Example
In this example we create a multidimensional array, with automatically assigned ID keys:
$families = array (
"Griffin"=>array ("Peter", "Lois", "Megan"),
"Quagmire"=>array ("Glenn"),
"Brown"=>array ("Cleveland", "Loretta", "Junior"));
The array above would look like this if written to the output:
Array (
[Griffin] => Array (
[0] => Peter
[1] => Lois
[2] => Megan
)
[Quagmire] => Array (
[0] => Glenn
)
[Brown] => Array (
[0] => Cleveland
[1] => Loretta
[2] => Junior
)
)
Example 2
Lets try displaying a single value from the array above:
echo "Is " . $families['Griffin'][2] . "a part of the Griffin family?";
The code above will output:
Is Megan a part of the Griffin family?
Condition statement and iteration statement are not needed in foreach() loop.
The syntax of foreach() loop is.
foreach (array variable as loop variable)
{
// loop statement
}
example using foreach() loop
<html>
<head></head>
<body>
Today‟s shopping list;
<ul>
<?php
$shoppinglist=array („green gram‟, ‟bengal gram‟, „‟rice‟);
foreach($shoppinglist as $ item)
{
echo”<li>$item”;
}
?>
</ul>
<?body>
</html>
Output:
A dog named Tripsy
A cat named Tabitha
A parrot named polly
Using array functions:
There are many built-in array functions in PHP that we can use along with array.
1. is_array()
This function check whether the variable in PHP is a array variable or not. It returns Boolean value as
output
2. array_key()
This function returns the list of key in associative array for example this function will return
'dog', cat', 'parrot‟ from the array $animals.
3. array_value()
This function will return only the array element in an associative array. For example, this function
returns 'Tripsy', 'Tabitha', 'polly' from the animals array,
4. list()
This list function assigns array elements to array variable. ex: $flavours=array(' strawberry', 'grape',
'vanilla'); list($f1, $f2, $f3) = $flavours; $f1 will have strawberry
$f2 will have grape and so on
5. extract()
The extract() function iterates through (associative array) converting the key value pairs into corresponding
variable value pairs.
$ fruits= array('red'= „apple‟, ' yellow'=' banana', 'purple'= „grapes‟); Extract ($ fruits):
$red will have 'apple'
$yellow will have' banana'
$purple will have' grapes'
6. Array_push() function:
It adds an element from the end of the array. Array_push($student, 'John'); The element John is added to
the $students array.
7. Array_pop()
This function removes an element from the end of the array. ex:-array-pop($students)
8. array-shift()
This function is used to pop element at the beginning of the array. array-shift ($student)
9. array-unshift:
This function adds element at the beginning of the array. array-unshift ($students, „Ronald');
10. Explode ()
The explode function splits a string into smaller components on the basis of a user defined character and then
returns those element in an array.
ex:-
$string=' this is a book';
$words = explode („$string‟, „ „);
This function returns and array variable $words will contain („this‟, „is‟, „book‟)
11. implode ()
The implode function create a single string from all the element of an array joining them together with user
defined separator.
EX:-
$words=array(„This‟,‟ is‟, „a‟, „book‟, „of‟, ‟Hindi‟);
$string=implode(„ ‟,$words);
$string=‟This is a book of Hindi‟;
Object-Oriented Programming
Object-Oriented Programming (OOP) is a programming model that is based on the concept of classes and objects. As
opposed to procedural programming where the focus is on writing procedures or functions that perform operations
on the data, in object-oriented programming the focus is on the creations of objects which contain both data and
functions together.
Object-oriented programming has several advantages over conventional or procedural style of programming. The
most important ones are listed below:
PHP is a server-side scripting language, mainly used for web development but also used as a general-purpose
programming language. Object-Oriented Programming (PHP OOP), is a type of programming language principle
added to php5, that helps in building complex, reusable web applications.
Class − This is a programmer-defined data type, which includes local functions as well as local data. You
can think of a class as a template for making many instances of the same kind (or class) of object.
Object − An individual instance of the data structure defined by a class. You define a class once and then
make many objects that belong to it. Objects are also known as instance.
Inheritance − When a class is defined by inheriting existing function of a parent class then it is called
inheritance. Here child class will inherit all or few member functions and variables of a parent class.
Polymorphism − This is an object oriented concept where same function can be used for different
purposes. For example function name will remain same but it make take different number of arguments and
can do different task.
Overloading − a type of polymorphism in which some or all of operators have different implementations
depending on the types of their arguments. Similarly functions can also be overloaded with different
implementation.
Data Abstraction − Any representation of data in which the implementation details are hidden
(abstracted).
Encapsulation − refers to a concept where we encapsulate all the data and member functions together to
form an object.
Constructor − refers to a special type of function which will be called automatically whenever there is an
object formation from a class.
Destructor − refers to a special type of function which will be called automatically whenever an object is
deleted or goes out of scope.
Classes and objects are the two main aspects of object-oriented programming. A class is a self-contained,
independent collection of variables and functions which work together to perform one or more specific tasks, while
objects are individual instances of a class.
A class acts as a template or blueprint from which lots of individual objects can be created. When individual objects
are created, they inherit the same generic properties and behaviors, although each object may have different values
for certain properties.
For example, think of a class as a blueprint for a house. The blueprint itself is not a house, but is a detailed plan of
the house. While, an object is like an actual house built according to that blueprint. We can build several identical
houses from the same blueprint, but each house may have different paints, interiors and families inside, as shown in
the illustration below.
A class can be declared using the class keyword, followed by the name of the class and a pair of curly braces ({})
Class is a programmer-defined data type, which includes local methods and local variables.
<?php
class Books{
public function name(){
echo “PHP book”;
}
public function price(){
echo “900 Rs/-”;
}
}
/*To create php object we have to use a new operator. Here php object is the object of the
Books Class */
$obj = new Books();
$obj->name();
$obj->price();
?>
Output:
PHP book
900 Rs/-
$Samsung->getPrice();
$Iphone->getPrice(); $Xiaomi->getPrice(); ?>
A destructor is called automatically when a scripts ends. However, to explicitly trigger the destructor, you
can destroy the object using the PHP unset() function, as follow:
<?php
class MyClass
{
// Constructor
public function __construct(){
echo 'The class "' . __CLASS__ . '" was initiated!<br>';
}
// Destructor
public function __destruct(){
echo 'The class "' . __CLASS__ . '" was destroyed.<br>';
}
}
// Create a new object
$obj = new MyClass;
// Destroy the object
unset($obj);
// Output a message at the end of the file
echo "The end of the file is reached.";
?>
Now, the PHP code in the above example will produce the following output:
PHP automatically clean up all resources allocated during execution when the script is finished, e.g. closing
database connections, destroying objects, etc.
The __CLASS__ is a magic constant which contains the name of the class in which it is occur. It is empty, if
it occurs outside of the class
When working with classes, you can even restrict access to its properties and methods using the visibility
keywords for greater control. There are three visibility keywords (from most visible to least
visible): public, protected, private, which determines how and from where properties and methods can be accessed
and modified.
public — A public property or method can be accessed anywhere, from within the class and outside. This is the
default visibility for all class members in PHP.
protected — A protected property or method can only be accessed from within the class itself or in child or
inherited classes i.e. classes that extends that class.
private — A private property or method is accessible only from within the class that defines it. Even child or
inherited classes cannot access private properties or methods.
The following example will show you how this visibility actually work
<?php
// Class definition
class Automobile
{
// Declare properties
public $fuel;
protected $engine;
private $transmission;
}
class Car extends Automobile
{
// Constructor
public function __construct(){
echo 'The class "' . __CLASS__ . '" was initiated!<br>';
}
}
// Create an object from Automobile class
$automobile = new Automobile;
// Attempt to set $automobile object properties
$automobile->fuel = 'Petrol'; // ok
$automobile->engine = '1500 cc'; // fatal error
$automobile->transmission = 'Manual'; // fatal error
// Create an object from Car class
$car = new Car;
// Attempt to set $car object properties
$car->fuel = 'Diesel'; // ok
$car->engine = '2200 cc'; // fatal error
$car->transmission = 'Automatic'; // undefined
?>
In addition to the visibility, properties and methods can also be declared as static, which makes them accessible
without needing an instantiation of the class. Static properties and methods can be accessed using the scope
resolution operator (::), like this: ClassName::$property and ClassName::method().
A property declared as static cannot be accessed via the object of that class though a static method can be, as
demonstrated in the following example:
<?php
// Class definition
class HelloClass
{
// Declare a static property
public static $greeting = "Hello World!";
The self keyword is different from the this keyword which means "the current object" or "the current instance of a
class". The this keyword is always preceded by a dollar sign ($) and followed by the -> operator (e.g. $this->name).
Since static methods can be called without an instance of a class (i.e. object), the pseudo-variable $this is not
available inside the method declared as static.
Inheritance
When the properties and the methods of the parent class are accessed by the child class, we call the concept has
inheritance. The child class can inherit the parent method and give own method implementation, this property is
called overridden method. When the same method of the parent class is inherited we call as inherited method. Now
let us see types of inheritance supported in Object Oriented Programming and corresponding Php inheritance
examples.
Types Of Inheritance
Single Level Inheritance: In Single Level Inheritance the Parent class methods will be extended by the child
class. All the methods can be inherited.
<?php
class A {
public function printItem($string) {
echo ' Hi : ' . $string;
}
public function printPHP() {
echo 'I am from valuebound' . PHP_EOL;
}
}
class B extends A {
public function printItem($string) {
echo 'Hi: ' . $string . PHP_EOL;
}
public function printPHP() {
echo "I am from ABC";
}
}
$a = new A();
$b = new B();
$a->printItem('Raju');
$a->printPHP();
$b->printItem('savan');
$b->printPHP();
?>
MultiLevel Inheritance : In MultiLevel Inheritance, the parent class method will be inherited by child class and
again subclass will inherit the child class method.
<?php
class A {
public function myage() {
return ' age is 80';
}
}
class B extends A {
public function mysonage() {
return ' age is 50';
}
}
class C extends B {
public function mygrandsonage() {
return 'age is 20';
}
public function myHistory() {
echo "Class A " .$this->myage();
echo "Class B ".$this-> mysonage();
echo "Class C " . $this->mygrandsonage();
}
}
$obj = new C();
$obj->myHistory();
?>
Output
Class A is 80
Class B is 50
Class C 20