You are on page 1of 50

Add-on Course Full Stack Web Development 2021-2022

UNIT – 1

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

Introduction: How the Web Works - Introduction to HTML - Introduction to CSS - HTML Tables and Forms -
Advanced CSS: Layout - JavaScript: Client-Side Scripting

How the Web Works


The World Wide Web (WWW or simply the Web) is certainly what most people think of when they see the word
“Internet.” But the WWW is only a subset of the Internet.

History of Internet

What is the Internet?


The Internet is a short form for an interconnected network. It has become a vital part of our lives, helping us
connect with people worldwide. The Internet is made of a large number of independently operated networks. It is
fully distributed with no central control. Each independently-operated system is motivated to ensure that there is
end-to-end connectivity of every part of the network.

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.

History of the Internet


The first question that pops into your mind is probably, “Who started the internet?”. The Internet was developed by
Bob Kahn and Vint Cerf in the 1970s. They began the design of what we today know as the „internet.‟ It was the
result of another research experiment which was called ARPANET, which stands for Advanced Research Projects
Agency Network. This was initially supposed to be a communications system for the Defense Team of the
United States of America - a network that would also survive a nuclear attack. It eventually became a successful
nationwide experimental packet network. But when was the first Internet started? It is believed that on 6 August
1991, when the World Wide Web opened to the public.

How Does the Internet Work?


Computers that we use every day are called clients because they are indirectly connected to the Internet through an
internet service provider. When you open a webpage on your computer, you connect to the webpage, and then you
can access it. Computers break the information into smaller pieces called packets, which are reassembled in their
original order.

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.

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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.

Father of the Internet: Tim Berners-Lee


Tim Berners-Lee was the man, who led the development of the World Wide Web, the defining of HTTP (HyperText
Transfer Protocol), HTML (hypertext markup language) used to create web pages, and URLs (Universal Resource
Locators). The development of WWW, HTTP, HTML and URLs took place between 1989 and 1991. Tim Berners-Lee
was born in London and he graduated in Physics from Oxford University in 1976. Currently, Tim Berners-Lee is the
Director of the World Wide Web Consortium, the group that sets technical standards for the web.

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).

Evolution of the Internet


Although the Internet was developed much earlier, it only became popular in households in the 1990s. The
emergence of the Internet can be tracked by how many businesses and homes started changing the way they
worked and started connecting their laptops and other devices to the Internet. However, the concept of hypertext
transfer protocol (HTTP) as we know it today, was created only during this time. This meant that people could access
the same web pages on their devices now and share information.

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.

The Two Main Types of Computer Networks


There are different computer network types, depending on how large they are and how much geographical area they
cover. The most common types are Local Area Network (LAN) and Wireless Local Area Network (WAN).

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.

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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.

 It is a great medium of sharing and has increased connectivity.


 With the internet, banking has now become easier. Long tiresome waiting lines have been eliminated since
the introduction of e-banking platforms.
 E-commerce websites are one of the great advantages of the internet. One can buy groceries, clothes,
household items, and much more with the internet.
 The Internet is also a great source of entertainment. One can watch videos and movies, listen to music,
and play games, without any hassle.
 Social media platforms like Facebook, Instagram, and Twitter have brought the world closer.
 The education system has also transformed. With the internet, any student across the world can attend
online classes.

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.

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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.

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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.

Client Server Model


What Is the Client-Server Model?
The client-server model is a network architecture that describes how servers share resources and interact with
network devices. For modern enterprises and data centers, many servers facilitate processes like email, printing,
internet connections, application hosting, and more.

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.

What Are the Components of a Client-Server Model?


All client-server frameworks contain three primary ingredients: clients, servers, and the networking devices to
connect the two segments.
Client Server Networking Device
Examples Examples Examples

Workstation Database Server Hub

Desktop DNS Bridge

Laptop Web Application Server Switch

Tablet File Server Router

Smartphone Proxy Server Gateway

IOT Device Virtual Machine Modem IoT Device

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.

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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.

