Introduction To Web Application Development

Download as pdf or txt
Download as pdf or txt
You are on page 1of 148

WEB APPLICATION DEVELOPMENT

1. DEFITINTION OF TERMS
The term "web" is an abbreviation for the World Wide Web (WWW) and refers to a vast
system of interconnected documents and resources that are accessible over the internet. It is
not a physical entity but rather a digital network of information that allows users to access
and navigate a wide range of content from all around the world.
The World Wide Web was invented by Sir Tim Berners-Lee in 1989 while he was working at
CERN (European Organization for Nuclear Research). It was originally designed as a way for
scientists to share research information and collaborate more effectively. However, its scope
quickly expanded, and it became a global platform for information dissemination,
communication, and commerce.
Key characteristics of the web include:
1. Hypertext: The web is based on the concept of hypertext, which allows users to
navigate between different pieces of information by clicking on hyperlinks.
Hyperlinks are clickable elements on web pages that connect one web page to
another, enabling seamless navigation and exploration of the web.
2. Web Pages: Web pages are individual documents written in HTML (Hypertext
Markup Language), containing text, images, videos, and interactive elements. They
form the building blocks of the web and are viewed through web browsers.
3. Web Browsers: Web browsers are software applications that allow users to access
and view web pages. Examples of popular web browsers include Google Chrome,
Mozilla Firefox, Microsoft Edge, Safari, and Opera.
4. URLs (Uniform Resource Locators): URLs are unique addresses used to identify
and locate specific resources on the web. They serve as the means for users and web
browsers to find and access web pages or files.
5. Web Servers: Web servers are computers or software that store and serve web
content to users when requested. They handle the distribution of web pages and
resources in response to users' requests made through web browsers.
6. HTTP (Hypertext Transfer Protocol): HTTP is the primary protocol used to transfer
data over the web. It defines the rules for communication between web browsers and
web servers, allowing the retrieval of web pages and resources.
The web has had a profound impact on society and has revolutionized how people access
information, communicate, conduct business, and share knowledge. It has become an
essential part of modern life, connecting people from different parts of the world and enabling
the sharing of ideas and culture on an unprecedented scale. The web continues to evolve, with
new technologies and applications constantly being developed to enhance its capabilities and
expand its reach.

1
The Architecture of the World Wide Web •
The Web has a client/server architecture •
Programs on servers communicate and share files with client workstations over a network
Clients and servers
Computers connected to the internet are called clients and servers. A simplified diagram of
how they interact might look like this:
• Clients are the typical web user's internet-connected devices (for example, your
computer connected to your Wi-Fi, or your phone connected to your mobile network)
and web-accessing software available on those devices (usually a web browser like
Firefox or Chrome).
• Servers are computers that store webpages, sites, or apps. When a client device wants
to access a webpage, a copy of the webpage is downloaded from the server onto the
client machine to be displayed in the user's web browser.
The other parts of the toolbox
The client and server we've described above don't tell the whole story. There are many other
parts involved, and we'll describe them below.
For now, let's imagine that the web is a road. On one end of the road is the client, which is
like your house. On the other end of the road is the server, which is a shop you want to buy
something from.
In addition to the client and the server, we also need to say hello to:
• Your internet connection: Allows you to send and receive data on the web. It's
basically like the street between your house and the shop.
• TCP/IP: Transmission Control Protocol and Internet Protocol are communication
protocols that define how data should travel across the internet. This is like the
transport mechanisms that let you place an order, go to the shop, and buy your goods.
In our example, this is like a car or a bike (or however else you might get around).
• DNS: Domain Name System is like an address book for websites. When you type a
web address in your browser, the browser looks at the DNS to find the website's IP
address before it can retrieve the website. The browser needs to find out which server
the website lives on, so it can send HTTP messages to the right place (see below).
This is like looking up the address of the shop so you can access it.

2
• HTTP: Hypertext Transfer Protocol is an application protocol that defines a language
for clients and servers to speak to each other. This is like the language you use to
order your goods.
• Component files: A website is made up of many different files, which are like the
different parts of the goods you buy from the shop. These files come in two main
types:
o Code files: Websites are built primarily from HTML, CSS, and JavaScript,
though you'll meet other technologies a bit later.
o Assets: This is a collective name for all the other stuff that makes up a
website, such as images, music, video, Word documents, and PDFs.
So what happens, exactly?
When you type a web address into your browser (for our analogy that's like walking to the
shop):
1. The browser goes to the DNS server, and finds the real address of the server that the
website lives on (you find the address of the shop).
2. The browser sends an HTTP request message to the server, asking it to send a copy of
the website to the client (you go to the shop and order your goods). This message, and
all other data sent between the client and the server, is sent across your internet
connection using TCP/IP.
3. If the server approves the client's request, the server sends the client a "200 OK"
message, which means "Of course you can look at that website! Here it is", and then
starts sending the website's files to the browser as a series of small chunks called data
packets (the shop gives you your goods, and you bring them back to your house).
4. The browser assembles the small chunks into a complete web page and displays it to
you (the goods arrive at your door — new shiny stuff, awesome!).
Order in which component files are parsed
When browsers send requests to servers for HTML files, those HTML files often
contain <link> elements referencing external CSS stylesheets and <script> elements
referencing external JavaScript scripts. It's important to know the order in which those files
are parsed by the browser as the browser loads the page:
• The browser parses the HTML file first, and that leads to the browser recognizing
any <link>-element references to external CSS stylesheets and any <script>-element
references to scripts.
• As the browser parses the HTML, it sends requests back to the server for any CSS
files it has found from <link> elements, and any JavaScript files it has found
from <script> elements, and from those, then parses the CSS and JavaScript.
• The browser generates an in-memory DOM tree from the parsed HTML, generates an
in-memory CSSOM structure from the parsed CSS, and compiles and executes the
parsed JavaScript.

3
• As the browser builds the DOM tree and applies the styles from the CSSOM tree and
executes the JavaScript, a visual representation of the page is painted to the screen,
and the user sees the page content and can begin to interact with it.
DNS explained
Real web addresses aren't the nice, memorable strings you type into your address bar to find
your favourite websites. They are special numbers that look like this: 192.0.2.172.
This is called an IP address, and it represents a unique location on the web. However, it's not
very easy to remember, is it? That's why the Domain Name System was invented. This
system uses special servers that match up a web address you type into your browser (like
"mozilla.org") to the website's real (IP) address.
Websites can be reached directly via their IP addresses. You can use a DNS lookup tool to
find the IP address of a website.
Packets explained
Earlier we used the term "packets" to describe the format in which the data is sent from
server to client. What do we mean here? Basically, when data is sent across the web, it is sent
in thousands of small chunks. There are multiple reasons why data is sent in small packets.
They are sometimes dropped or corrupted, and it's easier to replace small chunks when this
happens. Additionally, the packets can be routed along different paths, making the exchange
faster and allowing many different users to download the same website at the same time. If
each website was sent as a single big chunk, only one user could download it at a time, which
obviously would make the web very inefficient and not much fun to use.

What is HTTP?
HTTP (Hypertext Transfer Protocol) is the set of rules for transferring files -- such as text,
images, sound, video and other multimedia files -- over the web. As soon as a user opens their
web browser, they are indirectly using HTTP. Concisely, HTTP is an application-layer
protocol for transmitting hypermedia documents, such as HTML. It was designed for
communication between web browsers and web servers, but it can also be used for other
purposes. HTTP follows a classical client-server model, with a client opening a connection to
make a request, then waiting until it receives a response. HTTP is a stateless protocol,
meaning that the server does not keep any data (state) between two requests.
HTTP is an application protocol that runs on top of the TCP/IP suite of protocols, which
forms the foundation of the internet. The latest version of HTTP is HTTP/2, which was
published in May 2015. It is an alternative to its predecessor, HTTP 1.1, but does not it make
obsolete.

How HTTP works


Through the HTTP protocol, resources are exchanged between client devices and servers over
the internet. Client devices send requests to servers for the resources needed to load a web
page; the servers send responses back to the client to fulfill the requests. Requests and
responses share sub-documents -- such as data on images, text, text layouts, etc. -- which are
pieced together by a client web browser to display the full web page file.
In addition to the web page files it can serve, a web server contains an HTTP daemon, a
program that waits for HTTP requests and handles them when they arrive. A web browser is

4
an HTTP client that sends requests to servers. When the browser user enters file requests by
either "opening" a web file by typing in a URL or clicking on a hypertext link, the browser
builds an HTTP request and sends it to the Internet Protocol address (IP address) indicated by
the URL. The HTTP daemon in the destination server receives the request and sends back the
requested file or files associated with the request.

Client devices use HTTP to communicate with servers online and access web pages.

5
To expand on this example, a user wants to visit TechTarget.com. The user types in the web
address and the computer sends a "GET" request to a server that hosts that address. That GET
request is sent using HTTP and tells the TechTarget server that the user is looking for
the HTML (Hypertext Markup Language) code used to structure and give the login page its
look and feel. The text of that login page is included in the HTML response, but other parts of
the page -- particularly its images and videos -- are requested by separate HTTP requests and
responses. The more requests that are made -- for example, to call a page that has numerous
images -- the longer it will take the server to respond to those requests and for the user's
system to load the page.
When these request/response pairs are being sent, they use TCP/IP to reduce and transport
information in small packets of binary sequences of ones and zeros. These packets are
physically sent through electric wires, fibre optic cables and wireless networks.
The requests and responses that servers and clients use to share data with each other consist
of ASCII code. Requests state what information the client is seeking from the server;
responses contain code that the client browser will translate into a web page.

HTTP vs. HTTPS


HTTPS is the use of Secure Sockets Layer (SSL) or Transport Layer Security (TLS) as a
sublayer under regular HTTP application layering. HTTPS encrypts and decrypts user HTTP
page requests as well as the pages that are returned by the web server. It also protects against
eavesdropping and man-in-the-middle (MitM) attacks. HTTPS was developed
by Netscape. Migrating from HTTP to HTTPS is considered beneficial, as it offers an
added layer of security and trust.

HTTP requests and responses


Each interaction between the client and server is called a message. HTTP messages are
requests or responses. Client devices submit HTTP requests to servers, which reply by
sending HTTP responses back to the clients.
HTTP requests. This is when a client device, such as an internet browser, asks the server for
the information needed to load the website. The request provides the server with the desired
information it needs to tailor its response to the client device. Each HTTP request contains
encoded data, with information such as:
• The specific version of HTTP followed. HTTP and HTTP/2 are the two versions.

6
• A URL. This points to the resource on the web.
• An HTTP method. This indicates the specific action the request expects to receive
from the server in its response.
• HTTP request headers. This includes data such as what type of browser is being
used and what data the request is seeking from the server. It can also include cookies,
which show information previously sent from the server handling the request.
• An HTTP body. This is optional information the server needs from the request, such
as user forms -- username/password logins, short responses and file uploads -- that are
being submitted to the website.
HTTP responses. The HTTP response message is the data received by a client device from
the web server. As its name suggests, the response is the server's reply to an HTTP request.
The information contained in an HTTP response is tailored to the context the server received
from the request. HTTP responses typically include the following data:
• HTTP status code, which indicates the status of the request to the client device.
Responses may indicate success, an informational response, a redirect, or errors on
the server or client side.
• HTTP response headers, which send information about the server and requested
resources.
• An HTTP body (optional). If a request is successful, this contains the requested data
in the form of HTML code, which is translated into a web page by the client browser.
Types of Requests
All requests must be sent using an HTTP method. Using the HTTP method, you designate the
action you wish to perform. The methods/actions are also known as HTTP verbs.
HTTP request methods
HTTP defines a set of request methods to indicate the desired action to be performed for a
given resource. Although they can also be nouns, these request methods are sometimes
referred to as HTTP verbs. Each of them implements a different semantic, but some common
features are shared by a group of them: e.g., a request method can be safe, idempotent, or
cacheable.

HTTP Method Description


GET Every time you access a website, you are performing a GET method. It
retrieves data from the server. OR
The GET method requests a representation of the specified resource.
Requests using GET should only retrieve data.
POST The POST method submits an entity to the specified resource, often
causing a change in state or side effects on the server.
HEAD The HEAD method asks for a response identical to a GET request, but
without the response body.

7
PUT The PUT method replaces all current representations of the target
resource with the request payload.

DELETE The DELETE method deletes the specified resource.


CONNECT The CONNECT method establishes a tunnel to the server identified by
the target resource.
OPTIONS The OPTIONS method describes the communication options for the
target resource.
TRACE The TRACE method performs a message loop-back test along the path
to the target resource.

PATCH The PATCH method applies partial modifications to a resource.

It is a best practice to force your website and server resources to match the expected request.
If you receive an HTTP method different than what your application or website is expecting
to handle, it must either ignore or reject the request.
HTTP status codes
In response to HTTP requests, servers often issue response codes, indicating the request is
being processed, there was an error in the request or that the request is being redirected.
Common response codes include:
• 200 OK. This means that the request, such as GET or POST, worked and is being
acted upon.
• 300 Moved Permanently. This response code means that the URL of the requested
resource has been changed permanently.
• 401 Unauthorized. The client, or user making the request of the server, has not been
authenticated.
• 403 Forbidden. The client's identity is known but has not been given access
authorization.
• 404 Not Found. This is the most frequent error code. It means that the URL is not
recognized or the resource at the location does not exist.
• 500 Internal Server Error. The server has encountered a situation it doesn't know
how to handle.
General categories for HTTP Status Codes

Values Type Description

Informational
1xx Request received, continuing process.
Responses

2xx Success Responses The action was successfully received, understood, and

8
accepted.

Further action must be taken in order to complete the


3xx Redirection Messages
request.

Client Error
4xx The request contains bad syntax or cannot be fulfilled.
Responses

Server Error
5xx The server failed to fulfill an apparently valid request.
Responses

The above defines general categories for HTTP Status Codes. However, each category has
several more specific codes within it. In the following table, you can review some of the more
common, specific status codes you may encounter.

HTTP Code Meaning Description

The request was successfully processed by the


200 OK
server.

The request was fulfilled and a new resource


201 Created
was created.

Moved The URL has been moved to a different


301
Permanently location permanently.

Found
The URL has been moved to a different
302 (Temporarily
location temporarily.
Moved)

The server couldn’t understand the request,


400 Bad Request usually caused by a bad syntax or a
malformed URL.

The URL requires authentication, the required


401 Unauthorized
credentials are not present or wrong.

403 Forbidden The server refused to respond to the request.

9
The requested resource is not available on the
404 Not Found
server, but it may come back in the future.

The requested resource is permanently


410 Gone
unavailable.

Internal Server The server had an internal issue fulfilling the


500
Error request.

Service
503 The server is currently unavailable.
Unavailable

The request took longer than the server


504 Gateway Timeout
expected.

Proxies in HTTP
Proxies, or proxy servers, are the application-layer servers, computers or other machines that
go between the client device and the server. Proxies relay HTTP requests and responses
between the client and server. Typically, there are one or more proxies for each client-server
interaction.
Proxies may be transparent or non-transparent. Transparent proxies do not modify the client's
request but rather send it to the server in its original form. Non-transparent proxies will
modify the client's request in some capacity. Non-transparent proxies can be used for
additional services, often to increase the server's retrieval speed.

Proxy servers are intermediaries between clients (such as web browsers) and other servers on
the internet. When a client makes a request to access a resource (such as a web page, file, or
service), the request is first sent to the proxy server. The proxy server then forwards the
request to the target server, retrieves the response, and sends it back to the client. In this
process, the client and the target server may not directly communicate with each other, as the
proxy server acts as a middleman.
Proxy servers offer various functionalities and serve different purposes, including:
1. Anonymity and Privacy: Proxy servers can hide the client's IP address from the
target server. This provides a level of anonymity, as the target server only sees the IP
address of the proxy server, not the original client's IP. It can help users maintain
privacy and bypass geo-restrictions.

10
2. Caching: Proxy servers can cache frequently accessed resources. When a client
requests a resource that is already stored in the proxy's cache, the proxy can serve the
cached version instead of fetching it from the target server. Caching improves
performance by reducing response times and easing the load on the target server.
3. Content Filtering and Access Control: Proxy servers can be used to filter web
content based on specific rules, such as blocking access to certain websites or content
categories. They can also enforce access control policies, allowing or denying access
to specific resources.
4. Load Balancing: In some cases, proxy servers are employed to distribute incoming
client requests across multiple target servers, a technique known as load balancing.
This helps evenly distribute the workload and ensures optimal resource utilization.
5. Security and Firewall Protection: Proxy servers can act as an additional layer of
security, inspecting incoming and outgoing traffic for potential threats. They can help
protect internal networks from unauthorized access and defend against various
attacks, such as Distributed Denial of Service (DDoS) attacks.
6. Content Modification: Some proxy servers can modify the content of requests or
responses before forwarding them. This feature is often used for data compression,
translation, or encryption.
7. Traffic Monitoring and Logging: Proxy servers can log and analyze client requests
and server responses, providing administrators with valuable insights into network
usage and potential issues.
Proxy servers can be set up at various levels, including client-side proxies and server-side
proxies. Client-side proxies are configured within the client's network settings, while server-
side proxies are set up on the server-side infrastructure to handle incoming client requests.
Overall, proxy servers offer flexibility, security, and performance benefits, making them
valuable tools for various use cases in both corporate and individual environments.

Identifying resources on the Web


The target of an HTTP request is called a "resource", whose nature isn't defined further; it can
be a document, a photo, or anything else. Each resource is identified by a Uniform Resource
Identifier (URI) used throughout HTTP for identifying resources.

URL
Uniform Resource Locator (URL) is a text string that specifies where a resource (such as a
web page, image, or video) can be found on the Internet. In the context of HTTP, URLs are
called "Web address" or "link". Your browser displays URLs in its address bar, for example:
https://developer.mozilla.org. Some browsers display only the part of a URL after the "//",
that is, the Domain name.
URLs can also be used for file transfer (FTP), emails (SMTP), and other applications.

Basics: Anatomy of a URL


Here are some examples of URLs:

11
https://developer.mozilla.org
https://developer.mozilla.org/en-US/docs/Learn/
https://developer.mozilla.org/en-US/search?q=URL
Any of those URLs can be typed into your browser's address bar to tell it to load the
associated page (resource).
A URL is composed of different parts, some mandatory and others optional. The most
important parts are highlighted on the URL below (details are provided in the following
sections):