How Does the Client-Server Model Work?

An operational client-server architecture facilitates the following process:

1. The client submits a request through a network-enabled device.


2. The network server receives and processes the request.
3. The server delivers a response to the client.

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.

Client-Server Model Examples

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.

Accessing Web Content


When a web client wants to access a specific website, they enter the URL, and the browser requests an IP address
from the domain name system (DNS). The DNS server assigns the user an IP address for identification and delivery
of results.
By navigating to the website, a client triggered specific web content that the user can only access via an HTTP
response provided by a web server.
In this case, the end-user is the client presented with digital content. The DNS server and web server establish and
facilitate the connection to a database hosting the web content.

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

Advantages and Disadvantages of the Client-Server Model


Advantages Disadvantages

Central access and control of data Less control of some network devices

Efficient, scalable, and organized system Upfront cost and implementation

Load balancing for optimal performance Technical expertise for ongoing maintenance

Redundancy and data recovery options Servers at risk of DoS attacks

Interconnected network of devices Clients are attack vectors when breached

The Different Types of Client-Server Architectures


The four types of client-server frameworks are representative of how the client-server relationship evolved with
networking advancements.

1-Tier: All-in-One System


All client-server configuration settings, user interface, business logic, and database logic sit on network devices in the
base client-server architecture. Often limited to smaller networks, 1-Tier frameworks include presentation, business,
and data access layers on the same machine.

2-Tier: Client and Server


2-Tier architectures add a server to the mix and separate the presentation layer to a user interface, where the client
makes requests outside its capabilities. Clients and servers take on more business and database logic at varying
levels, providing administrators some control.

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.

N-Tier: Multitier Architecture


Working off of the 3-Tier architecture, N-Tier describes the further use of middleware to segment network traffic and
functions. Though this comes with greater complexity, modern enterprise organizations require multitier
architectures‟ flexibility, scalability, 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.

The Distributed Architecture of Choice for Enterprises


With benefits like centralized data control, workload balancing, added security, and redundancy, the client-server
model is the near-universal framework for SMBs up to enterprise organizations.

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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.

Domain Name System


What is DNS?
The Domain Name System (DNS) is the phonebook of the Internet. Humans access information online
through domain names, like nytimes.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.

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).

How does DNS work?


The process of DNS resolution involves converting a hostname (such as www.example.com) into a computer-
friendly IP address (such as 192.168.1.1). An IP address is given to each device on the Internet, and that
address is necessary to find the appropriate Internet device - like a street address is used to find a particular home.
When a user wants to load a webpage, a translation must occur between what a user types into their web browser
(example.com) and the machine-friendly address necessary to locate the example.com webpage.

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.

There are 4 DNS servers involved in loading a webpage:

 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.

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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.

Recursive DNS resolver


The recursive resolver is the computer that responds to a recursive request from a client and takes the time to track
down the DNS record. It does this by making a series of requests until it reaches the authoritative DNS nameserver
for the requested record (or times out or returns an error if no record is found). Luckily, recursive DNS resolvers do
not always need to make multiple requests in order to track down the records needed to respond to a
client; caching is a data persistence process that helps short-circuit the necessary requests by serving the requested
resource record earlier in the DNS lookup.

Authoritative DNS server


Put simply, an authoritative DNS server is a server that actually holds, and is responsible for, DNS resource records.
This is the server at the bottom of the DNS lookup chain that will respond with the queried resource record,
ultimately allowing the web browser making the request to reach the IP address needed to access a website or other
web resources. An authoritative nameserver can satisfy queries from its own data without needing to query another
source, as it is the final source of truth for certain DNS records.

What are the steps in a DNS lookup?


For most situations, DNS is concerned with a domain name being translated into the appropriate IP address. To learn
how this process works, it helps to follow the path of a DNS lookup as it travels from a web browser, through the
DNS lookup process, and back again. Let's take a look at the steps.
Note: Often DNS lookup information will be cached either locally inside the querying computer or remotely in the
DNS infrastructure. There are typically 8 steps in a DNS lookup. When DNS information is cached, steps are skipped
from the DNS lookup process which makes it quicker. The example below outlines all 8 steps when nothing is
cached.