Note: You might think of a URL like a regular postal mail address: the scheme represents the
postal service you want to use, the domain name is the city or town, and the port is like the
zip code; the path represents the building where your mail should be delivered;
the parameters represent extra information such as the number of the apartment in the
building; and, finally, the anchor represents the actual person to whom you've addressed your
mail.

Note: There are some extra parts and some extra rules regarding URLs, but they are not
relevant for regular users or Web developers. Don't worry about this, you don't need to know
them to build and use fully functional URLs.

Scheme

The first part of the URL is the scheme, which indicates the protocol that the browser must
use to request the resource (a protocol is a set method for exchanging or transferring data
around a computer network). Usually for websites the protocol is HTTPS or HTTP (its
unsecured version). Addressing web pages requires one of these two, but browsers also know
how to handle other schemes such as mailto: (to open a mail client), so don't be surprised if
you see other protocols.

Authority

12
Next follows the authority, which is separated from the scheme by the character pattern ://. If
present the authority includes both the domain (e.g. www.example.com) and the port (80),
separated by a colon:
• The domain indicates which Web server is being requested. Usually this is a
domain name, but an IP address may also be used (but this is rare as it is much
less convenient).
• The port indicates the technical "gate" used to access the resources on the web
server. It is usually omitted if the web server uses the standard ports of the
HTTP protocol (80 for HTTP and 443 for HTTPS) to grant access to its
resources. Otherwise, it is mandatory.
Note: The separator between the scheme and authority is ://. The colon separates the scheme
from the next part of the URL, while // indicates that the next part of the URL is the authority.
One example of a URL that doesn't use an authority is the mail client (mailto:foobar). It
contains a scheme but doesn't use an authority component. Therefore, the colon is not
followed by two slashes and only acts as a delimiter between the scheme and mail address.

Path to resource

?key1=value1&key2=value2 are extra parameters provided to the Web server. Those


parameters are a list of key/value pairs separated with the & symbol. The Web server can use
those parameters to do extra stuff before returning the resource. Each Web server has its own
rules regarding parameters, and the only reliable way to know if a specific Web server is
handling parameters is by asking the Web server owner.

Anchor

#SomewhereInTheDocument is an anchor to another part of the resource itself. An anchor


represents a sort of "bookmark" inside the resource, giving the browser the directions to show
the content located at that "bookmarked" spot. On an HTML document, for example, the
browser will scroll to the point where the anchor is defined; on a video or audio document,
the browser will try to go to the time the anchor represents. It is worth noting that the part
after the #, also known as the fragment identifier, is never sent to the server with the request.

What is three-tier architecture?


Three-tier architecture is a well-established software application architecture that organizes
applications into three logical and physical computing tiers: the presentation tier, or user
interface; the application tier, where data is processed; and the data tier, where the data
associated with the application is stored and managed.

13
The chief benefit of three-tier architecture is that because each tier runs on its own
infrastructure, each tier can be developed simultaneously by a separate development team,
and can be updated or scaled as needed without impacting the other tiers.
For decades three-tier architecture was the prevailing architecture for client-server
applications. Today, most three-tier applications are targets for modernization, using cloud-
native technologies such as containers and microservices, and for migration to the cloud.
The three tiers in detail
Presentation tier
The presentation tier is the user interface and communication layer of the application, where
the end user interacts with the application. Its main purpose is to display information to and
collect information from the user. This top-level tier can run on a web browser, as desktop
application, or a graphical user interface (GUI), for example. Web presentation tiers are
usually developed using HTML, CSS and JavaScript. Desktop applications can be written in
a variety of languages depending on the platform.
Application tier
The application tier, also known as the logic tier or middle tier, is the heart of the application.
In this tier, information collected in the presentation tier is processed - sometimes against
other information in the data tier - using business logic, a specific set of business rules. The
application tier can also add, delete or modify data in the data tier.
The application tier is typically developed using Python, Java, Perl, PHP or Ruby, and
communicates with the data tier using API calls.
Data tier
The data tier, sometimes called database tier, data access tier or back-end, is where the
information processed by the application is stored and managed. This can be
a relational database management system such as PostgreSQL, MySQL, MariaDB, Oracle,
DB2, Informix or Microsoft SQL Server, or in a NoSQL Database server such as
Cassandra, CouchDB or MongoDB.
In a three-tier application, all communication goes through the application tier. The
presentation tier and the data tier cannot communicate directly with one another.
These three tiers constitute a common three-tier architecture, also known as the client-server
architecture. The client (presentation tier) communicates with the server (application and data
tiers) through well-defined interfaces (APIs) or protocols like HTTP. This architectural
pattern promotes modularity, scalability, and maintainability of the application.
Apart from the three-tier architecture, more complex applications may adopt multi-tier
architectures, including additional layers for specific purposes like caching, security,
messaging, and external services integration. Some applications might also use a
microservices architecture, where different functional components are developed and
deployed independently, each having its own API and database, and communication between
services is usually facilitated through APIs or messaging protocols.
It's important to note that the choice of the application's architecture depends on the specific
requirements, complexity, scalability, and other factors that influence the development
process. Each tier's separation allows developers to focus on specific aspects of the
application, promoting code reusability and easier maintenance.

14
Tier vs. layer
In discussions of three-tier architecture, layer is often used interchangeably – and
mistakenly – for tier, as in 'presentation layer' or 'business logic layer.'
They aren't the same. A 'layer' refers to a functional division of the software, but a 'tier' refers
to a functional division of the software that runs on infrastructure separate from the other
divisions. The Contacts app on your phone, for example, is a three-layer application, but
a single-tier application, because all three layers run on your phone.
The difference is important, because layers can't offer the same benefits as tiers.

Benefits of three-tier architecture


Again, the chief benefit of three-tier architecture its logical and physical separation of
functionality. Each tier can run on a separate operating system and server platform - e.g., web
server, application server, database server - that best fits its functional requirements. And each
tier runs on at least one dedicated server hardware or virtual server, so the services of each
tier can be customized and optimized without impact the other tiers.
Other benefits (compared to single- or two-tier architecture) include:
• Faster development: Because each tier can be developed simultaneously by different
teams, an organization can bring the application to market faster, and programmers
can use the latest and best languages and tools for each tier.
• Improved scalability: Any tier can be scaled independently of the others as needed.
• Improved reliability: An outage in one tier is less likely to impact the availability or
performance of the other tiers.
• Improved security: Because the presentation tier and data tier can't communicate
directly, a well-designed application tier can function as a sort of internal firewall,
preventing SQL injections and other malicious exploits.
Three-tier application in web development
In web development, the tiers have different names but perform similar functions:
• The web server is the presentation tier and provides the user interface. This is usually
a web page or web site, such as an ecommerce site where the user adds products to the
shopping cart, adds payment details or creates an account. The content can be static or
dynamic, and is usually developed using HTML, CSS and JavaScript.

• The application server corresponds to the middle tier, housing the business logic
used to process user inputs. To continue the ecommerce example, this is the tier that
queries the inventory database to return product availability, or adds details to a
customer's profile. This layer often developed using Python, Ruby or PHP and runs a
framework such as e Django, Rails, Symphony or ASP.NET, for example.

• The database server is the data or backend tier of a web application. It runs on
database management software, such as MySQL, Oracle, DB2 or PostgreSQL, for
example.

15
Other multi-tier architectures
While three-tier architecture is easily the most widely-adopted multi-tier application
architecture, there are others you might encounter in your work or your research.
Two-tier architecture
Two-tier architecture is the original client-server architecture, consisting of a presentation tier
and a data tier; the business logic lives in the presentation tier, the data tier or both. In two-
tier architecture the presentation tier - and consequently the end user - has direct access to the
data tier, and the business logic is often limited. A simple contact management application,
where users can enter and retrieve contact data, is an example of a two-tier application.
N-tier architecture
N-tier architecture - also called or multi-tier architecture - refers to any application
architecture with more than one tier. But applications with more than three layers are rare,
because additional layers offer few benefits and can make the application slower, harder to
manage and more expensive to run. As a result, n-tier architecture and multi-tier architecture
are usually synonyms for three-tier architecture.

16
2. Web Application Development:
Web application development is a dynamic and ever-evolving field of software development
focused on creating applications that run on web browsers. These applications leverage web
technologies such as HTML, CSS, and JavaScript, along with various backend technologies,
to provide users with interactive, responsive, and feature-rich experiences over the internet.
Web applications have become an integral part of modern life, as they empower businesses,
organizations, and individuals to deliver services, interact with users, and manage data
efficiently.

The development of web applications involves a combination of front-end and back-end


technologies, along with various frameworks, libraries, and tools. Here's a detailed overview
of the key components and stages involved in web application development:
1. Client-Side (Front-End) Development
2. Server-Side (Back-End) Development
3. APIs (Application Programming Interfaces)
4. Web Servers and Hosting
5. Security
6. Testing
7. Deployment
8. Maintenance and Updates

1. Client-Side (Front-End) Development:


The front-end of a web application refers to the user interface (UI) and user experience (UX)
that users interact with directly. Front-end developers work on designing, coding, and
optimizing the visual elements and interactive features of the application. They utilize
technologies like HTML for structuring the content, CSS for styling and layout, and

17
JavaScript for adding interactivity and functionality. Modern front-end development also
involves the use of front-end libraries and frameworks like React, Angular, or Vue.js to
streamline development and create responsive and user-friendly interfaces.

Key technologies are


HTML: It provides the structure and content of the web page through a series of tags that
define headings, paragraphs, images, links, forms, and more.
CSS: It controls the presentation and layout of the HTML elements, ensuring the application
looks visually appealing and responsive on different devices.
JavaScript: This is a powerful scripting language used to add interactivity and dynamic
features to web pages. It enables actions like form validation, animations, and real-time
updates.

Who is a front-end developer?


A front-end developer is a type of software developer who specializes in creating and designing the
user interface (UI) and user experience (UX) of websites and web applications. The primary
responsibility of a front-end developer is to ensure that the visual and interactive aspects of a website
or application are user-friendly, aesthetically pleasing, and functionally efficient.
Front-end developers work with various technologies, tools, and languages, including:
1. HTML (HyperText Markup Language): The standard markup language used to create
the structure and layout of web pages.
2. CSS (Cascading Style Sheets): A stylesheet language used to control the presentation,
formatting, and appearance of web pages, such as colors, fonts, and layout.
3. JavaScript: A programming language that allows developers to add interactivity,
animations, and other dynamic elements to websites and web applications.
Front-end developers may also use libraries and frameworks, such as React, Angular, or
Vue.js, to streamline their work and create more sophisticated and interactive UIs.
Additionally, they often collaborate with back-end developers, who are responsible for the
server-side logic and data management, to ensure seamless integration between the front-end
and back-end components of a web application or website.

HTML, CSS, & JavaScript:


A front-end developer architects and develops websites and applications using web
technologies (i.e., HTML, CSS, DOM, and JavaScript), which run on the Open Web
Platform or act as compilation input for non-web platform environments (i.e., React Native).

18
Typically, a person enters into the field of front-end development by learning to develop
HTML, CSS, and JavaScript which commonly runs in a web browser but can also run in
a headless browser, or as compilation input for a native runtime environment. These four run
times scenarios are explained below.

Web Browsers (most common)


A web browser is software used to retrieve, present, and traverse information on the WWW.
Typically, browsers run on a desktop or laptop computer, tablet, or phone, but as of late a
browser can be found on just about anything (i.e, on a fridge, in cars, etc.).
The most common web browsers are (shown in order of most used first):
• Chrome
• Safari
• Microsoft Edge
• Firefox
Headless Browsers
Headless browsers are a web browser without a graphical user interface that can be
controlled from a command line interface programmatically for the purpose of web page
automation (e.g., functional testing, scraping, unit testing, etc.). Think of headless browsers
as a browser that you can run from the command line that can retrieve and traverse web
pages.
The most common headless browsers are:
• Headless Chromium
• Zombie
• slimerjs

Webviews

19
Webviews are used by a native OS, in a native application, to run web pages. Think of
a webview like an iframe or a single tab from a web browser that is embedded in a native
application running on a device (e.g., iOS, android, windows).
The most common solutions for webview development are:
• Electron (typically used for desktop apps)
• Tauri.js
• Cordova (typically for native phone/tablet apps)
• NW.js (typically used for desktop apps)
Native from Web Tech
Eventually, what is learned from web browser development can be used by front-end
developers to craft code for environments that are not fueled by a browser engine. As of late,
development environments are being dreamed up that use web technologies (e.g., CSS and
JavaScript), without web engines, to create native applications.
Some examples of these environments are:
• Flutter
• React Native
Responsive Web Design:
With the increasing diversity of devices, web applications need to adapt to various screen
sizes and resolutions. Responsive web design ensures that the application's layout and content
adjust automatically to provide an optimal viewing experience on different devices.
Front-End Developers Develop For...
Front-end developers develop for the web platform, and the web platform is most commonly
associated with web browser run times. Open a web browser like Google Chrome, navigate to
a web page like google.com, and what you are looking at was developed by a front-end
developer who developed the web page using HTML, CSS, and JavaScript.
The web platform runtime is not just for web browsers. It can also be used
by WebViews and Progressive Web App (aka PWA) techniques to create native-like
applications that are installed on an operating system. This means that a front-end developer
can take their knowledge of web technologies and the web platform run time associated with
browsers and web development and use these skills to create native applications for popular
operating systems like Windows, Mac OS X, iOS, Android, and Linux.
Loosely, think of a WebView or PWA like a single tab from a web browser without an address
bar or backward and forward buttons, that is embedded into a native application. This
scenario is identical to the browser, and WebViews/PWA's run from HTML, CSS, and
JavaScript but instead of facilitating internet access to web pages the intention is the web
platform runtime is used to access the native operating systems APIs (i.e., A single browser
view of a web page(s), using web technologies, that is run like a native application that may
or may not be connected to the internet that has access to native operations either via native
web APIs or bridges from web technologies to native APIs).
The most common solutions for WebView development are:

20
• Electron
• NW.js
• Neutralino.js
• DeskGap
Front-end developers can also find themselves developing source code using web platform
technologies (e.g., CSS and JavaScript), but then the source code created is not used by a web
platform run time scenario but instead as input which gets translated to native run time code.
Basically, coding environments exist where web technologies are written not to run on the
web platform but written to be used as input to create real native applications using native
APIs.
Some examples of these environments are:
• Flutter
• NativeScript
• React Native
(As of the time, the Instagram application for iOS and Android was developed using
React Native)
• tabris.js
As you can see, Front-end developers not only develop for web browsers but also for several
other run time scenarios beyond web browsers. Being a front-end developer today could
mean creating webpages and web applications that are accessed via web browsers, but it can
also mean creating native applications that are installed on operating systems and run offline
(e.g. Visual Studio Code is built using Electron).

Required Skills
A professional front-end developer will minimally have a working knowledge of browsers,
the internet and be skilled at using the following web technologies:
1. HyperText Markup Language (aka HTML)
2. Cascading Style Sheets (aka CSS)
3. Uniform Resource Locators (aka URLs)
4. Hypertext Transfer Protocol (aka HTTP)
5. JavaScript Programming Language (aka ECMAScript 262)
6. JavaScript Object Notation (aka JSON)
7. Document Object Model (aka DOM)
8. Web APIs (aka Browser APIs)
9. Web Content Accessibility Guidelines (aka WCAG) & Accessible Rich Internet
Applications (aka ARIA)

21
Beyond being skilled at the technologies just mentioned, a front-end developer might also be
skilled in one or more of the following areas:
• Content Management Systems (aka CMS)
• Node.js
• Cross-Browser Testing
• Cross-Platform Testing
• Unit Testing
• Cross-Device Testing
• Accessibility / WAI-ARIA
• Search Engine Optimization (aka SEO)
• Interaction or User Interface Design
• User Experience
• Usability
• E-commerce Systems
• Portal Systems
• Wireframing
• CSS Layout / Grids
• DOM Manipulation (e.g., jQuery)
• Mobile Web Performance
• Load Testing
• Performance Testing
• Progressive Enhancement / Graceful Degradation
• Version Control (e.g., GIT)
• MVC / MVVM / MV*
• Functional Programming
• Data Formats (e.g., JSON, XML)
• Data APIs (e.g Restful API)
• Web Font Embedding
• Scalable Vector Graphics (aka SVG)
• Regular Expressions
• Microdata / Microformats
• Task Runners, Build Tools, Process Automation Tools

22
• Responsive Web Design
• Object-Oriented Programming
• Application Architecture
• Modules
• Dependency Managers
• Package Managers
• JavaScript Animation
• CSS Animation
• Charts / Graphs
• UI Toolkits
• Code Quality Testing
• Code Coverage Testing
• Code Complexity Analysis
• Integration Testing
• Command Line / CLI
• Templating Strategies
• Templating Engines
• Single Page Applications
• Web/Browser Security
• Browser Developer Tools

2. Server-Side (Back-End) Development:


Web development activities that are done at the back end of programs are referred to as back
end development. Back-end development covers server-side web application logic and
functionality such as integrations and activities, like writing APIs, creating libraries, and
working with system components instead of frontend development, which focuses on
customer-facing services and programs. The back-end serves as the engine that processes user
inputs and generates dynamic content to be displayed on the front-end.
Key Concepts are:
Programming Languages: Commonly used back-end languages include Python, Ruby, PHP,
Java, and Node.js (JavaScript).
Frameworks: Frameworks like Django (Python), Ruby on Rails (Ruby), Laravel (PHP),
Spring (Java), and Express.js (Node.js) provide pre-built components and tools to streamline
the development process and enhance security.
Database Management: Web applications typically require a database to store, manage, and
retrieve data. The choice of database technology depends on the application's requirements,

23
such as data volume, scalability, and complexity. Commonly used databases include SQL-
based databases like MySQL, PostgreSQL, and NoSQL databases like MongoDB, Cassandra
and Firebase. Database administrators (DBAs) are responsible for ensuring data integrity,
security, and optimizing database performance.

Who is a Backend Developer


Backend developers build code that allows a database and an application to communicate
with one another. Backend developers take care and maintain the back-end of a website,
Including databases, servers, and apps, and they control what you don't see.
Back-end developers handle tasks such as database management, server-side scripting, and
handling user requests. They use programming languages like Python, Java, PHP, or Node.js
to create the application's business logic and connect it with the database. Back-end
developers use various programming languages and frameworks to create the functionality
that powers the web application. They use code that helps browsers communicate with
databases, store, understand, and delete data.

On a team, back-end developers collaborate with front-end developers, product managers,


principal architects, and website testers to build the structure of a website or mobile app.
Back-end developers must be familiar with many kinds of tools and frameworks, including
languages such as Python, Java, and Ruby. They make sure the back-end performs quickly
and responsively to front-end user requests.

Back-end developer vs. back-end engineer


Back-end developers and engineers have similar technical skills, but different responsibilities.
A back-end developer is like a teacher, whereas a back-end engineer is like a school principal
who creates the big-picture strategy. Back-end developers tend to focus on smaller parts of
the whole, such as applications and programs, working with teams to prove their design
methods are viable.

Back-end developer tasks and responsibilities


Back-end developers are required to have technical expertise, analytical thinking, and
excellent collaboration skills. As a back-end web developer, you should be able to work
independently to design the web infrastructure.
Here’s what many back-end developers do on a day-to-day basis:
• Build and maintain websites: A back-end developer’s main responsibility is to use
various tools, frameworks, and languages to determine how best to develop intuitive,
user-friendly prototypes and turn them into websites. This requires an understanding
of cross-platform functionality and compatibility.
• Write high-quality code: To produce sustainable web applications, developers must
write clean and easily maintainable code.
• Perform quality assurance (QA) testing: Create and oversee testing schedules to
optimize user interface and experience, ensuring optimal display on various browsers
and devices.
• Assess efficiency and speed: Once a website is up and running, and during updates
and edits, developers need to assess its performance and scalability, adjusting code as
necessary.

24
• Troubleshoot and debug: Be able to troubleshoot issues and resolve them, while
communicating them to project managers, stakeholders, and QA teams.
• Train and support: Maintain workflows with client teams to ensure ongoing support,
along with leading training and mentorship for junior developers.

Back-end Developer required skills


Web developers use a variety of tools to develop, test, and maintain web applications. Some
common tools for back-end developers include:
• Programming languages:
o Python
o PHP
o JavaScript
o Ruby
o Java
o C#
• Frameworks:
o Laravel (PHP)
o Django/Flask (Python)
o Spring (Java)
o Ruby on Rails (Ruby)
o Meteor (JavaScript)
o Node.js (JavaScript)
o ASP.NET Core (C#)
• Databases:
o MongoDB
o SQL Sever
o PostgreSQL
o MySQL
o Oracle
• Servers:
o Apache
o NGINX
o Lighttpd

25
o Microsoft IIS

3. APIs (Application Programming Interfaces):


APIs enable communication between different software systems, allowing them to exchange
data and functionality seamlessly. Web applications often use APIs to integrate with external
services or to provide access to specific functionalities for other applications. RESTful APIs
are widely used due to their simplicity and compatibility with various programming
languages and platforms. Front-end and back-end components need to communicate with
each other to deliver a seamless user experience. This communication happens through APIs
(Application Programming Interfaces). APIs allow data exchange and actions between
different software systems. An API is a set of programming code that enables data
transmission between one software product and another. It also contains the terms of this
data exchange.

The application programming interface must be clearly distinguished from a user interface. The user
interface accepts data from users, forwards it to the application for processing, and returns the results
to the user. The API does not interact with the user, but processes the data received from one program
module and transmits the results back to the other module. Here’s how it happens.
How do APIs work?
The working principle of an API is commonly expressed through the request-response
communication between a client and a server. The client is any front-end application that a
user interacts with. The server is in charge of backend logic and database operations. In this
scenario, an API works as a middle layer between the client and the server, making it possible
to send data requests and responses.

The Red Hat specialists note that APIs are sometimes considered contracts, where
documentation is an agreement between the parties, “If party 1 sends a remote request
structured a particular way, this is how party 2 software will respond.”
Let’s take a more detailed look at the API architecture.
API components
Application programming interfaces consist of two components:
• technical specification, describing the data exchange options between solutions with
the specification done in the form of a request for processing and data delivery
protocols; and

26
• software interface, written to the specification that represents it.
The software that needs to access information (i.e., X hotel room rates for certain dates) or
functionality (i.e., a route from point A to point B on a map based on a user’s location) from
another software calls its API while specifying the requirements of how data/functionality
must be provided. The other software returns data/functionality requested by the former
application. And the interface by which these two applications communicate is what the API
specifies.
API function calls
Each API contains and is implemented by function calls – language statements that request
software to perform particular actions and services. Function calls are composed of verbs
(i.e., BEGIN, GET, DELETE, etc.) and nouns (i.e., Data, Access, etc.) that enable a machine
to understand what to do next, say,
• start or finish a session,
• get amenities for a single room type, or
• restore or retrieve objects from a server.
Function calls and other parameters are described in the API documentation — a manual for
developers that includes all necessary information on how to work with the API and use the
services it provides. We will talk more about the documentation in one of the following
sections.
As for now, we’ll focus on what types of APIs exist, their use cases, and who each type is
suitable for.

Types of APIs
There are different types of APIs that can be categorized based on the ways they are available
for use and according to their initial design purposes.
APIs by availability aka release policies
In terms of release policies, APIs can be private, partner, and public.

27
Private APIs: These application software interfaces are designed to improve organizational
solutions and services. In-house developers or contractors may use these APIs to integrate a
company’s IT systems or applications as well as build new systems or customer-facing apps
leveraging existing systems.
Even if apps are publicly accessible, the interface itself remains available only for those
working directly with the API publisher. The private strategy allows a company to fully
control API usage.
Partner APIs: This type of API is openly promoted but shared with business partners who
have signed an agreement with the publisher. The common use case for partner APIs is
software integration between two parties. A company that provides partners with access to
data or capability benefits from extra revenue streams. At the same time, it can monitor how
the exposed digital assets are used, ensure whether third-party solutions using their APIs
provide decent user experience, and maintain corporate identity in their apps.
Public APIs: Also known as developer-facing or external, these APIs are available for any
third-party developers. A public API program allows for increasing brand awareness and
receiving an additional source of income when properly executed.
There are two types of public APIs – open (free of charge) and commercial ones.
• Open public APIs, as the Open API Definition suggests, are those with all features
public and available for use without restrictive terms and conditions. For instance, it’s
possible to build an application that utilizes the API without explicit approval from
the API supplier or mandatory licensing fees. The definition also states that the API
description and any related documentation must be openly available. On top of that,
these APIs can be freely used to create and test applications.
• Commercial API users pay subscription fees or use APIs on a pay-as-you-go basis. A
popular approach among publishers is to offer free trials, so users can evaluate APIs
before purchasing subscriptions. Learn more about how businesses benefit from
opening their APIs for public use in our detailed article on the API economy.

28
Availability is only one criterion on which APIs are classified. Let’s look at them from a
different angle.
APIs by use cases
APIs can be classified according to the systems for which they are designed.

Database APIs. Database APIs enable communication between an application and a database
management system. Developers work with databases by writing queries to access data, change
tables, etc. The Drupal 7 Database API, for example, allows users to write unified queries for different
databases, both proprietary and open source (Oracle, MongoDB, PostgreSQL, MySQL, CouchDB,
and MSSQL).
Another example is ORDS database API, which is embedded in Oracle REST Data Services.
Operating systems APIs. This group of APIs defines how applications use the resources and
services of operating systems. Every OS has its set of APIs, for instance, Windows API or
Linux API (kernel user-space API and kernel internal API).
Apple provides API references for macOS and iOS in its developer documentation. APIs for
building applications for Apple’s macOS desktop operating system are included in the Cocoa
set of developer tools. Those building apps for the iOS mobile operating system use Cocoa
Touch – a modified version of Cocoa.
Remote APIs. Remote APIs define standards of interaction for applications running on
different machines. In other words, one software product accesses resources located outside
the device that requests them, which explains the name. Since two remotely located
applications are connected over a communications network, particularly the internet, most
remote APIs are written based on web standards. Java Database Connectivity API and Java
Remote Method Invocation API are two examples of remote application programming
interfaces.

29
Web APIs. This API class is the most common. Web APIs provide machine-readable data
and functionality transfer between web-based systems which represent client-server
architecture. These APIs mainly deliver requests from web applications and responses from
servers using Hypertext Transfer Protocol (HTTP).
Developers can use web APIs to extend the functionality of their apps or sites. For instance,
the Pinterest API comes with tools for adding users’ Pinterest data like boards or Pins to a
website. Google Maps API enables the addition of a map with an organization’s location.
Most businesses use more than one API to connect applications and share information. Some
end up needing an API management tool to help them control, distribute, and analyze
different APIs. Popularly used API protocols are:

API specifications/protocols
The goal of API specifications is to standardize data exchange between web services. In this
case, standardization means the ability of diverse systems, written in different programming
languages and/or running on different OSs, or using different technologies, to seamlessly
communicate with each other.
Remote Procedure Call (RPC)
Web APIs may adhere to resource exchange principles based on a Remote Procedure Call or
RPC. This protocol specifies the interaction between applications based on the client-server
architecture. One program (client) requests data or functionality from another program
(server), located in another computer on a network, and the server sends the required
response.
RPC is also known as a subroutine or function call. One of two ways to implement a remote
procedure call is SOAP.
Service Object Access Protocol (SOAP)
SOAP is a lightweight protocol for exchanging structured information in a decentralized,
distributed environment, according to the definition by Microsoft that developed it. Generally
speaking, this specification contains the syntax rules for request and response messages sent
by web applications. APIs that comply with the principles of SOAP enable XML messaging
between systems through HTTP or Simple Mail Transfer Protocol (SMTP) for transferring
mail.
Extensible markup language (XML) is a simple and very flexible text format widely used for
data storage and exchange over the internet or other networks. XML defines a set of rules for
encoding documents in a format that both humans and machines can read. The markup
language is a collection of symbols that can be placed in the text to delineate and label the
parts of the text document. XML text documents contain self-descriptive tags of data objects,
which makes them easily readable.

30
An example of a SOAP XML request call in Google Ad Manager. Source: Google Ad
Manager
SOAP is mostly used with enterprise web-based software to ensure the high security of transmitted
data. SOAP APIs are preferred among providers of payment gateways, identity management, and
CRM solutions, as well as financial and telecommunication services. PayPal’s public API is one of the
commonly known SOAP APIs. It’s also frequently used for legacy system support.
Representational State Transfer (REST)
The term REST was introduced by computer scientist Roy Fielding in a dissertation in 2000.
Unlike SOAP, which is a protocol, REST is a software architectural style with six
constraints for building applications that work over HTTP, often web services. The World
Wide Web is the most common realization and application of this architectural style.
REST is considered a simpler alternative to SOAP, which many developers find difficult to
use because it requires writing a lot of code to complete every task and following the XML
structure for every message sent. REST follows another logic since it makes data available as
resources. Each resource is represented by a unique URL, and one can request this resource
by providing its URL.
Web APIs that comply with REST architectural constraints are called RESTful APIs. These
APIs use HTTP requests (AKA methods or verbs) to work with resources: GET, PUT,
HEAD, POST, PATCH, CONNECT, TRACE, OPTIONS and DELETE.
RESTful systems support messaging in different formats, such as plain text, HTML, YAML,
XML, and JSON, while SOAP only allows XML. The ability to support multiple formats for
storing and exchanging data is one of the reasons REST is a prevailing choice for building
public APIs these days.
Social media giants and travel companies provide external APIs to improve their brand
visibility even more. Twitter has numerous RESTful APIs; Expedia has both SOAP and
RESTful APIs for its partners.

31
JavaScript Object Notation (JSON) is a lightweight and easy-to-parse text format for data
exchange. Its syntax is based on a subset of the Standard ECMA-262 3rd Edition. Each JSON
file contains collections of name/value pairs and ordered lists of values. Since these are
universal data structures, the format can be used with any programming language.

JSON has been widely adopted thanks to the popularity of REST.

gRPC
gRPC is an open-source universal API framework that is also classified under RPC. Unlike
SOAP, gRPC is much newer and was released publicly in 2015 by Google. With gRPC, the
client application can directly call methods from a server application located on a different
computer as if it was a local object. This makes it easier to create distributed services and
applications.
Like SOAP and REST, the transport layer for gRPC is HTTP. However, similar to RCP,
gRPC allows developers to define any kind of function calls, rather than selecting from
predefined options such as PUT and GET in the case of REST.

32
By default, gRPC uses protocol buffers instead of JSON or XML as the Interface Definition
Language (IDL) for serializing structured data. Here, the developer needs to first define the
structure of the data they want to serialize. Once the data structures have been specified, they
use the protocol buffer compiler to generate the data access classes in the programming
language of your choice. The data is then compressed and serialized in binary format at
runtime.

Example of RPC method parameters and return types. Source: gRPC

GraphQL
The need for faster feature development, more efficient data loading due to increased mobile
adoption, and a multitude of clients, made the developers look for other approaches to
software architecture. GraphQL, initially created by Facebook in 2012 for internal use, is the
new REST with organizations like Shopify, Yelp, GitHub, Coursera, and The New York
Times, using it to build APIs.
GraphQL is a query language for APIs. It allows the client to detail the exact data it needs and
simplifies data aggregation from multiple sources, so the developer can use one API call to
request all needed data. Another special feature of GraphQL is that it uses a type system to
describe data.

Using types to describe data allows apps to specify what data they need to get

Apps using GraphQL control what data they need to fetch from a server, which allows them

33
to run fast even when the mobile connection is slow.

API documentation
No matter how many opportunities for creating or extending software products API gives, it
would remain an unusable piece of code if developers didn’t understand how to work with it.
Well-written and structured API documentation that explains how to effectively use and
integrate an API in an easy-to-comprehend manner will make a developer happy and eager to
recommend the API to peers.
The API documentation is a reference manual with all the needed information about the API,
including functions, classes, return types, and arguments.
Numerous content elements make good documentation, such as
• a quick start guide;
• authentication information;
• explanations for every API call (request);
• examples of every request and return with a response description, error messages,
etc.;
• samples of code for popular programmatic languages like Python, Java, JavaScript, or
PHP;
• tutorials; and
• SDK examples (if SDKs are available) illustrating how to access the resource, etc.
The detailed API requirements should also be clearly articulated in the documentation. They
include functional, nonfunctional, and implementation requirements. Functional requirements
define what an API should do and how it’s going to do it. Nonfunctional API requirements
describe the ways an API should perform in terms of service level agreement. For example, if
you apply a particular security mechanism to an API, consumers that require a different
security mechanism won’t be able to use this API. And finally, implementation requirements
provide information on the ways to meet functional or nonfunctional requirements for a
particular API implementation.
Documentation may be static and interactive. The latter allows you to try out APIs and see
return results. It usually consists of two columns: human and machine. The human column
contains API descriptions, and the machine column has a console to make calls and contains
info that clients and servers will be interested in when testing the API.
Generation is the process of documenting APIs by developers and technical writers. The
specialists may use API documentation solutions (i.e., Swagger tools, Postman, Slate,
or ReDoc) to unify documentation structure and design.

Why use an API?


APIs serve numerous purposes. Generally, they can simplify and speed up software
development. Developers can add functionality (i.e., a recommender system,
accommodation booking engine, payment processing, or image recognition feature) from

34
other providers to existing solutions or build new applications using services by third-party
providers.
Whatever the case, specialists don’t have to deal with source code, trying to understand how
the other solution works. They simply connect their software to another one. In other words,
APIs serve as an abstraction layer between two systems, hiding the complexity and working
details of the latter.
The role of APIs is even greater if we look at it not only from the software development angle
but also from the business collaboration angle. These machine-readable interfaces for
resource exchange are like delivery services that work under the hood and enable that needed
technological connectivity. According to the Fourth State of API Integration Report of 2020,
83 percent of participants find API integration “critical” to their businesses and IT
infrastructures.
In this regard, the two main tasks for decision-makers and developers are to select the API
that works for a company’s specific business needs and understand how to effectively use it.

4. Web Servers and Hosting:


Web servers play a vital role in serving web applications to users. They handle incoming
requests, process them using the back-end logic, and send the appropriate responses to the
users' browsers. Popular web servers include Apache, Nginx, and Microsoft Internet
Information Services (IIS). Web applications need to be hosted on servers accessible via the
internet, and this hosting can be done on on-premises servers or cloud-based platforms like
Amazon Web Services (AWS), Microsoft Azure, or Google Cloud Platform (GCP).
The term web server can refer to hardware or software, or both of them working together.
1. On the hardware side, a web server is a computer that stores web server software and
a website's component files (for example, HTML documents, images, CSS
stylesheets, and JavaScript files). A web server connects to the Internet and supports
physical data interchange with other devices connected to the web.
2. On the software side, a web server includes several parts that control how web users
access hosted files. At a minimum, this is an HTTP server. An HTTP server is
software that understands URLs (web addresses) and HTTP (the protocol your
browser uses to view webpages). An HTTP server can be accessed through the
domain names of the websites it stores, and it delivers the content of these hosted
websites to the end user's device.
At the most basic level, whenever a browser needs a file that is hosted on a web server, the
browser requests the file via HTTP. When the request reaches the correct (hardware) web
server, the (software) HTTP server accepts the request, finds the requested document, and
sends it back to the browser, also through HTTP. (If the server doesn't find the requested
document, it returns a 404 response instead.)

35
To publish a website, you need either a static or a dynamic web server.
A static web server, or stack, consists of a computer (hardware) with an HTTP server
(software). We call it "static" because the server sends its hosted files as-is to your browser.
A dynamic web server consists of a static web server plus extra software, most commonly
an application server and a database. We call it "dynamic" because the application server
updates the hosted files before sending content to your browser via the HTTP server.
For example, to produce the final webpages you see in the browser, the application server
might fill an HTML template with content from a database. Sites like MDN or Wikipedia
have thousands of webpages. Typically, these kinds of sites are composed of only a few
HTML templates and a giant database, rather than thousands of static HTML documents. This
setup makes it easier to maintain and deliver the content.
Deeper dive
To review: to fetch a webpage, your browser sends a request to the web server, which
searches for the requested file in its own storage space. Upon finding the file, the server reads
it, processes it as needed, and sends it to the browser. Let's look at those steps in more detail.
Hosting files
First, a web server has to store the website's files, namely all HTML documents and their
related assets, including images, CSS stylesheets, JavaScript files, fonts, and video.
Technically, you could host all those files on your own computer, but it's far more convenient
to store files all on a dedicated web server because:
• A dedicated web server is typically more available (up and running).
• Excluding downtime and system troubles, a dedicated web server is always connected
to the Internet.
• A dedicated web server can have the same IP address all the time. This is known as
a dedicated IP address. (Not all ISPs provide a fixed IP address for home lines.)
• A dedicated web server is typically maintained by a third party.
For all these reasons, finding a good hosting provider is a key part of building your website.
Examine the various services companies offer. Choose one that fits your needs and budget.
(Services range from free to thousands of dollars per month.) You can find more details in
this article.