The 8 steps in a DNS lookup:


1. A user types „example.com‟ into a web browser and the query travels into the Internet and is received
by a DNS recursive resolver.
2. The resolver then queries a DNS root nameserver (.).
3. The root server then responds to the resolver with the address of a Top Level Domain (TLD) DNS
server (such as .com or .net), which stores the information for its domains. When searching for
example.com, our request is pointed toward the .com TLD.
4. The resolver then makes a request to the .com TLD.
5. The TLD server then responds with the IP address of the domain‟s nameserver, example.com.
6. Lastly, the recursive resolver sends a query to the domain‟s nameserver.
7. The IP address for example.com is then returned to the resolver from the nameserver.
8. The DNS resolver then responds to the web browser with the IP address of the domain requested
initially.
Once the 8 steps of the DNS lookup have returned the IP address for example.com, the browser is able to
make the request for the web page:
9. The browser makes a HTTP request to the IP address.
10. The server at that IP returns the webpage to be rendered in the browser (step 10).

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

What is a DNS resolver?


The DNS resolver is the first stop in the DNS lookup, and it is responsible for dealing with the client that made the
initial request. The resolver starts the sequence of queries that ultimately leads to a URL being translated into the
necessary IP address.
It's important to differentiate between a recursive DNS query and a recursive DNS resolver. The query refers to the
request made to a DNS resolver requiring the resolution of the query. A DNS recursive resolver is the computer that
accepts a recursive query and processes the response by making the necessary requests.

What are the types of DNS queries?


In a typical DNS lookup three types of queries occur. By using a combination of these queries, an optimized process
for DNS resolution can result in a reduction of distance traveled. In an ideal situation cached record data will be
available, allowing a DNS name server to return a non-recursive query.
3 types of DNS queries:
1. Recursive query - In a recursive query, a DNS client requires that a DNS server (typically a DNS
recursive resolver) will respond to the client with either the requested resource record or an error
message if the resolver can't find the record.
2. Iterative query - in this situation the DNS client will allow a DNS server to return the best answer it
can. If the queried DNS server does not have a match for the query name, it will return a referral to a
DNS server authoritative for a lower level of the domain namespace. The DNS client will then make a
query to the referral address. This process continues with additional DNS servers down the query
chain until either an error or timeout occurs.
3. Non-recursive query - typically this will occur when a DNS resolver client queries a DNS server for a
record that it has access to either because it's authoritative for the record or the record exists inside of
its cache. Typically, a DNS server will cache DNS records to prevent additional bandwidth consumption
and load on upstream servers.

URL (Uniform Resource Locator)

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.

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

How is a URL structured?


The URL contains the name of the protocol needed to access a resource, as well as a resource name. The first part of
a URL identifies what protocol to use as the primary access medium. The second part identifies the IP address or
domain name -- and possibly subdomain -- where the resource is located.
URL protocols include HTTP (Hypertext Transfer Protocol) and HTTPS (HTTP Secure) for web resources, mail to for
email addresses, FTP for files on a File Transfer Protocol (FTP) server, and telnet for a session to access remote
computers. Most URL protocols are followed by a colon and two forward slashes; "mail to" is followed only by a
colon.
Optionally, after the domain, a URL can also specify:
 a path to a specific page or file within a domain;
 a network port to use to make the connection;
 a specific reference point within a file, such as a named anchor in an HTML file; and
 a query or search parameters used -- commonly found in URLs for search results.

Importance of a URL design


URLs can only be sent over the Internet using the ASCII character-set. Because URLs often contain non-ASCII
characters, the URL must be converted into a valid ASCII format. URL encoding replaces unsafe ASCII characters
with a "%" followed by two hexadecimal digits. URLs cannot contain spaces.
URL examples
When designing URLs, there are different theories about how to make the syntax most usable for readers and
archivists. For example, in the URL's path, dates, authors, and topics can be included in a section referred to as the
"slug." Consider, for example, the URL for this definition:
https://www.techtarget.com/searchnetworking/definition/URL

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.