36
Once you have web hosting service, you must upload your files to your web server.
Communicating through HTTP
Second, a web server provides support for HTTP (Hypertext Transfer Protocol). As its name
implies, HTTP specifies how to transfer hypertext (linked web documents) between two
computers.
A Protocol is a set of rules for communication between two computers. HTTP is a textual,
stateless protocol.
Textual
All commands are plain-text and human-readable.
Stateless
Neither the server nor the client remember previous communications. For example, relying
on HTTP alone, a server can't remember a password you typed or remember your progress on
an incomplete transaction. You need an application server for tasks like that. (We'll cover that
sort of technology in other articles.)
HTTP provides clear rules for how a client and server communicate. Be aware of these
things:
• Usually only clients make HTTP requests, and only to servers. Servers respond to
a client's HTTP request. A server can also populate data into a client cache, in advance
of it being requested, through a mechanism called server push.
• When requesting a file via HTTP, clients must provide the file's URL.
• The web server must answer every HTTP request, at least with an error message.
On a web server, the HTTP server is responsible for processing and answering incoming
requests.
1. Upon receiving a request, an HTTP server checks if the requested URL matches an
existing file.
2. If so, the web server sends the file content back to the browser. If not, the server will
check if it should generate a file dynamically for the request (see Static vs. dynamic
content).
3. If neither of these options are possible, the web server returns an error message to the
browser, most commonly 404 Not Found. The 404 error is so common that some web

37
designers devote considerable time and effort to designing 404 error pages.

Static vs. dynamic content


Roughly speaking, a server can serve either static or dynamic content. Remember that the
term static means "served as-is". Static websites are the easiest to set up, so we suggest you
make your first site a static site.
The term dynamic means that the server processes the content or even generates it on the fly
from a database. This approach provides more flexibility, but the technical stack is more
complex, making it dramatically more challenging to build a website.
It is impossible to suggest a single off-the-shelf application server that will be the right
solution for every possible use case. Some application servers are designed to host and
manage blogs, wikis, or e-commerce solutions, while others are more generic. If you're
building a dynamic website, take the time to research your requirements and find the
technology that best fits your needs.
Most website developers won't need to create an application server from scratch, because
there are so many off-the-shelf solutions, many of which are highly configurable. But if you
do need to create your own server, then you will probably want to use a server framework,
leveraging its existing code and libraries, and extending just the parts that you need in order
to meet your use case. Only a relatively small number of developers should need to develop a
server completely from scratch: for example, in order to meet tight resource constraints on an
embedded system. If you'd like to experiment with building a server, take a look through the
resources in the Server-side website programming learning pathway.
5. Security:
Security is a critical aspect of web application development. Developers must implement
measures to protect user data, prevent unauthorized access, and defend against various cyber
threats, such as SQL injection, cross-site scripting (XSS), and cross-site request forgery
(CSRF). Encryption, authentication, and authorization techniques are employed to secure
data and user interactions.

6. Testing:

38
Thorough testing is essential to ensure the web application works as intended and is free of
bugs and errors. Testing may involve unit testing, integration testing, functional testing,
performance testing, and security testing.
7. Deployment:
Once the web application is developed and tested, it needs to be deployed on a web server to
make it accessible to users over the internet. This server could be a cloud-based service or a
dedicated physical server.
8. Maintenance and Updates:
Web application development is an ongoing process. Regular maintenance, bug fixes, and
updates are necessary to ensure the application remains secure, functional, and up-to-date
with the latest technologies and user expectations.
Web application development is a multifaceted process that involves combining front-end
technologies for user interfaces, back-end technologies for server-side processing, and
databases for data storage and retrieval. It requires careful planning, design, and
implementation to create robust, secure, and scalable applications that meet the needs of
modern users and businesses in the digital age. The continuous evolution of web technologies
and best practices ensures that web application development will remain a dynamic and
exciting field for the foreseeable future.

39
3. PHP (Hypertext Preprocessor)
PHP tutorial for beginners and professionals provides in-depth knowledge of PHP scripting
language. Our PHP tutorial will help you to learn PHP scripting language easily.
This PHP tutorial covers all the topics of PHP such as introduction, control statements,
functions, array, string, file handling, form handling, regular expression, date and time,
object-oriented programming in PHP, math, PHP MySQL, PHP with Ajax, PHP with jQuery
and PHP with XML.
What is PHP
PHP is an open-source, interpreted, and object-oriented scripting language that can be
executed at the server-side. PHP is well suited for web development. Therefore, it is used to
develop web applications (an application that executes on the server and generates the
dynamic page.).
PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995. PHP
8.2.0 is the latest version of PHP, which was released on 24 November, 2022. Some
important points need to be noticed about PHP are as followed:
o PHP stands for Hypertext Preprocessor.
o PHP is an interpreted language, i.e., there is no need for compilation.
o PHP is faster than other scripting languages, for example, ASP and JSP.
o PHP is a server-side scripting language, which is used to manage the dynamic content
of the website.
o PHP can be embedded into HTML.
o PHP is an object-oriented language.
o PHP is an open-source scripting language.
o PHP is simple and easy to learn language.

40
What is a Scripting Language?
A script is a set of programming instructions that is interpreted at runtime.
A scripting language is a language that interprets scripts at runtime. Scripts are usually
embedded into other software environments.
The purpose of the scripts is usually to enhance the performance or perform routine tasks for
an application.
Server-side scripts are interpreted on the server while client-side scripts are interpreted by the
client application.
PHP is a server-side script that is interpreted on the server while JavaScript is an example of a
client-side script that is interpreted by the client browser. Both PHP and JavaScript can be
embedded into HTML pages.

Programming Language Vs Scripting Language


Programming language Scripting language
Has all the features needed to develop complete
Mostly used for routine tasks
applications.
The code has to be compiled before it can be The code is usually executed without
executed compiling
Does not need to be embedded into other Is usually embedded into other software
languages environments.

Why use PHP


PHP is a server-side scripting language, which is used to design the dynamic web
applications with MySQL database.
o It handles dynamic content, database as well as session tracking for the website.
o You can create sessions in PHP.

41
o It can access cookies variable and also set cookies.
o It helps to encrypt the data and apply validation.
o PHP supports several protocols such as HTTP, POP3, SNMP, LDAP, IMAP, and many
more.
o Using PHP language, you can control the user to access some pages of your website.
o As PHP is easy to install and set up, this is the main reason why PHP is the best
language to learn.
o PHP can handle the forms, such as - collect the data from users using forms, save it
into the database, and return useful information to the user. For example -
Registration form.

o Other benefit that you get with PHP is that it’s a server side scripting language; this
means you only need to install it on the server and client computers requesting for
resources from the server do not need to have PHP installed; only a web browser
would be enough.
o PHP has in built support for working hand in hand with MySQL; this doesn’t
mean you can’t use PHP with other database management systems. You can still use
PHP with

• Postgres
• MySQL
• Oracle
• MS SQL Server
• ODBC etc.

o PHP is cross platform; this means you can deploy your application on a number of
different operating systems such as windows, Linux, Mac OS etc.

PHP Features
PHP is very popular language because of its simplicity and open source. There are some
important features of PHP given below:

42
Performance:
PHP script is executed much faster than those scripts which are written in other languages
such as JSP and ASP. PHP uses its own memory, so the server workload and loading time is
automatically reduced, which results in faster processing speed and better performance.
Open Source:
PHP source code and software are freely available on the web. You can develop all the
versions of PHP according to your requirement without paying any cost. All its components
are free to download and use.
Familiarity with syntax:
PHP has easily understandable syntax. Programmers are comfortable coding with it.
Embedded:
PHP code can be easily embedded within HTML tags and script.
Platform Independent:
PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP
application developed in one OS can be easily executed in other OS also.
Database Support:
PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.
Error Reporting -
PHP has predefined error reporting constants to generate an error notice or warning at
runtime. E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE.
Loosely Typed Language:
PHP allows us to use a variable without declaring its datatype. It will be taken automatically
at the time of execution based on the type of data it contains on its value.

43
Web servers Support:
PHP is compatible with almost all local servers used today like Apache, Netscape, Microsoft
IIS, etc.
Security:
PHP is a secure language to develop the website. It consists of multiple layers of security to
prevent threads and malicious attacks.
Control:
Different programming languages require long script or code, whereas PHP can do the same
work in a few lines of code. It has maximum control over the websites like you can make
changes easily whenever you want.
A Helpful PHP Community:
It has a large community of developers who regularly updates documentation, tutorials,
online help, and FAQs. Learning PHP from the communities is one of the significant benefits.

PHP in Web Development


PHP is widely used in web development nowadays. PHP can develop dynamic websites
easily. But you must have the basic the knowledge of following technologies for web
development as well.
o HTML
o CSS
o JavaScript
o Ajax
o XML and JSON
o jQuery
Prerequisite
Before learning PHP, you must have the basic knowledge of HTML, CSS, and JavaScript.
So, learn these technologies for better implementation of PHP.
HTML - HTML is used to design static webpage.
CSS - CSS helps to make the webpage content more effective and attractive.
JavaScript - JavaScript is used to design an interactive website.

Install PHP
To install PHP, we will suggest you to install AMP (Apache, MySQL, PHP) software stack. It
is available for all operating systems. There are many AMP options available in the market
that are given below:
o WAMP for Windows

44
o LAMP for Linux
o MAMP for Mac
o SAMP for Solaris
o FAMP for FreeBSD
o XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform: It includes some
other components too such as FileZilla, OpenSSL, Webalizer, Mercury Mail, etc.
If you are on Windows and don't want Perl and other features of XAMPP, you should go for
WAMP. In a similar way, you may use LAMP for Linux and MAMP for Macintosh.
How to install XAMPP server on windows
We will learn how to install the XAMPP server on windows platform step by step. Follow the
below steps and install the XAMPP server on your system.
Step 1: Click on the above link provided to download the XAMPP server according to your
window requirement.

Step 2: After downloading XAMPP, double click on the downloaded file and allow XAMPP
to make changes in your system. A window will pop-up, where you have to click on
the Next button.

45
Step 3: Here, select the components, which you want to install and click Next.

Step 4: Choose a folder where you want to install the XAMPP in your system and click Next.

46
Step 5: Click Next and move ahead.

Step 6: XAMPP is ready to install, so click on the Next button and install the XAMPP.

47
Step 7: A finish window will display after successful installation. Click on the Finish button.

Step 8: Choose your preferred language.

48
Step 9: XAMPP is ready to use. Start the Apache server and MySQL and run the php
program on the localhost.

Step 10: If no error is shown, then XAMPP is running successfully.

49
How to run PHP code in XAMPP
Generally, a PHP file contains HTML tags and some PHP scripting code. It is very easy to
create a simple PHP example. To do so, create a file and write HTML tags + PHP code and
save this file with .php extension.
Note: PHP statements ends with semicolon (;).
All PHP code goes between the php tag. It starts with <?php and ends with ?>. The syntax of
PHP tag is given below:
1. <?php
2. //your code here
3. ?>
Let's see a simple PHP example where we are writing some text using PHP echo command.
File: first.php
1. <!DOCTYPE>
2. <html>
3. <body>
4. <?php
5. echo "<h2>Hello First PHP</h2>";
6. ?>
7. </body>
8. </html>
Output:
Hello First PHP
How to run PHP programs in XAMPP
How to run PHP programs in XAMPP PHP is a popular backend programming language.
PHP programs can be written on any editor, such as - Notepad, Notepad++, Dreamweaver,
etc. These programs save with .php extension, i.e., filename.php inside the htdocs folder.
For example - p1.php.
As I'm using window, and my XAMPP server is installed in D drive. So, the path for the
htdocs directory will be "D:\xampp\htdocs".
PHP program runs on a web browser such as - Chrome, Internet Explorer, Firefox, etc. Below
some steps are given to run the PHP programs.
Step 1: Create a simple PHP program like hello world.
1. <?php
2. echo "Hello World!";

50
3. ?>
Step 2: Save the file with hello.php name in the htdocs folder, which resides inside the
xampp folder.
Note: PHP program must be saved in the htdocs folder, which resides inside the xampp
folder, where you installed the XAMPP. Otherwise it will generate an error - Object not
found.
Step 3: Run the XAMPP server and start the Apache and MySQL.
Step 4: Now, open the web browser and type localhost http://localhost/hello.php on your
browser window.
Step 5: The output for the above hello.php program will be shown as the screenshot below:

Most of the time, PHP programs run as a web server module. However, PHP can also be run
on CLI (Command Line Interface).
PHP Case Sensitivity
In PHP, keyword (e.g., echo, if, else, while), functions, user-defined functions, classes are not
case-sensitive. However, all variable names are case-sensitive.
In the below example, you can see that all three echo statements are equal and valid:
1. <!DOCTYPE>
2. <html>
3. <body>
4. <?php
5. echo "Hello world using echo </br>";
6. ECHO "Hello world using ECHO </br>";
7. EcHo "Hello world using EcHo </br>";
8. ?>
9. </body>
10. </html>
Output:
Hello world using echo
Hello world using ECHO
Hello world using EcHo

51
Look at the below example that the variable names are case sensitive. You can see the
example below that only the second statement will display the value of the $color variable.
Because it treats $color, $ColoR, and $COLOR as three different variables:
1. <html>
2. <body>
3. <?php
4. $color = "black";
5. echo "My car is ". $ColoR ."</br>";
6. echo "My dog is ". $color ."</br>";
7. echo "My Phone is ". $COLOR ."</br>";
8. ?>
9. </body>
10. </html>
Output:
Notice: Undefined variable: ColoR in D:\xampp\htdocs\program\p2.php on line 8
My car is
My dog is black

Notice: Undefined variable: COLOR in D:\xampp\htdocs\program\p2.php on line 10


My Phone is
Only $color variable has printed its value, and other variables $ColoR and $COLOR are
declared as undefined variables. An error has occurred in line 5 and line 7.
PHP Echo
PHP echo is a language construct, not a function. Therefore, you don't need to use parenthesis
with it. But if you want to use more than one parameter, it is required to use parenthesis.
The syntax of PHP echo is given below:
1. void echo ( string $arg1 [, string $... ] )
PHP echo statement can be used to print the string, multi-line strings, escaping characters,
variable, array, etc. Some important points that you must know about the echo statement are:
o echo is a statement, which is used to display the output.
o echo can be used with or without parentheses: echo(), and echo.
o echo does not return any value.
o We can pass multiple strings separated by a comma (,) in echo.
o echo is faster than the print statement.

52
PHP echo: printing string
File: echo1.php
1. <?php
2. echo "Hello by PHP echo";
3. ?>
Output:
Hello by PHP echo
PHP echo: printing multi line string
File: echo2.php
1. <?php
2. echo "Hello by PHP echo
3. this is multi line
4. text printed by
5. PHP echo statement
6. ";
7. ?>
Output:

Hello by PHP echo this is multi line text printed by PHP echo statement
PHP echo: printing escaping characters
File: echo3.php
1. <?php
2. echo "Hello escape \"sequence\" characters";
3. ?>
Output:
Hello escape "sequence" characters
PHP echo: printing variable value
File: echo4.php
1. <?php
2. $msg="Hello CSC415 PHP";
3. echo "Message is: $msg";
4. ?>

53
Output:
Message is: Hello CSC415 PHP
PHP Print
Like PHP echo, PHP print is a language construct, so you don't need to use parenthesis with
the argument list. Print statement can be used with or without parentheses: print and print().
Unlike echo, it always returns 1.
The syntax of PHP print is given below:
1. int print(string $arg)
PHP print statement can be used to print the string, multi-line strings, escaping characters,
variable, array, etc. Some important points that you must know about the echo statement are:
o print is a statement, used as an alternative to echo at many times to display the output.
o print can be used with or without parentheses.
o print always returns an integer value, which is 1.
o Using print, we cannot pass multiple arguments.
o print is slower than the echo statement.
PHP print: printing string
File: print1.php
1. <?php
2. print "Hello by PHP print ";
3. print ("Hello by PHP print()");
4. ?>
Output:
Hello by PHP print Hello by PHP print()
PHP print: printing multi line string
File: print2.php
1. <?php
2. print "Hello by PHP print
3. this is multi line
4. text printed by
5. PHP print statement
6. ";
7. ?>
Output:

54
Hello by PHP print this is multi line text printed by PHP print statement
PHP print: printing escaping characters
File: print3.php
1. <?php
2. print "Hello escape \"sequence\" characters by PHP print";
3. ?>
Output:
Hello escape "sequence" characters by PHP print
PHP print: printing variable value
File: print4.php
1. <?php
2. $msg="Hello print() in PHP";
3. print "Message is: $msg";
4. ?>
Output:
Message is: Hello print() in PHP

PHP echo and print Statements


We frequently use the echo statement to display the output. There are two basic ways to get
the output in PHP:
o echo
o print
echo and print are language constructs, and they never behave like a function. Therefore,
there is no requirement for parentheses. However, both the statements can be used with or
without parentheses. We can use these statements to output variables or strings.
Difference between echo and print
echo
o echo is a statement, which is used to display the output.
o echo can be used with or without parentheses.
o echo does not return any value.
o We can pass multiple strings separated by comma (,) in echo.
o echo is faster than print statement.

55
print
o print is also a statement, used as an alternative to echo at many times to display the
output.
o print can be used with or without parentheses.
o print always returns an integer value, which is 1.
o Using print, we cannot pass multiple arguments.
o print is slower than echo statement.
You can see the difference between echo and print statements with the help of the following
programs.
For Example (Check multiple arguments)
You can pass multiple arguments separated by a comma (,) in echo. It will not generate any
syntax error.
1. <?php
2. $fname = "Gunjan";
3. $lname = "Garg";
4. echo "My name is: ".$fname,$lname;
5. ?>
Output:

It will generate a syntax error because of multiple arguments in a print statement.


1. <?php
2. $fname = "Gunjan";
3. $lname = "Garg";
4. print "My name is: ".$fname,$lname;
5. ?>
Output:

56
For Example (Check Return Value)
echo statement does not return any value. It will generate an error if you try to display its
return value.
1. <?php
2. $lang = "PHP";
3. $ret = echo $lang." is a web development language.";
4. echo "</br>";
5. echo "Value return by print statement: ".$ret;
6. ?>
Output:

As we already discussed that print returns a value, which is always 1.


1. <?php
2. $lang = "PHP";
3. $ret = print $lang." is a web development language.";
4. print "</br>";
5. print "Value return by print statement: ".$ret;
6. ?>
Output:

PHP Variables
In PHP, a variable is declared using a $ sign followed by the variable name. Here, some
important points to know about variables:
o As PHP is a loosely typed language, so we do not need to declare the data types of the
variables. It automatically analyzes the values and makes conversions to its correct
datatype.
o After declaring a variable, it can be reused throughout the code.
o Assignment Operator (=) is used to assign the value to a variable.

57
Syntax of declaring a variable in PHP is given below:
$variablename=value;
Rules for declaring PHP variable:
o A variable must start with a dollar ($) sign, followed by the variable name.
o It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
o A variable name must start with a letter or underscore (_) character.
o A PHP variable name cannot contain spaces.
o One thing to be kept in mind that the variable name cannot start with a number or
special symbols.
o PHP variables are case-sensitive, so $name and $NAME both are treated as different
variable.
PHP Variable: Declaring string, integer, and float
Let's see the example to store string, integer, and float values in PHP variables.
File: variable1.php
1. <?php
2. $str="hello string";
3. $x=200;
4. $y=44.6;
5. echo "string is: $str <br/>";
6. echo "integer is: $x <br/>";
7. echo "float is: $y <br/>";
8. ?>
Output:
string is: hello string
integer is: 200
float is: 44.6
PHP Variable: Sum of two variables
File: variable2.php
1. <?php
2. $x=5;
3. $y=6;
4. $z=$x+$y;

58
5. echo $z;
6. ?>
Output:
11
PHP Variable: case sensitive
In PHP, variable names are case sensitive. So variable name "color" is different from Color,
COLOR, COLor etc.
File: variable3.php
1. <?php
2. $color="red";
3. echo "My car is " . $color . "<br>";
4. echo "My house is " . $COLOR . "<br>";
5. echo "My boat is " . $coLOR . "<br>";
6. ?>
Output:
My car is red
Notice: Undefined variable: COLOR in C:\wamp\www\variable.php on line 4
My house is
Notice: Undefined variable: coLOR in C:\wamp\www\variable.php on line 5
My boat is
PHP Variable: Rules
PHP variables must start with letter or underscore only.
PHP variable can't be start with numbers and special symbols.
File: variablevalid.php
1. <?php
2. $a="hello";//letter (valid)
3. $_b="hello";//underscore (valid)
4.
5. echo "$a <br/> $_b";
6. ?>
Output:
hello

59
hello
File: variableinvalid.php
1. <?php
2. $4c="hello";//number (invalid)
3. $*d="hello";//special symbol (invalid)
4.
5. echo "$4c <br/> $*d";
6. ?>
Output:
Parse error: syntax error, unexpected '4' (T_LNUMBER), expecting variable (T_VARIABLE)
or '$' in C:\wamp\www\variableinvalid.php on line 2
PHP: Loosely typed language
PHP is a loosely typed language; it means PHP automatically converts the variable to its
correct data type.
PHP $ and $$ Variables
The $var (single dollar) is a normal variable with the name var that stores any value like
string, integer, float, etc.
The $$var (double dollar) is a reference variable that stores the value of the $variable inside
it.
To understand the difference better, let's see some examples.
Example 1
1. <?php
2. $x = "abc";
3. $$x = 200;
4. echo $x."<br/>";
5. echo $$x."<br/>";
6. echo $abc;
7. ?>
Output:

60
In the above example, we have assigned a value to the variable x as abc. Value of reference
variable $$x is assigned as 200.
Now we have printed the values $x, $$x and $abc.
Example2
1. <?php
2. $x="U.P";
3. $$x="Lucknow";
4. echo $x. "<br>";
5. echo $$x. "<br>";
6. echo "Capital of $x is " . $$x;
7. ?>
Output:

In the above example, we have assigned a value to the variable x as U.P. Value of reference
variable $$x is assigned as Lucknow.
Now we have printed the values $x, $$x and a string.
Example3
1. <?php
2. $name="Cat";
3. ${$name}="Dog";
4. ${${$name}}="Monkey";

61
5. echo $name. "<br>";
6. echo ${$name}. "<br>";
7. echo $Cat. "<br>";
8. echo ${${$name}}. "<br>";
9. echo $Dog. "<br>";
10. ?>
Output:

In the above example, we have assigned a value to the variable name Cat. Value of reference
variable ${$name} is assigned as Dog and ${${$name}} as Monkey.
Now we have printed the values as $name, ${$name}, $Cat, ${${$name}} and $Dog.
PHP Constants
1. PHP constants are name or identifier that can't be changed during the execution of the
script except for magic constants, which are not really constants. PHP constants can
be defined by 2 ways:
Using define() function
2. Using const keyword
Constants are similar to the variable except once they defined, they can never be undefined or
changed. They remain constant across the entire program. PHP constants follow the same
PHP variable rules. For example, it can be started with a letter or underscore only.
Conventionally, PHP constants should be defined in uppercase letters.
Note: Unlike variables, constants are automatically global throughout the script.
PHP constant: define()
Use the define() function to create a constant. It defines constant at run time. Let's see the
syntax of define() function in PHP.
1. define(name, value, case-insensitive)
1. name: It specifies the constant name.
2. value: It specifies the constant value.

62
3. case-insensitive: Specifies whether a constant is case-insensitive. Default value is
false. It means it is case sensitive by default.
Let's see the example to define PHP constant using define().
File: constant1.php
1. <?php
2. define("MESSAGE","Hello FUTA PHP");
3. echo MESSAGE;
4. ?>
Output:
Hello FUTA PHP
Create a constant with case-insensitive name:
File: constant2.php
1. <?php
2. define("MESSAGE","Hello FUTA PHP",true);//not case sensitive
3. echo MESSAGE, "</br>";
4. echo message;
5. ?>
Output:
Hello FUTA PHP
Hello FUTA PHP
File: constant3.php
1. <?php
2. define("MESSAGE","Hello FUTA PHP",false);//case sensitive
3. echo MESSAGE;
4. echo message;
5. ?>
Output:
Hello FUTA PHP
Notice: Use of undefined constant message - assumed 'message'
in C:\wamp\www\vconstant3.php on line 4
message
PHP constant: const keyword

63
PHP introduced a keyword const to create a constant. The const keyword defines constants at
compile time. It is a language construct, not a function. The constant defined using const
keyword are case-sensitive.
File: constant4.php
1. <?php
2. const MESSAGE="Hello const by FUTA PHP";
3. echo MESSAGE;
4. ?>
Output:
Hello const by FUTA PHP
Constant() function
There is another way to print the value of constants using constant() function instead of using
the echo statement.
Syntax
The syntax for the following constant function:
1. constant (name)
File: constant5.php

1. <?php
2. define("MSG", "FUTA");
3. echo MSG, "</br>";
4. echo constant("MSG");
5. //both are similar
6. ?>
Output:
FUTA
FUTA

Constant vs Variables

Constant Variables

Once the constant is defined, it can never be A variable can be undefined as well as
redefined. redefined easily.

64
A constant can only be defined using define() A variable can be defined by simple
function. It cannot be defined by any simple assignment (=) operator.
assignment.

There is no need to use the dollar ($) sign before To declare a variable, always use the dollar
constant during the assignment. ($) sign before the variable.

Constants do not follow any variable scoping Variables can be declared anywhere in the
rules, and they can be defined and accessed program, but they follow variable scoping
anywhere. rules.

Constants are the variables whose values can't The value of the variable can be changed.
be changed throughout the program.

By default, constants are global. Variables can be local, global, or static.

PHP Data Types


PHP data types are used to hold different types of data or values. PHP supports 8 primitive
data types that can be categorized further in 3 types:
1. Scalar Types (predefined)
2. Compound Types (user-defined)
3. Special Types
PHP Data Types: Scalar Types
It holds only single value. There are 4 scalar data types in PHP.
1. boolean
2. integer
3. float
4. string
PHP Data Types: Compound Types
It can hold multiple values. There are 2 compound data types in PHP.
1. array
2. object
PHP Data Types: Special Types
There are 2 special data types in PHP.

65
1. resource
2. NULL

PHP Boolean
Booleans are the simplest data type works like switch. It holds only two values: TRUE
(1) or FALSE (0). It is often used with conditional statements. If the condition is correct, it
returns TRUE otherwise FALSE.
Example:
1. <?php
2. if (TRUE)
3. echo "This condition is TRUE.";
4. if (FALSE)
5. echo "This condition is FALSE.";
6. ?>
Output: This condition is TRUE.
PHP Integer
Integer means numeric data with a negative or positive sign. It holds only whole numbers,
i.e., numbers without fractional part or decimal points.
Rules for integer:
o An integer can be either positive or negative.
o An integer must not contain decimal point.
o Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
o The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 i.e., -
2^31 to 2^31.
Example:
1. <?php
2. $dec1 = 34;
3. $oct1 = 0243;
4. $hexa1 = 0x45;
5. echo "Decimal number: " .$dec1. "</br>";
6. echo "Octal number: " .$oct1. "</br>";
7. echo "HexaDecimal number: " .$hexa1. "</br>";
8. ?>

66
Output:
Decimal number: 34
Octal number: 163
HexaDecimal number: 69
PHP Float
A floating-point number is a number with a decimal point. Unlike integer, it can hold
numbers with a fractional or decimal point, including a negative or positive sign.
Example:
1. <?php
2. $n1 = 19.34;
3. $n2 = 54.472;
4. $sum = $n1 + $n2;
5. echo "Addition of floating numbers: " .$sum;
6. ?>
Output:
Addition of floating numbers: 73.812
PHP String
A string is a non-numeric data type. It holds letters or any alphabets, numbers, and even
special characters.
String values must be enclosed either within single quotes or in double quotes. But both are
treated differently. To clarify this, see the example below:
Example:
1. <?php
2. $company = "FUTA";
3. //both single and double quote statements will treat different
4. echo "Hello $company";
5. echo "</br>";
6. echo 'Hello $company';
7. ?>
Output:
Hello FUTA
Hello $company
PHP Array

67
An array is a compound data type. It can store multiple values of same data type in a single
variable.
Example:
1. <?php
2. $bikes = array ("Royal Enfield", "Yamaha", "KTM");
3. var_dump($bikes); //the var_dump() function returns the datatype and values
4. echo "</br>";
5. echo "Array Element1: $bikes[0] </br>";
6. echo "Array Element2: $bikes[1] </br>";
7. echo "Array Element3: $bikes[2] </br>";
8. ?>
Output:
array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3) "KTM"
}
Array Element1: Royal Enfield
Array Element2: Yamaha
Array Element3: KTM
You will learn more about array in later chapters of this tutorial.
PHP object
Objects are the instances of user-defined classes that can store both values and functions.
They must be explicitly declared.
Example:
1. <?php
2. class bike {
3. function model() {
4. $model_name = "Royal Enfield";
5. echo "Bike Model: " .$model_name;
6. }
7. }
8. $obj = new bike();
9. $obj -> model();
10. ?>
Output:

68
Bike Model: Royal Enfield
This is an advanced topic of PHP, which we will discuss later in detail.
PHP Resource
Resources are not the exact data type in PHP. Basically, these are used to store some function
calls or references to external PHP resources. For example - a database call. It is an external
resource.
This is an advanced topic of PHP, so we will discuss it later in detail with examples.
PHP Null
Null is a special data type that has only one value: NULL. There is a convention of writing it
in capital letters as it is case sensitive.
The special type of data type NULL defined a variable with no value.
Example:

1. <?php
2. $nl = NULL;
3. echo $nl; //it will not give any output
4. ?>
Output:
PHP Operators
PHP Operator is a symbol i.e used to perform operations on operands. In simple words,
operators are used to perform operations on variables or values. For example:
1. $num=10+20;//+ is the operator and 10,20 are operands
In the above example, + is the binary + operator, 10 and 20 are operands and $num is
variable.
PHP Operators can be categorized in following forms:
o Arithmetic Operators
o Assignment Operators
o Bitwise Operators
o Comparison Operators
o Incrementing/Decrementing Operators
o Logical Operators
o String Operators
o Array Operators
o Type Operators

69
o Execution Operators
o Error Control Operators
We can also categorize operators on behalf of operands. They can be categorized in 3 forms:
o Unary Operators: works on single operands such as ++, -- etc.
o Binary Operators: works on two operands such as binary +, -, *, / etc.
o Ternary Operators: works on three operands such as "?:".

Arithmetic Operators
The PHP arithmetic operators are used to perform common arithmetic operations such as
addition, subtraction, etc. with numeric values.

Operator Name Example Explanation

+ Addition $a + $b Sum of operands

- Subtraction $a - $b Difference of operands

* Multiplication $a * $b Product of operands

/ Division $a / $b Quotient of operands

% Modulus $a % $b Remainder of operands

** Exponentiation $a ** $b $a raised to the power $b

The exponentiation (**) operator has been introduced in PHP 5.6.

Assignment Operators
The assignment operators are used to assign value to different variables. The basic
assignment operator is "=".

Operator Name Example Explanation

= Assign $a = $b The value of right operand is assigned to the


left operand.

70
+= Add then Assign $a += $b Addition same as $a = $a + $b

-= Subtract then $a -= $b Subtraction same as $a = $a - $b


Assign

*= Multiply then $a *= $b Multiplication same as $a = $a * $b


Assign

/= Divide then $a /= $b Find quotient same as $a = $a / $b


Assign
(quotient)

%= Divide then $a %= $b Find remainder same as $a = $a % $b


Assign
(remainder)

Bitwise Operators
The bitwise operators are used to perform bit-level operations on operands. These operators
allow the evaluation and manipulation of specific bits within the integer.

Operator Name Example Explanation

& And $a & $b Bits that are 1 in both $a and $b are set to 1,
otherwise 0.

| Or (Inclusive or) $a | $b Bits that are 1 in either $a or $b are set to 1

^ Xor (Exclusive $a ^ $b Bits that are 1 in either $a or $b are set to 0.


or)

~ Not ~$a Bits that are 1 set to 0 and bits that are 0 are set
to 1

<< Shift left $a << $b Left shift the bits of operand $a $b steps

>> Shift right $a >> $b Right shift the bits of $a operand by $b number
of places

71
Comparison Operators
Comparison operators allow comparing two values, such as number or string. Below the list
of comparison operators are given:

Operator Name Example Explanation

== Equal $a == $b Return TRUE if $a is equal to $b

=== Identical $a === $b Return TRUE if $a is equal to $b, and they are
of same data type

!== Not identical $a !== $b Return TRUE if $a is not equal to $b, and they
are not of same data type

!= Not equal $a != $b Return TRUE if $a is not equal to $b

<> Not equal $a <> $b Return TRUE if $a is not equal to $b

< Less than $a < $b Return TRUE if $a is less than $b

> Greater than $a > $b Return TRUE if $a is greater than $b

<= Less than or $a <= $b Return TRUE if $a is less than or equal $b


equal to

>= Greater than or $a >= $b Return TRUE if $a is greater than or equal $b


equal to

<=> Spaceship $a <=>$b Return -1 if $a is less than $b


Return 0 if $a is equal $b
Return 1 if $a is greater than $b

72
Incrementing/Decrementing Operators
The increment and decrement operators are used to increase and decrease the value of a
variable.

Operator Name Example Explanation

++ Increment ++$a Increment the value of $a by one, then return $a

$a++ Return $a, then increment the value of $a by one

-- decrement --$a Decrement the value of $a by one, then return $a

$a-- Return $a, then decrement the value of $a by one

Logical Operators
The logical operators are used to perform bit-level operations on operands. These operators
allow the evaluation and manipulation of specific bits within the integer.

Operator Name Example Explanation

And And $a and $b Return TRUE if both $a and $b are true

Or Or $a or $b Return TRUE if either $a or $b is true

Xor Xor $a xor $b Return TRUE if either $ or $b is true but not both

! Not ! $a Return TRUE if $a is not true

&& And $a && $b Return TRUE if either $a and $b are true

|| Or $a || $b Return TRUE if either $a or $b is true

String Operators

73
The string operators are used to perform the operation on strings. There are two string
operators in PHP, which are given below:

Operator Name Example Explanation

. Concatenation $a . $b Concatenate both $a and $b

.= Concatenation and $a .= $b First concatenate $a and $b, then assign the


Assignment concatenated string to $a, e.g. $a = $a . $b

Array Operators
The array operators are used in case of array. Basically, these operators are used to compare
the values of arrays.

Operator Name Example Explanation

+ Union $a + $y Union of $a and $b

== Equality $a == $b Return TRUE if $a and $b have same key/value pair

!= Inequality $a != $b Return TRUE if $a is not equal to $b

=== Identity $a === $b Return TRUE if $a and $b have same key/value pair
of same type in same order

!== Non- $a !== $b Return TRUE if $a is not identical to $b


Identity

<> Inequality $a <> $b Return TRUE if $a is not equal to $b

Type Operators
The type operator instanceof is used to determine whether an object, its parent and its
derived class are the same type or not. Basically, this operator determines which certain class
the object belongs to. It is used in object-oriented programming.
1. <?php
2. //class declaration
3. class Developer
4. {}

74
5. class Programmer
6. {}
7. //creating an object of type Developer
8. $charu = new Developer();
9.
10. //testing the type of object
11. if( $charu instanceof Developer)
12. {
13. echo "Charu is a developer.";
14. }
15. else
16. {
17. echo "Charu is a programmer.";
18. }
19. echo "</br>";
20. var_dump($charu instanceof Developer); //It will return true.
21. var_dump($charu instanceof Programmer); //It will return false.
22. ?>
Output:
Charu is a developer.
bool(true) bool(false)

Execution Operators
PHP has an execution operator backticks (``). PHP executes the content of backticks as a
shell command. Execution operator and shell_exec() give the same result.

Operator Name Example Explanation

`` backticks echo `dir`; Execute the shell command and return the result.
Here, it will show the directories available in current
folder.

Note: Note that backticks (``) are not single-quotes.

Error Control Operators


75
PHP has one error control operator, i.e., at (@) symbol. Whenever it is used with an
expression, any error message will be ignored that might be generated by that expression.

Operator Name Example Explanation

@ at @file ('non_existent_file') Intentional file error

PHP Operators Precedence


Let's see the precedence of PHP operators with associativity.

Operators Additional Information Associativity

clone new clone and new non-


associative