HTTP vs. HTTPs


Both HTTP and HTTPS are used to retrieve data from a web server to view content in a browser. The difference
between them is that HTTPS uses a Secure Sockets Layer (SSL) certificate to encrypt the connection between the
end user and the server.

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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 vs. URI


A URL is the most common type of Uniform Resource Identifier (URI). URIs are strings of characters used to identify
a resource over a network. URLs are essential to navigating the internet.

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:

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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.

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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.

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

Static web servers vs. Dynamic web servers


A web server can be used to store, process or deliver either static or dynamic web pages. Let's understands the
definition of static and dynamic web servers with the help of their difference table given below:

S.NO. Static Web Servers Dynamic Web Servers

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.

Web server security Methods


Though there are various security techniques available in the market that a user can implement to have a safe web
server experience, below given are some examples of security practices that can include processes:
1. A reverse proxy is a proxy server that is accessible to the clients, therefore hiding the internal server. It
acts as an intermediary as wherever any user makes requests to the web server for any data or file, the
proxy server seizes those requests and then communicates with the webserver.
2. Access restriction is a technique that limits the web host's access to infrastructure machines or using
Secure Socket Shell (SSH);
3. Keeping web servers mended and updated, as it benefits to ensure the web server isn't vulnerable to
exposures;
4. Network monitoring is a security practice that ensures that no unauthorized activity is going on the web
server; and
5. Using a firewall and SSL safeguards the web server as firewalls can supervise HTTP request traffic
while a Secure Sockets Layer (SSL) supports securing the data.

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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 version release year:

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.

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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

Elements can also have attributes. Attributes look like this:

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.

An attribute should have:

 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.

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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;
}

 Selector: selects the element you want to target


 Always remains the same whether we apply internal or external styling
 There are few basic selectors like tags, id‟s, and classes
 All forms this key-value pair
 Keys: properties(attributes) like color, font-size, background, width, height,etc
 Value: values associated with these properties
CSS How-To
 There are 3 ways to write CSS in our HTML file.
o Inline CSS
o Internal CSS
o External CSS
 Priority order
o Inline > Internal > External
Inline CSS
 Before CSS this was the only way to apply styles
 Not an efficient way to write as it has a lot of redundancy
 Self-contained
 Uniquely applied on each element
 The idea of separation of concerns was lost
 Example:
<h3 style=” color:red”> Have a great day </h3>
<p style =” color: green”> I did this , I did that </p>

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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>

<h1>This heading will be green</h1>


<p style="color:Red">This paragraph will be red</p>
<p id="center">This paragraph will be pink and center-aligned</p>

</body>
</html>

This is Css file

#center {
text-align: center;
color:pink;
}

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

{
text-align:center;
color:green;
}

</style>
</head>
<body>

<h1>This heading will be green and center-aligned </h1>


<p class = "center2">This paragraph will be red and center-aligned </p>
<p id ="center1">This paragraph will be pink and center-aligned</p>

</body>
</html>

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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.

How to Run JavaScript?


Being a scripting language, JavaScript cannot run on its own. In fact, the browser is responsible for
running JavaScript code. When a user requests an HTML page with JavaScript in it, the script is sent to the
browser and it is up to the browser to execute it. The main advantage of JavaScript is that all modern web
browsers support JavaScript. So, you do not have to worry about whether your site visitor uses Internet Explorer,
Google Chrome, Firefox or any other browser. JavaScript will be supported. Also, JavaScript runs on any operating
system including Windows, Linux or Mac. Thus, JavaScript overcomes the main disadvantages of VBScript (Now
deprecated) which is limited to just IE and Windows.

Tools You Need

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.

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

A Simple JavaScript Program

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>

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

UNIT – 2

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