[ array() left

** arithmetic right

++ -- ~ (int) (float) (string) (array) (object) increment/decrement and types right


(bool) @

instanceof types non-


associative

! logical (negation) right

*/% arithmetic left

+-. arithmetic and string left


concatenation

<< >> bitwise (shift) left

< <= > >= comparison non-


associative

== != === !== <> comparison non-


associative

76
& bitwise AND left

^ bitwise XOR left

| bitwise OR left

&& logical AND left

|| logical OR left

?: ternary left

= += -= *= **= /= .= %= &= |= ^= <<= assignment right


>>= =>

and logical left

xor logical left

or logical left

, many uses (comma) left

PHP Comments
PHP comments can be used to describe any line of code so that other developer can
understand the code easily. It can also be used to hide any code.
PHP supports single line and multi line comments. These comments are similar to C/C++ and Perl
style (Unix shell style) comments.
PHP Single Line Comments
There are two ways to use single line comments in PHP.
o // (C++ style single line comment)
o # (Unix Shell style single line comment)
1. <?php
2. // this is C++ style single line comment
3. # this is Unix Shell style single line comment
4. echo "Welcome to PHP single line comments";
5. ?>

77
Output:
Welcome to PHP single line comments
PHP Multi Line Comments
In PHP, we can comments multiple lines also. To do so, we need to enclose all lines within /*
*/. Let's see a simple example of PHP multiple line comment.
1. <?php
2. /*
3. Anything placed
4. within comment
5. will not be displayed
6. on the browser;
7. */
8. echo "Welcome to PHP multi line comment";
9. ?>
Output:
Welcome to PHP multi line comment
Control Statements
PHP If Else
PHP if else statement is used to test condition. There are various ways to use if statement in
PHP.

o if
o if-else
o if-else-if
o nested if
PHP If Statement
PHP if statement allows conditional execution of code. It is executed if condition is true.
If statement is used to executes the block of code exist inside the if statement only if the
specified condition is true.
Syntax
1. if(condition){
2. //code to be executed
3. }

78
Flowchart

Example
1. <?php
2. $num=12;
3. if($num<100){
4. echo "$num is less than 100";
5. }
6. ?>
Output:
12 is less than 100
PHP If-else Statement
PHP if-else statement is executed whether condition is true or false.
If-else statement is slightly different from if statement. It executes one block of code if the
specified condition is true and another block of code if the condition is false.
Syntax
1. if(condition){
2. //code to be executed if true
3. }else{
4. //code to be executed if false
5. }

79
Flowchart

Example
1. <?php
2. $num=12;
3. if($num%2==0){
4. echo "$num is even number";
5. }else{
6. echo "$num is odd number";
7. }
8. ?>
Output:
12 is even number
PHP If-else-if Statement
The PHP if-else-if is a special statement used to combine multiple if?.else statements. So, we
can check multiple conditions using this statement.
Syntax
1. if (condition1){
2. //code to be executed if condition1 is true
3. } elseif (condition2){
4. //code to be executed if condition2 is true
5. } elseif (condition3){
6. //code to be executed if condition3 is true
7. ....

80
8. } else{
9. //code to be executed if all given conditions are false
10. }
Flowchart

Example
1. <?php
2. $marks=69;
3. if ($marks<33){
4. echo "fail";
5. }
6. else if ($marks>=34 && $marks<50) {
7. echo "D grade";
8. }
9. else if ($marks>=50 && $marks<65) {
10. echo "C grade";
11. }
12. else if ($marks>=65 && $marks<80) {
13. echo "B grade";
14. }
15. else if ($marks>=80 && $marks<90) {
16. echo "A grade";
17. }
18. else if ($marks>=90 && $marks<100) {

81
19. echo "A+ grade";
20. }
21. else {
22. echo "Invalid input";
23. }
24. ?>
Output:
B Grade
PHP nested if Statement
The nested if statement contains the if block inside another if block. The inner if statement
executes only when specified condition in outer if statement is true.
Syntax
1. if (condition) {
2. //code to be executed if condition is true
3. if (condition) {
4. //code to be executed if condition is true
5. }
6. }
Flowchart

Example
1. <?php
2. $age = 23;
3. $nationality = "Indian";

82
4. //applying conditions on nationality and age
5. if ($nationality == "Indian")
6. {
7. if ($age >= 18) {
8. echo "Eligible to give vote";
9. }
10. else {
11. echo "Not eligible to give vote";
12. }
13. }
14. ?>
Output:
Eligible to give vote
PHP Switch Example
1. <?php
2. $a = 34; $b = 56; $c = 45;
3. if ($a < $b) {
4. if ($a < $c) {
5. echo "$a is smaller than $b and $c";
6. }
7. }
8. ?>
Output:
34 is smaller than 56 and 45

PHP Switch
PHP switch statement is used to execute one statement from multiple conditions. It works like
PHP if-else-if statement.
Syntax
1. switch(expression){
2. case value1:
3. //code to be executed

83
4. break;
5. case value2:
6. //code to be executed
7. break;
8. ......
9. default:
10. code to be executed if all cases are not matched;
11. }
Important points to be noticed about switch case:
1. The default is an optional statement. Even it is not important, that default must
always be the last statement.
2. There can be only one default in a switch statement. More than one default may lead
to a Fatal error.
3. Each case can have a break statement, which is used to terminate the sequence of
statement.
4. The break statement is optional to use in switch. If break is not used, all the
statements will execute after finding matched case value.
5. PHP allows you to use number, character, string, as well as functions in switch
expression.
6. Nesting of switch statements is allowed, but it makes the program more complex and
less readable.
7. You can use semicolon (;) instead of colon (:). It will not generate any error.
PHP Switch Flowchart

84
PHP Switch Example
1. <?php
2. $num=20;
3. switch($num){
4. case 10:
5. echo("number is equals to 10");
6. break;
7. case 20:
8. echo("number is equal to 20");
9. break;
10. case 30:

85
11. echo("number is equal to 30");
12. break;
13. default:
14. echo("number is not equal to 10, 20 or 30");
15. }
16. ?>
Output:
number is equal to 20
PHP switch statement with character
Program to check Vowel and consonant
We will pass a character in switch expression to check whether it is vowel or constant. If the
passed character is A, E, I, O, or U, it will be vowel otherwise consonant.
1. <?php
2. $ch = 'U';
3. switch ($ch)
4. {
5. case 'a':
6. echo "Given character is vowel";
7. break;
8. case 'e':
9. echo "Given character is vowel";
10. break;
11. case 'i':
12. echo "Given character is vowel";
13. break;
14. case 'o':
15. echo "Given character is vowel";
16. break;
17. case 'u':
18. echo "Given character is vowel";
19. break;
20. case 'A':

86
21. echo "Given character is vowel";
22. break;
23. case 'E':
24. echo "Given character is vowel";
25. break;
26. case 'I':
27. echo "Given character is vowel";
28. break;
29. case 'O':
30. echo "Given character is vowel";
31. break;
32. case 'U':
33. echo "Given character is vowel";
34. break;
35. default:
36. echo "Given character is consonant";
37. break;
38. }
39. ?>
Output:
Given character is vowel
PHP switch statement with String
PHP allows to pass string in switch expression. Let's see the below example of course
duration by passing string in switch case statement.
1. <?php
2. $ch = "B.Tech";
3. switch ($ch)
4. {
5. case "BCA":
6. echo "BCA is 3 years course";
7. break;
8. case "Bsc":

87
9. echo "Bsc is 3 years course";
10. break;
11. case "B.Tech":
12. echo "B.Tech is 4 years course";
13. break;
14. case "B.Arch":
15. echo "B.Arch is 5 years course";
16. break;
17. default:
18. echo "Wrong Choice";
19. break;
20. }
21. ?>
Output:
B.Tech is 4 years course
PHP switch statement is fall-through
PHP switch statement is fall-through. It means it will execute all statements after getting the
first match, if break statement is not found.
1. <?php
2. $ch = 'c';
3. switch ($ch)
4. {
5. case 'a':
6. echo "Choice a";
7. break;
8. case 'b':
9. echo "Choice b";
10. break;
11. case 'c':
12. echo "Choice c";
13. echo "</br>";
14. case 'd':

88
15. echo "Choice d";
16. echo "</br>";
17. default:
18. echo "case a, b, c, and d is not found";
19. }
20. ?>
Output:
Choice c
Choice d
case a, b, c, and d is not found
PHP nested switch statement
Nested switch statement means switch statement inside another switch statement. Sometimes
it leads to confusion.
1. <?php
2. $car = "Hyundai";
3. $model = "Tucson";
4. switch( $car )
5. {
6. case "Honda":
7. switch( $model )
8. {
9. case "Amaze":
10. echo "Honda Amaze price is 5.93 - 9.79 Lakh.";
11. break;
12. case "City":
13. echo "Honda City price is 9.91 - 14.31 Lakh.";
14. break;
15. }
16. break;
17. case "Renault":
18. switch( $model )
19. {

89
20. case "Duster":
21. echo "Renault Duster price is 9.15 - 14.83 L.";
22. break;
23. case "Kwid":
24. echo "Renault Kwid price is 3.15 - 5.44 L.";
25. break;
26. }
27. break;
28. case "Hyundai":
29. switch( $model )
30. {
31. case "Creta":
32. echo "Hyundai Creta price is 11.42 - 18.73 L.";
33. break;
34. case "Tucson":
35. echo "Hyundai Tucson price is 22.39 - 32.07 L.";
36. break;
37. case "Xcent":
38. echo "Hyundai Xcent price is 6.5 - 10.05 L.";
39. break;
40. }
41. break;
42. }
43. ?>
Output:
Hyundai Tucson price is 22.39 - 32.07 L.
PHP For Loop
PHP for loop can be used to traverse set of code for the specified number of times.
It should be used if the number of iterations is known otherwise use while loop. This means
for loop is used when you already know how many times you want to execute a block of
code.
It allows users to put all the loop related statements in one place. See in the syntax given
below:

90
Syntax
1. for(initialization; condition; increment/decrement){
2. //code to be executed
3. }
Parameters
The php for loop is similar to the java/C/C++ for loop. The parameters of for loop have the
following meanings:
initialization - Initialize the loop counter value. The initial value of the for loop is done only
once. This parameter is optional.
condition - Evaluate each iteration value. The loop continuously executes until the condition
is false. If TRUE, the loop execution continues, otherwise the execution of the loop ends.
Increment/decrement - It increments or decrements the value of the variable.

Flowchart

Example
1. <?php
2. for($n=1;$n<=10;$n++){
3. echo "$n<br/>";
4. }
5. ?>
Output:

91
1
2
3
4
5
6
7
8
9
10
Example
All three parameters are optional, but semicolon (;) is must to pass in for loop. If we don't
pass parameters, it will execute infinite.
1. <?php
2. $i = 1;
3. //infinite loop
4. for (;;) {
5. echo $i++;
6. echo "</br>";
7. }
8. ?>
Output:
1
2
3
4
.
.
.
Example
Below is the example of printing numbers from 1 to 9 in four different ways using for loop.
1. <?php

92
2. /* example 1 */
3.
4. for ($i = 1; $i <= 9; $i++) {
5. echo $i;
6. }
7. echo "</br>";
8.
9. /* example 2 */
10.
11. for ($i = 1; ; $i++) {
12. if ($i > 9) {
13. break;
14. }
15. echo $i;
16. }
17. echo "</br>";
18.
19. /* example 3 */
20.
21. $i = 1;
22. for (; ; ) {
23. if ($i > 9) {
24. break;
25. }
26. echo $i;
27. $i++;
28. }
29. echo "</br>";
30.
31. /* example 4 */
32.
33. for ($i = 1, $j = 0; $i <= 9; $j += $i, print $i, $i++);

93
34. ?>
Output:
123456789
123456789
123456789
123456789
PHP Nested For Loop
We can use for loop inside for loop in PHP, it is known as nested for loop. The inner for loop
executes only when the outer for loop condition is found true.
In case of inner or nested for loop, nested for loop is executed fully for one outer for loop. If
outer for loop is to be executed for 3 times and inner for loop for 3 times, inner for loop will
be executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer loop and 3 times for 3rd
outer loop).

Example
1. <?php
2. for($i=1;$i<=3;$i++){
3. for($j=1;$j<=3;$j++){
4. echo "$i $j<br/>";
5. }
6. }
7. ?>
Output:
11
12
13
21
22
23
31
32
33
PHP For Each Loop

94
PHP for each loop is used to traverse array elements.
Syntax
1. foreach( $array as $var ){
2. //code to be executed
3. }
4. ?>
Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. foreach( $season as $arr ){
4. echo "Season is: $arr<br />";
5. }
6. ?>
Output:
Season is: summer
Season is: winter
Season is: spring
Season is: autumn
PHP foreach loop
The foreach loop is used to traverse the array elements. It works only on array and object. It
will issue an error if you try to use it with the variables of different datatype.
Polymorphism in Java | Dynamic Method Dispatch
The foreach loop works on elements basis rather than index. It provides an easiest way to
iterate the elements of an array.
In foreach loop, we don't need to increment the value.
Syntax
1. foreach ($array as $value) {
2. //code to be executed
3. }
There is one more syntax of foreach loop.
Syntax
1. foreach ($array as $key => $element) {

95
2. //code to be executed
3. }
Flowchart

Example 1:
PHP program to print array elements using foreach loop.
1. <?php
2. //declare array
3. $season = array ("Summer", "Winter", "Autumn", "Rainy");
4.
5. //access array elements using foreach loop
6. foreach ($season as $element) {
7. echo "$element";
8. echo "</br>";
9. }
10. ?>
Output:
Summer
Winter

96
Autumn
Rainy
Example 2:
PHP program to print associative array elements using foreach loop.

1. <?php
2. //declare array
3. $employee = array (
4. "Name" => "Alex",
5. "Email" => "[email protected]",
6. "Age" => 21,
7. "Gender" => "Male"
8. );
9.
10. //display associative array element through foreach loop
11. foreach ($employee as $key => $element) {
12. echo $key . " : " . $element;
13. echo "</br>";
14. }
15. ?>
Output:
Name : Alex
Email : [email protected]
Age : 21
Gender : Male
Example 3:
Multi-dimensional array
1. <?php
2. //declare multi-dimensional array
3. $a = array();
4. $a[0][0] = "Alex";
5. $a[0][1] = "Bob";

97
6. $a[1][0] = "Camila";
7. $a[1][1] = "Denial";
8.
9. //display multi-dimensional array elements through foreach loop
10. foreach ($a as $e1) {
11. foreach ($e1 as $e2) {
12. echo "$e2\n";
13. }
14. }
15. ?>
Output:
Alex Bob Camila Denial
Example 4:
Dynamic array
1. <?php
2. //dynamic array
3. foreach (array ('f', 'e', 'd', 'e', 'r', 'a', 'l') as $elements) {
4. echo "$elements\n";
5. }
6. ?>
Output:
federal
PHP While Loop
PHP while loop can be used to traverse set of code like for loop. The while loop executes a
block of code repeatedly until the condition is FALSE. Once the condition gets FALSE, it
exits from the body of loop.
Polymorphism in Java | Dynamic Method Dispatch
It should be used if the number of iterations is not known.
The while loop is also called an Entry control loop because the condition is checked before
entering the loop body. This means that first the condition is checked. If the condition is true,
the block of code will be executed.
Syntax
1. while(condition){

98
2. //code to be executed
3. }
Alternative Syntax
1. while(condition):
2. //code to be executed
3.
4. endwhile;
PHP While Loop Flowchart

PHP While Loop Example


1. <?php
2. $n=1;
3. while($n<=10){
4. echo "$n<br/>";
5. $n++;
6. }
7. ?>
Output:
1
2
3
4
5

99
6
7
8
9
10
Alternative Example
1. <?php
2. $n=1;
3. while($n<=10):
4. echo "$n<br/>";
5. $n++;
6. endwhile;
7. ?>
Output:
1
2
3
4
5
6
7
8
9
10
Example
Below is the example of printing alphabets using while loop.
1. <?php
2. $i = 'A';
3. while ($i < 'H') {
4. echo $i;
5. $i++;
6. echo "</br>";

100
7. }
8. ?>
Output:

A
B
C
D
E
F
G
PHP Nested While Loop
We can use while loop inside another while loop in PHP, it is known as nested while loop.
In case of inner or nested while loop, nested while loop is executed fully for one outer while
loop. If outer while loop is to be executed for 3 times and nested while loop for 3 times,
nested while loop will be executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer
loop and 3 times for 3rd outer loop).
Example
1. <?php
2. $i=1;
3. while($i<=3){
4. $j=1;
5. while($j<=3){
6. echo "$i $j<br/>";
7. $j++;
8. }
9. $i++;
10. }
11. ?>
Output:
11
12
13

101
21
22
23
31
32
33
PHP Infinite While Loop
If we pass TRUE in while loop, it will be an infinite loop.
Syntax

1. while(true) {
2. //code to be executed
3. }
Example
1. <?php
2. while (true) {
3. echo "Hello CSC415!";
4. echo "</br>";
5. }
6. ?>
Output:
Hello CSC415!
Hello CSC415!
Hello CSC415!
Hello CSC415!
.
.
.
.
.
Hello CSC415!
Hello CSC415!

102
PHP do-while loop
PHP do-while loop can be used to traverse set of code like php while loop. The PHP do-while
loop is guaranteed to run at least once.
The PHP do-while loop is used to execute a set of code of the program several times. If you
have to execute the loop at least once and the number of iterations is not even fixed, it is
recommended to use the do-while loop.
It executes the code at least one time always because the condition is checked after executing
the code.
The do-while loop is very much similar to the while loop except the condition check. The
main difference between both loops is that while loop checks the condition at the beginning,
whereas do-while loop checks the condition at the end of the loop.
Syntax
1. do{
2. //code to be executed
3. }while(condition);
Flowchart

Example
1. <?php
2. $n=1;
3. do{
4. echo "$n<br/>";
5. $n++;
6. }while($n<=10);
7. ?>
Output:
1

103
2
3
4
5
6
7
8
9
10
Example
A semicolon is used to terminate the do-while loop. If you don't use a semicolon after the do-
while loop, it is must that the program should not contain any other statements after the do-
while loop. In this case, it will not generate any error.
1. <?php
2. $x = 5;
3. do {
4. echo "Welcome to CSC415! </br>";
5. $x++;
6. } while ($x < 10);
7. ?>
Output:

Welcome to CSC415!
Welcome to CSC415!
Welcome to CSC415!
Welcome to CSC415!
Welcome to CSC415!
Example
The following example will increment the value of $x at least once. Because the given
condition is false.
1. <?php
2. $x = 1;
3. do {

104
4. echo "1 is not greater than 10.";
5. echo "</br>";
6. $x++;
7. } while ($x > 10);
8. echo $x;
9. ?>
Output:
1 is not greater than 10.
2
Difference between while and do-while loop