Introduction to Server-Side Development with PHP - PHP Arrays and Superglobals - PHP Classes and Objects
Working with Databases Error Handling and Validation

What is server side website programming?


The HyperText Transfer Protocol is used by web browsers to connect with web servers (HTTP). An HTTP request is
sent from your browser to the destination server when you click a link on a web page, submit a form, or conduct a
search.
The request includes a URL that identifies the affected resource, a method that defines the required action (for
example, getting, deleting, or posting the resource), and additional information encoded in URL parameters (field-
value pairs sent via a query string), POST data (data sent via the HTTP POST method), or associated cookies.
Web servers listen for client request messages, process them when they come, and provide an HTTP response
message to the web browser. A status line in the response indicates whether or not the request was successful (e.g.,
"HTTP/1.1 200 OK" for success).
The requested resource (e.g., a new HTML page, an image, etc.) would be contained in the body of a successful
response to a request, which could subsequently be displayed by the web browser.
Static sites
A simple web server architecture for a static site is depicted in the diagram below (a static site is one that returns the
same hard-coded content from the server whenever a particular resource is requested). When a user requests a
page, the browser makes an HTTP "GET" request with the page's URL.
The server obtains the requested document from its file system and sends the document together with a success
status in an HTTP response (usually 200 OK). An error status is issued if the file cannot be retrieved for whatever
reason.
Dynamic sites
A dynamic website is one in which some of the response material is created dynamically and only when it is required.
HTML pages are generally built on a dynamic website by putting data from a database into placeholders in HTML
templates (this is a much more efficient way of storing large amounts of content than using static websites).
A dynamic site can provide varied data for a URL depending on the user's input or saved preferences, as well as
execute additional activities as part of the answer (e.g. sending notifications).
The server must run the majority of the code required to operate a dynamic website. "Server side programming"
is the term used to describe the process of writing this code (or sometimes "back-end scripting").
The graphic below depicts a basic dynamic website architecture. Browsers make HTTP requests to the server, which
the server processes and delivers suitable HTTP replies to, as shown in the preceding diagram.
Requests for static resources (any files that don't change —typically: CSS, JavaScript, Images, pre-created PDF files,
etc.) are handled in the same way as requests for static sites.
Instead, requests for dynamic resources are sent (2) to server side code (shown in the diagram as a Web
Application). The server understands the request, pulls the relevant information from the database (3), mixes the
retrieved data with HTML templates (4), and sends back a response with the created HTML for "dynamic requests"
(5,6).

What is the difference between server side and client-side programming?

 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).

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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.

Efficient storage and delivery of information

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

 It processes the user input


 Displays the requested pages
 Structure of web applications
 Interaction with servers/storages
 Interaction with databases
 Querying the database
 Encoding of data into HTML
 Operations over databases like delete, update

Advantages of server side programming language

 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.

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

Disadvantages of server side programming language

 Debugging web server scripts is tricky.


 Web server scripting is a hacking vulnerability.
 Hosting a web server can be taxing on a computer since it necessitates a big amount of RAM, lowering the system's
speed.

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:-

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

 Dynamically create images


 PDF and SWF files
 Connect to IMAP and POP 3
 Interface with my SQL, oracle, postqre SQL & SQ lite
 Handle electronic payments
 Execute perl, java, com.code
What is a PHP File?
 PHP files can contain text, HTML, CSS, JavaScript, and PHP code
 PHP codes are executed on the server, and the result is returned to the browser as plain HTML
 PHP files have extension ".php"
What Can PHP Do?
 PHP can generate dynamic page content
 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, and modify data in database
 PHP can be used to control user-access
 PHP can encrypt data
 PHP is not limited to output HTML. We can output images, PDF files, and even Flash movies. We can also
output any text, such as XHTML and XML.
Why PHP?
 PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.) PHP is compatible with almost all
servers used today (Apache, IIS, etc.) PHP supports a wide range of databases
 PHP is free. Download it from the official PHP resource: www.php.net PHP is easy to learn and runs