while Loop do-while loop

The while loop is also named as entry The do-while loop is also named as exit control
control loop. loop.

The body of the loop does not execute if The body of the loop executes at least once, even
the condition is false. if the condition is false.

Condition checks first, and then block of Block of statements executes first and then
statements executes. condition checks.

This loop does not use a semicolon to Do-while loop use semicolon to terminate the
terminate the loop. loop.

Functions
PHP Functions
PHP function is a piece of code that can be reused many times. It can take input as argument
list and return value. There are thousands of built-in functions in PHP.
In PHP, we can define Conditional function, Function within Function and Recursive
function also.

Advantage of PHP Functions


Code Reusability: PHP functions are defined only once and can be invoked many times, like
in other programming languages.
Less Code: It saves a lot of code because you don't need to write the logic many times. By
the use of function, you can write the logic only once and reuse it.

105
Easy to understand: PHP functions separate the programming logic. So it is easier to
understand the flow of the application because every logic is divided in the form of functions.

PHP User-defined Functions


We can declare and call user-defined functions easily. Let's see the syntax to declare user-
defined functions.
Syntax
1. function functionname(){
2. //code to be executed
3. }
Note: Function name must be start with letter and underscore only like other labels in PHP. It
can't be start with numbers or special symbols.
PHP Functions Example
File: function1.php
1. <?php
2. function sayHello(){
3. echo "Hello PHP Function";
4. }
5. sayHello();//calling function
6. ?>
Output:

Hello PHP Function


PHP Function Arguments
We can pass the information in PHP function through arguments which is separated by
comma.
PHP supports Call by Value (default), Call by Reference, Default argument
values and Variable-length argument list.
Let's see the example to pass single argument in PHP function.
File: functionarg.php
1. <?php
2. function sayHello($name){
3. echo "Hello $name<br/>";
4. }

106
5. sayHello("Sonoo");
6. sayHello("Vimal");
7. sayHello("John");
8. ?>
Output:
Hello Sonoo
Hello Vimal
Hello John
Let's see the example to pass two argument in PHP function.
File: functionarg2.php
1. <?php
2. function sayHello($name,$age){
3. echo "Hello $name, you are $age years old<br/>";
4. }
5. sayHello("Sonoo",27);
6. sayHello("Vimal",29);
7. sayHello("John",23);
8. ?>
Output:
Hello Sonoo, you are 27 years old
Hello Vimal, you are 29 years old
Hello John, you are 23 years old
PHP Call By Reference
Value passed to the function doesn't modify the actual value by default (call by value). But
we can do so by passing value as a reference.
By default, value passed to the function is call by value. To pass value as a reference, you
need to use ampersand (&) symbol before the argument name.
Let's see a simple example of call by reference in PHP.
File: functionref.php

1. <?php
2. function adder(&$str2)

107
3. {
4. $str2 .= 'Call By Reference';
5. }
6. $str = 'Hello ';
7. adder($str);
8. echo $str;
9. ?>
Output:
Hello Call By Reference
PHP Function: Default Argument Value
We can specify a default argument value in function. While calling PHP function if you don't
specify any argument, it will take the default argument. Let's see a simple example of using
default argument value in PHP function.
File: functiondefaultarg.php
1. <?php
2. function sayHello($name="Sonoo"){
3. echo "Hello $name<br/>";
4. }
5. sayHello("Rajesh");
6. sayHello();//passing no value
7. sayHello("John");
8. ?>
Output:

Hello Rajesh
Hello Sonoo
Hello John
PHP Function: Returning Value
Let's see an example of PHP function that returns value.
File: functiondefaultarg.php
1. <?php
2. function cube($n){
3. return $n*$n*$n;

108
4. }
5. echo "Cube of 3 is: ".cube(3);
6. ?>
Output:
Cube of 3 is: 27
PHP Parameterized Function
PHP Parameterized functions are the functions with parameters. You can pass any number of
parameters inside a function. These passed parameters act as variables inside your function.
They are specified inside the parentheses, after the function name.
The output depends upon the dynamic values passed as the parameters into the function.

PHP Parameterized Example 1


Addition and Subtraction
In this example, we have passed two parameters $x and $y inside two
functions add() and sub().
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Parameter Addition and Subtraction Example</title>
5. </head>
6. <body>
7. <?php
8. //Adding two numbers
9. function add($x, $y) {
10. $sum = $x + $y;
11. echo "Sum of two numbers is = $sum <br><br>";
12. }
13. add(467, 943);
14.
15. //Subtracting two numbers
16. function sub($x, $y) {
17. $diff = $x - $y;
18. echo "Difference between two numbers is = $diff";

109
19. }
20. sub(943, 467);
21. ?>
22. </body>
23. </html>
Output:

PHP Parameterized Example 2


Addition and Subtraction with Dynamic number
In this example, we have passed two parameters $x and $y inside two
functions add() and sub().

1. <?php
2. //add() function with two parameter
3. function add($x,$y)
4. {
5. $sum=$x+$y;
6. echo "Sum = $sum <br><br>";
7. }
8. //sub() function with two parameter
9. function sub($x,$y)
10. {
11. $sub=$x-$y;
12. echo "Diff = $sub <br><br>";
13. }
14. //call function, get two argument through input box and click on add or sub button
15. if(isset($_POST['add']))

110
16. {
17. //call add() function
18. add($_POST['first'],$_POST['second']);
19. }
20. if(isset($_POST['sub']))
21. {
22. //call add() function
23. sub($_POST['first'],$_POST['second']);
24. }
25. ?>
26. <form method="post">
27. Enter first number: <input type="number" name="first"/><br><br>
28. Enter second number: <input type="number" name="second"/><br><br>
29. <input type="submit" name="add" value="ADDITION"/>
30. <input type="submit" name="sub" value="SUBTRACTION"/>
31. </form>
Output:

We passed the following number,

111
Now clicking on ADDITION button, we get the following output.

Now clicking on SUBTRACTION button, we get the following output.

PHP Call By Value


PHP allows you to call function by value and reference both. In case of PHP call by value,
actual value is not modified if it is modified inside the function.
Let's understand the concept of call by value by the help of examples.
Example 1
In this example, variable $str is passed to the adder function where it is concatenated with
'Call By Value' string. But, printing $str variable results 'Hello' only. It is because changes are
done in the local variable $str2 only. It doesn't reflect to $str variable.
1. <?php
2. function adder($str2)
3. {
4. $str2 .= 'Call By Value';
5. }
6. $str = 'Hello ';
7. adder($str);
8. echo $str;

112
9. ?>
Output:
Hello
Example 2
Let's understand PHP call by value concept through another example.
1. <?php
2. function increment($i)
3. {
4. $i++;
5. }
6. $i = 10;
7. increment($i);
8. echo $i;
9. ?>
Output:
10

PHP Call By Reference


In case of PHP call by reference, actual value is modified if it is modified inside the function.
In such case, you need to use & (ampersand) symbol with formal arguments. The &
represents reference of the variable.
Let's understand the concept of call by reference by the help of examples.
Example 1
In this example, variable $str is passed to the adder function where it is concatenated with
'Call By Reference' string. Here, printing $str variable results 'This is Call By Reference'. It is
because changes are done in the actual variable $str.
1. <?php
2. function adder(&$str2)
3. {
4. $str2 .= 'Call By Reference';
5. }
6. $str = 'This is ';
7. adder($str);

113
8. echo $str;
9. ?>
Output:
This is Call By Reference
Example 2
Let's understand PHP call by reference concept through another example.
1. <?php
2. function increment(&$i)
3. {
4. $i++;
5. }
6. $i = 10;
7. increment($i);
8. echo $i;
9. ?>
Output:
11

114
PHP Math
PHP provides many predefined math constants and functions that can be used to perform
mathematical operations.
PHP Math: abs() function
The abs() function returns absolute value of given number. It returns an integer value but if
you pass floating point value, it returns a float value.
Syntax
1. number abs ( mixed $number )
Example
1. <?php
2. echo (abs(-7)."<br/>"); // 7 (integer)
3. echo (abs(7)."<br/>"); //7 (integer)
4. echo (abs(-7.2)."<br/>"); //7.2 (float/double)
5. ?>
Output:
7
7
7.2
PHP Math: ceil() function
The ceil() function rounds fractions up.
Syntax
1. float ceil ( float $value )
Example
1. <?php
2. echo (ceil(3.3)."<br/>");// 4
3. echo (ceil(7.333)."<br/>");// 8
4. echo (ceil(-4.8)."<br/>");// -4
5. ?>
Output:
4
8
-4

115
PHP Math: floor() function
The floor() function rounds fractions down.
Syntax
1. float floor ( float $value )
Example
1. <?php
2. echo (floor(3.3)."<br/>");// 3
3. echo (floor(7.333)."<br/>");// 7
4. echo (floor(-4.8)."<br/>");// -5
5. ?>
Output:

3
7
-5
PHP Math: sqrt() function
The sqrt() function returns square root of given argument.
Syntax
1. float sqrt ( float $arg )
Example
1. <?php
2. echo (sqrt(16)."<br/>");// 4
3. echo (sqrt(25)."<br/>");// 5
4. echo (sqrt(7)."<br/>");// 2.6457513110646
5. ?>
Output:
4
5
2.6457513110646
PHP Math: decbin() function
The decbin() function converts decimal number into binary. It returns binary number as a
string.

116
Syntax
1. string decbin ( int $number )
Example
1. <?php
2. echo (decbin(2)."<br/>");// 10
3. echo (decbin(10)."<br/>");// 1010
4. echo (decbin(22)."<br/>");// 10110
5. ?>
Output:
10
1010
10110
PHP Math: dechex() function
The dechex() function converts decimal number into hexadecimal. It returns hexadecimal
representation of given number as a string.
Syntax
1. string dechex ( int $number )
Example
1. <?php
2. echo (dechex(2)."<br/>");// 2
3. echo (dechex(10)."<br/>");// a
4. echo (dechex(22)."<br/>");// 16
5. ?>
Output:

2
a
16
PHP Math: decoct() function
The decoct() function converts decimal number into octal. It returns octal representation of
given number as a string.
Syntax
1. string decoct ( int $number )

117
Example
1. <?php
2. echo (decoct(2)."<br/>");// 2
3. echo (decoct(10)."<br/>");// 12
4. echo (decoct(22)."<br/>");// 26
5. ?>
Output:
2
12
26
PHP Math: base_convert() function
The base_convert() function allows you to convert any base number to any base number. For
example, you can convert hexadecimal number to binary, hexadecimal to octal, binary to
octal, octal to hexadecimal, binary to decimal etc.
Syntax
1. string base_convert ( string $number , int $frombase , int $tobase )
Example
1. <?php
2. $n1=10;
3. echo (base_convert($n1,10,2)."<br/>");// 1010
4. ?>
Output:
1010
PHP Math: bindec() function
The bindec() function converts binary number into decimal.
Syntax
1. number bindec ( string $binary_string )
Example
1. <?php
2. echo (bindec(10)."<br/>");// 2
3. echo (bindec(1010)."<br/>");// 10
4. echo (bindec(1011)."<br/>");// 11
5. ?>

118
Output:

2
10
11
PHP Math Functions
Let's see the list of important PHP math functions.

Function Description

abs() It is used to find the absolute (positive) value of a number.

sin() It is used to return the sine of a number.

sinh() It is used to return the hyperbolic sine of a number.

asin() It is used to find the arc sine of a number.

asinh() It is used to find the inverse hyperbolic sine of a number.

cos() It is used to find the cosine of a number.

cosh() It is used to return the cosh of a number.

acos() It is used to return the arc cosine of a number.

acosh() It is used to return the inverse hyperbolic cosine of a number.

tan() It is used to return the tangent of a number.

tanh() It is used to return the hyperbolic tangent of a number.

atan() It is used to return the arc tangent of a number in radians.

atan2() It is used to return the arc tangent of two variables x and y.

atanh() It is used to return the inverse hyperbolic tangent of a number.

119
base_convert() It is used to convert a number from one number base to another.

bindec() It is used to convert a binary number to a decimal number.

ceil() It is used to find round a number up to the nearest integer.

pi() It returns the approximation value of PI.

decbin() It converts a decimal number to a binary number.

dechex() It converts a decimal number to a hexadecimal number.

decoct() It converts a decimal number to an octal number

deg2rad() It converts a degree value to a radian value.

rad2deg() It converts a radian value to a degree value.

exp() It is used to calculate the exponent of e.

expm1() It is used to return exp(x) - 1.

floor() It converts round a number down to the nearest integer.

fmod() It returns the remainder of x/y.

getrandmax() It returns the largest possible value returned by rand().

hexadec() It is used to convert a hexadecimal number to a decimal number.

hypot() It is used to calculate the hypotenuse of a right-angle triangle.

is_finite() To check whether a value is finite or not.

is_infinite() It is used to check whether a value is infinite or not.

is_nan() It is used to check whether a value is 'not-a-number'.

lcg_value() It is used to return a pseudo random number in a range between 0 and 1.

120
log() It is used to return the natural logarithm of a number.

log10() It is used to return the base-10 logarithm of a number.

log1p() It is used to return log(1+number).

max() It is used to return the highest value in an array, or the highest value of
several specified values.

min() It returns the lowest value in an array, or the lowest value of several
specified values.

getrandmax() It is used to return the maximum value by using rand().

mt_getrandmax() Returns the largest possible value returned by mt_rand().

mt_rand() Generates a random integer using Mersenne Twister algorithm.

mt_srand() Seeds the Mersenne Twister random number generator.

octdec() It is used to converts an octal number to a decimal number.

pow() It is used to return x raised to the power of y.

intdiv It returns the integer quotient of the division of dividend by divisor.

rand() It is used to generates a random integer.

round() It is used to round a floating-point number.

fmod() It is used to return the floating point remainder of the division of the
argument.

sqrt() It is used to return the square root of a number.

121
PHP Arrays
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple
values of similar type in a single variable.
Advantage of PHP Array
Less Code: We don't need to define multiple variables.
Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
Sorting: We can sort the elements of array.

PHP Array Types


There are 3 types of array in PHP.
1. Indexed Array
2. Associative Array
3. Multidimensional Array

PHP Indexed Array


PHP index is represented by number which starts from 0. We can store number, string and
object in the PHP array. All PHP array elements are assigned to an index number by default.
There are two ways to define indexed array:

1st way:
1. $season=array("summer","winter","spring","autumn");
2nd way:
1. $season[0]="summer";
2. $season[1]="winter";
3. $season[2]="spring";
4. $season[3]="autumn";
Example
File: array1.php
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
4. ?>
Output:

122
Season are: summer, winter, spring and autumn
File: array2.php
1. <?php
2. $season[0]="summer";
3. $season[1]="winter";
4. $season[2]="spring";
5. $season[3]="autumn";
6. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
7. ?>
Output:
Season are: summer, winter, spring and autumn
Click me for more details...

PHP Associative Array


We can associate name with each array elements in PHP using => symbol.
There are two ways to define associative array:

1st way:
1. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
2nd way:
1. $salary["Sonoo"]="350000";
2. $salary["John"]="450000";
3. $salary["Kartik"]="200000";
Example
File: arrayassociative1.php
1. <?php
2. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
3. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
4. echo "John salary: ".$salary["John"]."<br/>";
5. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
6. ?>
Output:

123
Sonoo salary: 350000
John salary: 450000
Kartik salary: 200000
File: arrayassociative2.php
1. <?php
2. $salary["Sonoo"]="350000";
3. $salary["John"]="450000";
4. $salary["Kartik"]="200000";
5. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
6. echo "John salary: ".$salary["John"]."<br/>";
7. echo "Kartik salary: ".$salary["Kartik"]."<br/>";
8. ?>
Output:
Sonoo salary: 350000
John salary: 450000
Kartik salary: 200000
PHP Indexed Array
PHP indexed array is an array which is represented by an index number by default. All
elements of array are represented by an index number which starts from 0.
PHP indexed array can store numbers, strings or any object. PHP indexed array is also known
as numeric array.
Definition
There are two ways to define indexed array:
1st way:
1. $size=array("Big","Medium","Short");
2nd way:
1. $size[0]="Big";
2. $size[1]="Medium";
3. $size[2]="Short";
PHP Indexed Array Example
File: array1.php
1. <?php
2. $size=array("Big","Medium","Short");

124
3. echo "Size: $size[0], $size[1] and $size[2]";
4. ?>
Output:
Size: Big, Medium and Short
File: array2.php
1. <?php
2. $size[0]="Big";
3. $size[1]="Medium";
4. $size[2]="Short";
5. echo "Size: $size[0], $size[1] and $size[2]";
6. ?>
Output:
Size: Big, Medium and Short
Traversing PHP Indexed Array
We can easily traverse array in PHP using foreach loop. Let's see a simple example to
traverse all the elements of PHP array.
File: array3.php
1. <?php
2. $size=array("Big","Medium","Short");
3. foreach( $size as $s )
4. {
5. echo "Size is: $s<br />";
6. }
7. ?>
Output:
Size is: Big
Size is: Medium
Size is: Short
Count Length of PHP Indexed Array
PHP provides count() function which returns length of an array.
1. <?php
2. $size=array("Big","Medium","Short");

125
3. echo count($size);
4. ?>
Output:
3
PHP Associative Array
PHP allows you to associate name/label with each array elements in PHP using => symbol.
Such way, you can easily remember the element because each element is represented by label
than an incremented number.
Definition
There are two ways to define associative array:
1st way:
1. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
2nd way:
1. $salary["Sonoo"]="550000";
2. $salary["Vimal"]="250000";
3. $salary["Ratan"]="200000";
Example
File: arrayassociative1.php
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
4. echo "Vimal salary: ".$salary["Vimal"]."<br/>";
5. echo "Ratan salary: ".$salary["Ratan"]."<br/>";
6. ?>
Output:
Sonoo salary: 550000
Vimal salary: 250000
Ratan salary: 200000
File: arrayassociative2.php
1. <?php
2. $salary["Sonoo"]="550000";
3. $salary["Vimal"]="250000";
4. $salary["Ratan"]="200000";

126
5. echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
6. echo "Vimal salary: ".$salary["Vimal"]."<br/>";
7. echo "Ratan salary: ".$salary["Ratan"]."<br/>";
8. ?>
Output:
Sonoo salary: 550000
Vimal salary: 250000
Ratan salary: 200000
Traversing PHP Associative Array
By the help of PHP for each loop, we can easily traverse the elements of PHP associative
array.
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. foreach($salary as $k => $v) {
4. echo "Key: ".$k." Value: ".$v."<br/>";
5. }
6. ?>
Output:

Key: Sonoo Value: 550000


Key: Vimal Value: 250000
Key: Ratan Value: 200000
PHP Multidimensional Array
PHP multidimensional array is also known as array of arrays. It allows you to store tabular
data in an array. PHP multidimensional array can be represented in the form of matrix which
is represented by row * column.
Definition
1. $emp = array
2. (
3. array(1,"sonoo",400000),
4. array(2,"john",500000),
5. array(3,"rahul",300000)
6. );

127
PHP Multidimensional Array Example
Let's see a simple example of PHP multidimensional array to display following tabular data.
In this example, we are displaying 3 rows and 3 columns.

Id Name

1 sonoo

2 john

3 rahul

File: multiarray.php
1. <?php
2. $emp = array
3. (
4. array(1,"sonoo",400000),
5. array(2,"john",500000),
6. array(3,"rahul",300000)
7. );
8.
9. for ($row = 0; $row < 3; $row++) {
10. for ($col = 0; $col < 3; $col++) {
11. echo $emp[$row][$col]." ";
12. }
13. echo "<br/>";
14. }
15. ?>
Output:
1 sonoo 400000
2 john 500000
3 rahul 300000
PHP Array Functions
PHP provides various array functions to access and manipulate the elements of array. The
important PHP array functions are given below.

128
1) PHP array() function
PHP array() function creates and returns an array. It allows you to create indexed, associative
and multidimensional arrays.
Syntax
1. array array ([ mixed $... ] )
Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
4. ?>
Output:
Season are: summer, winter, spring and autumn
2) PHP array_change_key_case() function
PHP array_change_key_case() function changes the case of all key of an array.
Note: It changes case of key only.
Syntax
1. array array_change_key_case ( array $array [, int $case = CASE_LOWER ] )
Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_change_key_case($salary,CASE_UPPER));
4. ?>
Output:
Array ( [SONOO] => 550000 [VIMAL] => 250000 [RATAN] => 200000 )
Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_change_key_case($salary,CASE_LOWER));
4. ?>
Output:
Array ( [sonoo] => 550000 [vimal] => 250000 [ratan] => 200000 )
3) PHP array_chunk() function

129
PHP array_chunk() function splits array into chunks. By using array_chunk() method, you
can divide array into many parts.
Syntax

1. array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )


Example
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. print_r(array_chunk($salary,2));
4. ?>
Output:
Array (
[0] => Array ( [0] => 550000 [1] => 250000 )
[1] => Array ( [0] => 200000 )
)
4) PHP count() function
PHP count() function counts all elements in an array.
Syntax
1. int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )
Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. echo count($season);
4. ?>
Output:
4
5) PHP sort() function
PHP sort() function sorts all the elements in an array.
Syntax
1. bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
Example

130
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. sort($season);
4. foreach( $season as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>
Output:
autumn
spring
summer
winter
6) PHP array_reverse() function
PHP array_reverse() function returns an array containing elements in reversed order.
Syntax

1. array array_reverse ( array $array [, bool $preserve_keys = false ] )


Example
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $reverseseason=array_reverse($season);
4. foreach( $reverseseason as $s )
5. {
6. echo "$s<br />";
7. }
8. ?>
Output:
autumn
spring
winter
summer

131
7) PHP array_search() function
PHP array_search() function searches the specified value in an array. It returns key if search
is successful.
Syntax
1. mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] )
Example

1. <?php
2. $season=array("summer","winter","spring","autumn");
3. $key=array_search("spring",$season);
4. echo $key;
5. ?>
Output:
2
8) PHP array_intersect() function
PHP array_intersect() function returns the intersection of two array. In other words, it returns
the matching elements of two array.
Syntax
1. array array_intersect ( array $array1 , array $array2 [, array $... ] )
Example
1. <?php
2. $name1=array("sonoo","john","vivek","smith");
3. $name2=array("umesh","sonoo","kartik","smith");
4. $name3=array_intersect($name1,$name2);
5. foreach( $name3 as $n )
6. {
7. echo "$n<br />";
8. }
9. ?>
Output:
sonoo
smith

132
State Management
PHP Cookie
PHP cookie is a small piece of information which is stored at client browser. It is used to
recognize the user.
Cookie is created at server side and saved to client browser. Each time when client sends
request to the server, cookie is embedded with request. Such way, cookie can be received at
the server side.

In short, cookie can be created, sent and received at server end.


Note: PHP Cookie must be used before <html> tag.
PHP setcookie() function
PHP setcookie() function is used to set cookie with HTTP response. Once cookie is set, you
can access it by $_COOKIE superglobal variable.
Syntax
1. bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path
2. [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
Example
1. setcookie("CookieName", "CookieValue");/* defining name and value only*/
2. setcookie("CookieName", "CookieValue", time()+1*60*60);//using expiry in 1 hour(1
*60*60 seconds or 3600 seconds)
3. setcookie("CookieName", "CookieValue", time()+1*60*60, "/mypath/", "mydomain.c
om", 1);
PHP $_COOKIE
PHP $_COOKIE superglobal variable is used to get cookie.
Example

1. $value=$_COOKIE["CookieName"];//returns cookie value


PHP Cookie Example
File: cookie1.php

133
1. <?php
2. setcookie("user", "Sonoo");
3. ?>
4. <html>
5. <body>
6. <?php
7. if(!isset($_COOKIE["user"])) {
8. echo "Sorry, cookie is not found!";
9. } else {
10. echo "<br/>Cookie Value: " . $_COOKIE["user"];
11. }
12. ?>
13. </body>
14. </html>
Output:
Sorry, cookie is not found!
Firstly cookie is not set. But, if you refresh the page, you will see cookie is set now.
Output:
Cookie Value: Sonoo
PHP Delete Cookie
If you set the expiration date in past, cookie will be deleted.
File: cookie1.php
1. <?php
2. setcookie ("CookieName", "", time() -
3600);// set the expiration date to one hour ago
3. ?>
PHP Session
PHP session is used to store and pass information from one page to another temporarily (until
user close the website).
PHP session technique is widely used in shopping websites where we need to store and pass
cart information e.g. username, product code, product name, product price etc from one page
to another.
PHP session creates unique user id for each browser to recognize the user and avoid conflict
between multiple browsers.

134
PHP session_start() function
PHP session_start() function is used to start the session. It starts a new or resumes existing
session. It returns existing session if session is created already. If session is not available, it
creates and returns new session.
Syntax
1. bool session_start ( void )
Example
1. session_start();
PHP $_SESSION
PHP $_SESSION is an associative array that contains all session variables. It is used to set
and get session variable values.
Example: Store information

1. $_SESSION["user"] = "Sachin";
Example: Get information
1. echo $_SESSION["user"];
PHP Session Example
File: session1.php
1. <?php
2. session_start();
3. ?>
4. <html>
5. <body>
6. <?php

135
7. $_SESSION["user"] = "Sachin";
8. echo "Session information are set successfully.<br/>";
9. ?>
10. <a href="session2.php">Visit next page</a>
11. </body>
12. </html>
File: session2.php
1. <?php
2. session_start();
3. ?>
4. <html>
5. <body>
6. <?php
7. echo "User is: ".$_SESSION["user"];
8. ?>
9. </body>
10. </html>
PHP Session Counter Example
File: sessioncounter.php
1. <?php
2. session_start();
3.
4. if (!isset($_SESSION['counter'])) {
5. $_SESSION['counter'] = 1;
6. } else {
7. $_SESSION['counter']++;
8. }
9. echo ("Page Views: ".$_SESSION['counter']);
10. ?>
PHP Destroying Session
PHP session_destroy() function is used to destroy all session variables completely.
File: session3.php

136
1. <?php
2. session_start();
3. session_destroy();
4. ?>

PHP Form Handling


We can create and use forms in PHP. To get form data, we need to use PHP superglobals
$_GET and $_POST.
The form request may be get or post. To retrieve data from get request, we need to use
$_GET, for post request $_POST.
PHP Get Form
Get request is the default form request. The data passed through get request is visible on the
URL browser so it is not secured. You can send limited amount of data through get request.
Let's see a simple example to receive data from get request in PHP.
File: form1.html
1. <form action="welcome.php" method="get">
2. Name: <input type="text" name="name"/>
3. <input type="submit" value="visit"/>
4. </form>
File: welcome.php
1. <?php
2. $name=$_GET["name"];//receiving name field value in $name variable
3. echo "Welcome, $name";
4. ?>
PHP Post Form
Post request is widely used to submit form that have large amount of data such as file upload,
image upload, login form, registration form etc.
The data passed through post request is not visible on the URL browser so it is secured. You
can send large amount of data through post request.
Let's see a simple example to receive data from post request in PHP.

File: form1.html
1. <form action="login.php" method="post">
2. <table>

137
3. <tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>
4. <tr><td>Password:</td><td> <input type="password" name="password"/></td></tr>

5. <tr><td colspan="2"><input type="submit" value="login"/> </td></tr>


6. </table>
7. </form>
File: login.php
1. <?php
2. $name=$_POST["name"];//receiving name field value in $name variable
3. $password=$_POST["password"];//receiving password field value in $password varia
ble
4.
5. echo "Welcome: $name, your password is: $password";
6. ?>
Output:

138
PHP Mail
PHP mail() function is used to send email in PHP. You can send text message, html message
and attachment with message using PHP mail() function.
PHP mail() function
Syntax
1. bool mail ( string $to , string $subject , string $message [, string $additional_headers [
, string $additional_parameters ]] )
$to: specifies receiver or receivers of the mail. The receiver must be specified one of the
following forms.
o [email protected]
o [email protected], [email protected]
o User <[email protected]>
o User <[email protected]>, Another User <[email protected]>
$subject: represents subject of the mail.
$message: represents message of the mail to be sent.
Note: Each line of the message should be separated with a CRLF ( \r\n ) and lines should not
be larger than 70 characters.
$additional_headers (optional): specifies the additional headers such as From, CC, BCC
etc. Extra additional headers should also be separated with CRLF ( \r\n ).

PHP Mail Example


File: mailer.php
1. <?php
2. ini_set("sendmail_from", "[email protected]");
3. $to = "[email protected]";//change receiver address
4. $subject = "This is subject";
5. $message = "This is simple text message.";
6. $header = "From:[email protected] \r\n";
7.
8. $result = mail ($to,$subject,$message,$header);
9.
10. if( $result == true ){
11. echo "Message sent successfully...";
12. }else{

139
13. echo "Sorry, unable to send mail...";
14. }
15. ?>
If you run this code on the live server, it will send an email to the specified receiver.

PHP Mail: Send HTML Message


To send HTML message, you need to mention Content-type text/html in the message header.
1. <?php
2. $to = "[email protected]";//change receiver address
3. $subject = "This is subject";
4. $message = "<h1>This is HTML heading</h1>";
5.
6. $header = "From:[email protected] \r\n";
7. $header .= "MIME-Version: 1.0 \r\n";
8. $header .= "Content-type: text/html;charset=UTF-8 \r\n";
9.
10. $result = mail ($to,$subject,$message,$header);
11.
12. if( $result == true ){
13. echo "Message sent successfully...";
14. }else{
15. echo "Sorry, unable to send mail...";
16. }
17. ?>

PHP Mail: Send Mail with Attachment


To send message with attachment, you need to mention many header information which is
used in the example given below.
1. <?php
2. $to = "[email protected]";
3. $subject = "This is subject";

140
4. $message = "This is a text message.";
5. # Open a file
6. $file = fopen("/tmp/test.txt", "r" );//change your file location
7. if( $file == false )
8. {
9. echo "Error in opening file";
10. exit();
11. }
12. # Read the file into a variable
13. $size = filesize("/tmp/test.txt");
14. $content = fread( $file, $size);
15.
16. # encode the data for safe transit
17. # and insert \r\n after every 76 chars.
18. $encoded_content = chunk_split( base64_encode($content));
19.
20. # Get a random 32 bit number using time() as seed.
21. $num = md5( time() );
22.
23. # Define the main headers.
24. $header = "From:[email protected]\r\n";
25. $header .= "MIME-Version: 1.0\r\n";
26. $header .= "Content-Type: multipart/mixed; ";
27. $header .= "boundary=$num\r\n";
28. $header .= "--$num\r\n";
29.
30. # Define the message section
31. $header .= "Content-Type: text/plain\r\n";
32. $header .= "Content-Transfer-Encoding:8bit\r\n\n";
33. $header .= "$message\r\n";
34. $header .= "--$num\r\n";
35.

141
36. # Define the attachment section
37. $header .= "Content-Type: multipart/mixed; ";
38. $header .= "name=\"test.txt\"\r\n";
39. $header .= "Content-Transfer-Encoding:base64\r\n";
40. $header .= "Content-Disposition:attachment; ";
41. $header .= "filename=\"test.txt\"\r\n\n";
42. $header .= "$encoded_content\r\n";
43. $header .= "--$num--";
44.
45. # Send email now
46. $result = mail ( $to, $subject, "", $header );
47. if( $result == true ){
48. echo "Message sent successfully...";
49. }else{
50. echo "Sorry, unable to send mail...";
51. }
52. ?>
Database Connectivity
PHP MySQL Connect
Since PHP 5.5, mysql_connect() extension is deprecated. Now it is recommended to use one
of the 2 alternatives.
o mysqli_connect()
o PDO::__construct()

PHP mysqli_connect()
PHP mysqli_connect() function is used to connect with MySQL database. It
returns resource if connection is established or null.
Syntax
1. resource mysqli_connect (server, username, password)
PHP mysqli_close()
PHP mysqli_close() function is used to disconnect with MySQL database. It returns true if
connection is closed or false.
Syntax

142
1. bool mysqli_close(resource $resource_link)
PHP MySQL Connect Example
Example
1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $conn = mysqli_connect($host, $user, $pass);
6. if(! $conn )
7. {
8. die('Could not connect: ' . mysqli_error());
9. }
10. echo 'Connected successfully';
11. mysqli_close($conn);
12. ?>
Output:
Connected successfully

PHP MySQL Create Database


Since PHP 4.3, mysql_create_db() function is deprecated. Now it is recommended to use
one of the 2 alternatives.
o mysqli_query()
o PDO::__query()
PHP MySQLi Create Database Example
Example
1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $conn = mysqli_connect($host, $user, $pass);
6. if(! $conn )
7. {

143
8. die('Could not connect: ' . mysqli_connect_error());
9. }
10. echo 'Connected successfully<br/>';
11.
12. $sql = 'CREATE Database mydb';
13. if(mysqli_query( $conn,$sql)){
14. echo "Database mydb created successfully.";
15. }else{
16. echo "Sorry, database creation failed ".mysqli_error($conn);
17. }
18. mysqli_close($conn);
19. ?>
Output:
Connected successfully
Database mydb created successfully.
PHP MySQL Create Table
PHP mysql_query() function is used to create table. Since PHP 5.5, mysql_query() function
is deprecated. Now it is recommended to use one of the 2 alternatives.
o mysqli_query()
o PDO::__query()
PHP MySQLi Create Table Example
Example
1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6.
7. $conn = mysqli_connect($host, $user, $pass,$dbname);
8. if(!$conn){
9. die('Could not connect: '.mysqli_connect_error());
10. }

144
11. echo 'Connected successfully<br/>';
12.
13. $sql = "create table emp5(id INT AUTO_INCREMENT,name VARCHAR(20) NOT
NULL,
14. emp_salary INT NOT NULL,primary key (id))";
15. if(mysqli_query($conn, $sql)){
16. echo "Table emp5 created successfully";
17. }else{
18. echo "Could not create table: ". mysqli_error($conn);
19. }
20.
21. mysqli_close($conn);
22. ?>
Output:
Connected successfully
Table emp5 created successfully
PHP MySQL Insert Record
PHP mysql_query() function is used to insert record in a table. Since PHP
5.5, mysql_query() function is deprecated. Now it is recommended to use one of the 2
alternatives.
o mysqli_query()
o PDO::__query()
PHP MySQLi Insert Record Example
Example
1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6.
7. $conn = mysqli_connect($host, $user, $pass,$dbname);
8. if(!$conn){
9. die('Could not connect: '.mysqli_connect_error());

145
10. }
11. echo 'Connected successfully<br/>';
12.
13. $sql = 'INSERT INTO emp4(name,salary) VALUES ("sonoo", 9000)';
14. if(mysqli_query($conn, $sql)){
15. echo "Record inserted successfully";
16. }else{
17. echo "Could not insert record: ". mysqli_error($conn);
18. }
19.
20. mysqli_close($conn);
21. ?>
Output:
Connected successfully
Record inserted successfully
PHP MySQL Update Record
PHP mysql_query() function is used to update record in a table. Since PHP
5.5, mysql_query() function is deprecated. Now it is recommended to use one of the 2
alternatives.
o mysqli_query()
o PDO::__query()
PHP MySQLi Update Record Example
Example
1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6.
7. $conn = mysqli_connect($host, $user, $pass,$dbname);
8. if(!$conn){
9. die('Could not connect: '.mysqli_connect_error());
10. }

146
11. echo 'Connected successfully<br/>';
12.
13. $id=2;
14. $name="Rahul";
15. $salary=80000;
16. $sql = "update emp4 set name=\"$name\", salary=$salary where id=$id";
17. if(mysqli_query($conn, $sql)){
18. echo "Record updated successfully";
19. }else{
20. echo "Could not update record: ". mysqli_error($conn);
21. }
22.
23. mysqli_close($conn);
24. ?>
Output:
Connected successfully
Record updated successfully
PHP MySQL Delete Record
PHP mysql_query() function is used to delete record in a table. Since PHP
5.5, mysql_query() function is deprecated. Now it is recommended to use one of the 2
alternatives.
o mysqli_query()
o PDO::__query()
PHP MySQLi Delete Record Example
Example
1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $dbname = 'test';
6.
7. $conn = mysqli_connect($host, $user, $pass,$dbname);
8. if(!$conn){

147
9. die('Could not connect: '.mysqli_connect_error());
10. }
11. echo 'Connected successfully<br/>';
12.
13. $id=2;
14. $sql = "delete from emp4 where id=$id";
15. if(mysqli_query($conn, $sql)){
16. echo "Record deleted successfully";
17. }else{
18. echo "Could not deleted record: ". mysqli_error($conn);
19. }
20.
21. mysqli_close($conn);
22. ?>
Output:
Connected successfully
Record deleted successfully

148

You might also like