efficiently on the server side
What's new in PHP 7
 PHP 7 is much faster than the previous popular stable release (PHP 5.6) PHP 7 has improved Error Handling
 PHP 7 supports stricter Type Declarations for function arguments PHP 7 supports new operators (like the
spaceship operator: <=>)
PHP Syntax
PHP code is executed on the server, and the plain HTML result is sent to the browser.
Basic PHP Syntax
A PHP scripting block always starts with <?php and ends with ?>. A PHP scripting block can be placed
anywhere in the document.
On servers with shorthand support enabled you can start a scripting block with <? and end with ?>.
For maximum compatibility, we recommend that you use the standard form (<?php) rather than the
shorthand form.
<?php
?>
A PHP file normally contains HTML tags, just like an HTML file, and some PHP scripting code. Below, we have
an example of a simple PHP script which sends the text "Hello World" to the browser:
<html>
<body>
<?php
echo "Hello World";
?>
</body>
</html>
Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish one
set of instructions from another.
There are two basic statements to output text with PHP: echo and print. In the example above we have
used the echo statement to output the text "Hello World".
The file must have the .php extension. If the file has a.html extension, the PHP code will not be executed.
PHP statements and comments

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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.

There are three comment styles listed here:


// this is a single-line comment
# so is this
/* and this is a multiline comment */

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

Enter your message hello Submit

Message. php
<? PHP
// retrieve form data in a variable
$input=$- post[" MSG"];
// print it
echo " you said <i> $input </i>”
?>

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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:

 Integers: are whole numbers, without a decimal point, like 4195.


 Doubles: are floating-point numbers, like 3.14159 or 49.1.
 Booleans: have only two possible values either true or false.
 NULL: is a special type that only has one value: NULL.
 Strings: are sequences of characters, like 'PHP supports string operations.'
 Arrays: are named and indexed collections of other values.
 Objects: are instances of programmer-defined classes, which can package up both other kinds of values
and functions that are specific to the class.
 Resources: are special variables that hold references to resources external to PHP (such as database
connections).
The first five are simple types, and the next two (arrays and objects) are compound - the compound types
can package up other arbitrary values of arbitrary type, whereas the simple types cannot.
The escape-sequence replacements are:
 \n is replaced by the newline character
 \r is replaced by the carriage-return character
 \t is replaced by the tab character
 \$ is replaced by the dollar sign itself ($)
 \" is replaced by a single double-quote (")
 \\ is replaced by a single backslash (\)
Variable Naming
Rules for naming a variable is:
 Variable names must begin with a letter or underscore character.
 A variable name can consist of numbers, letters, underscores but you cannot use characters like + , - , %
, ( , ) . & , etc
 There is no size limit for variables.
Constants:
A constant is used to store fixed values.We can declare and use constants using define() function.
The syntax is
define (" constant name", value);
Example:
define (" gold price",3800);
define (" PI",3.14)
We can use just like a variable. The only difference is the variable will start with $ sign and a constant doesn‟t have
$ sign.The constant name can have small letters (lower case).

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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

include_once instanceof insteadof interface isset list

namespace new or print private protected

public require require_once return static switch

throw trait try unset use var


while xor

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

PHP 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 gets set to the value of the assignment
expression on the right.
Assignment Same as... Description
x=y x=y The left operand gets set to the value of the expression on
the right
x += y x=x+y Addition

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

x -= y x = x -y Subtraction
x *= y x = x *y Multiplication
x /= y x = x /y Division
x %= y x = x %y Modulus

PHP Comparison Operators


The PHP comparison operators are used to compare two values (number or string):
Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x === $y Returns true if $x is equal to $y, and they
are of the same type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!== Not identical $x !== $y Returns true if $x is not equal to $y, or
they are not of the same type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
>= Greater than or equal $x >= $y Returns true if $x is greater than or equal
to to $y
<= Less than or equal to $x <= $y Returns true if $x is less than or equal to
$y
<=> Spaceship $x <=> $y Returns an integer less than, equal to, or
greater than zero, depending on if $x is
less than, equal to, or greater than $y.
Introduced in PHP 7.

PHP 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.
Operator Name Description
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one

PHP Logical Operators


The PHP logical operators are used to combine conditional statements.
Operator Name Example Result
And And $x and $y True if both $x and $y are true
Or Or $x or $y True if either $x or $y is true
Xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true

PHP String Operators


PHP has two operators that are specially designed for strings.
Operator Name Example Result
. Concatenation $txt1 . $txt2 Concatenation of $txt1 and
$txt2
.= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $txt1
PHP Array Operators
The PHP array operators are used to compare arrays.
Operator Name Example Result
+ Union $x + $y Union of $x and $y

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

== Equality $x == $y Returns true if $x and $y have the same


key/value pairs
=== Identity $x === $y Returns true if $x and $y have the same
key/value pairs in the same order and of the
same types
!= Inequality $x != $y Returns true if $x is not equal to $y
<> Inequality $x <> $y Returns true if $x is not equal to $y
!== Non-identity $x !== $y Returns true if $x is not identical to $y

PHP Conditional Assignment Operators


The PHP conditional assignment operators are used to set a value depending on conditions:
Operator Name Example Result
?: Ternary $x = expr1 ? expr2 : expr3 Returns the value of $x.
The value of $x is expr2 if expr1 =
TRUE.
The value of $x is expr3 if expr1 =
FALSE

PHP Conditional Statements


Very often when you write code, you want to perform different actions for different conditions. You can use
conditional statements in your code to do this.
In PHP we have the following conditional statements:
 if statement - executes some code if one condition is true
 if...else statement - executes some code if a condition is true and another code if that condition is false
 if...elseif...else statement - executes different codes for more than two conditions
 switch statement - selects one of many blocks of code to be executed
PHP - The if Statement
The if statement executes some code if one condition is true.
Syntax
if (condition)
{
code to be executed if condition is true;
}
Example
Output "Have a good day!" if the current time (HOUR) is less than 20:
<?php
$t = date("H");
if ($t < "20")
{
echo "Have a good day!";
}
?>
PHP - The if...else Statement
The if...else statement executes some code if a condition is true and another code if that condition is false.
Syntax
if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}
Example

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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!";
}
?>

PHP switch Statement


The switch statement is used to perform different actions based on different conditions.
The PHP switch Statement
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;
}
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

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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,

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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) {

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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;

while($x < 10) {


if ($x == 4) {
$x++;
continue;
}
echo "The number is: $x <br>";
$x++;
}
?>

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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";

The ID keys can be used in a script:


<?php
$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";
echo $names[1] . " and " . $names[2] . " are ". $names[0] . "'s neighbors";
?>
The code above will output:
Quagmire and Joe are Peter's neighbors
Associative Arrays
An associative array, each ID key is associated with a value. When storing data about specific named
values, a numerical array is not always the best way to do it.
With associative arrays we can use the values as keys and assign values to them.
Example 1
In this example we use an array to assign ages to the different persons:
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
Example 2
This example is the same as example 1, but shows a different way of creating the array:
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";

The ID keys can be used in a script:


<?php
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
echo "Peter is " . $ages['Peter'] . " years old.";
?>
The code above will output:
Peter is 32 years old.

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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?

Processing array with loop:


In PHP we can process arrays using loops like for, while, etc..
We also have a special loop in PHP known as for each loop for array processing. Example for array processing with
loop
<html>
<head></head>
<body>
Today shopping list;
<ul>
<?php
$shoppinglist=array(„green gram‟,‟bengal gram‟,‟rice‟);
for($x=0;$x< sizeof($shoppinglist);x++)
{
echo<li>$shoppinglist[$x];
}
?>
</ul>
</body>
</html>
In this example for loop is used to interact with the array. This loops extract elements from the
array and prints in the screen one after another as an order list. The sizeof() function returns the number
of elements in the array.
foreach loop()
This loop runs for each element of the array movning through the element of array on each
interation. In for loop, we have condition statement and iteration(increment/decrement) statement.

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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>

For each loop for an associative array:


Consider the following example for associative array
< html>
< head></ head>
< body>
$ can see
<ul>
<?php
// define associative array
$ animals=array(' dog'='Tripsy',' cat'=>‟Tabitha‟, 'parrot'='polly)';
//iterate over it
foreach($ animal as $ key=$ value)
{
echo"</ u>A $ key name $ value";
}
?>
</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,

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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:

 It provides a clear modular structure for the programs.


 It helps you adhere to the "don't repeat yourself" (DRY) principle, and thus make your code much easier to
maintain, modify and debug.
 It makes it possible to create more complicated behavior with less code and shorter development time and high
degree of reusability.

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.

The Object Oriented concepts in PHP are:

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

 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.

Class & Object:

Understanding Classes and Objects

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.

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

 Class is a collection of objects. Object has properties and behaviour.

<?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/-

Creating Objects in PHP


When class is created, we can create any number of objects in that class. The object is created with the help of the
new keyword.
Calling Member Function
When the object is created we can access the variables and method function of the class with the help of operator „-
>, accessing the method is done to get the information of that method.
<?php
class Mobile {
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par){
$this->price = $par;
}
function getPrice(){
echo $this->price ."<br/>";
}
function setName($par){
$this->title = $par;
}
function getName(){
echo $this->title ." <br/>";
}
}
$Samsung = new Mobile();
$Xiaomi = new Mobile();
$Iphone = new Mobile();
$Samsung->setName( "SamsungS8 );
$Iphone->setName( "Iphone7s" );
$Xiaomi->setName( "MI4" );
$Samsung->setPrice( 90000 );
$Iphone->setPrice( 65000 );
$Xiaomi->setPrice( 15000 );
Now you call another member functions to get the values set by in above example
$Samsung->getName();
$Iphone->getName();
$Xiaomi->getName();

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

$Samsung->getPrice();
$Iphone->getPrice(); $Xiaomi->getPrice(); ?>

Output for the above code


Samsung S8
Iphone S7
MI4
90000
65000
15000
Using Constructors and Destructors
To make the object-oriented programming easier, PHP provides some magic methods that are executed
automatically when certain actions occur within an object.
For example, the magic method __construct() (known as constructor) is executed automatically whenever a
new object is created. Similarly, the magic method __destruct() (known as destructor) is executed automatically
when the object is destroyed. A destructor function cleans up any resources allocated to an object once the object is
destroyed.
<?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;
// Output a message at the end of the file
echo "The end of the file is reached.";
?>
The PHP code in the above example will produce the following output:

The class "MyClass" was initiated!


The end of the file is reached.
The class "MyClass" was destroyed.

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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:

The class "MyClass" was initiated!


The class "MyClass" was destroyed.
The end of the file is reached.

 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

Controlling the Visibility of Properties and Methods

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.

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

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
?>

Static Properties and Methods

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:

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

<?php
// Class definition
class HelloClass
{
// Declare a static property
public static $greeting = "Hello World!";

// Declare a static method


public static function sayHello(){
echo self::$greeting;
}
}
// Attempt to access static property and method directly
echo HelloClass::$greeting; // Output: Hello World!
HelloClass::sayHello(); // Output: Hello World!
// Attempt to access static property and method via object
$hello = new HelloClass;
echo $hello->greeting; // Strict Warning
$hello->sayHello(); // Output: Hello World!
?>
The keyword self in the above example means "the current class". It is never preceded by a dollar sign ($) and
always followed by the :: operator (e.g. self::$name).

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

1. Single Level Inheritance


2. Multilevel 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.

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

Single Level Inheritance

<?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';

Valluvar College of Science and Management - Karur


Add-on Course Full Stack Web Development 2021-2022

}
}
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

Valluvar College of Science and Management - Karur

You might also like