Professional Documents
Culture Documents
Unit 3 Web
Unit 3 Web
SERVER-SIDE
DEVELOPEMNT AND
PHP
What is Server-Side Development?
• Client side refers to the part of the web • Server side refers to the part of the web
application that runs on the user’s application that runs on the server, such as
device, such as a web browser. a database or a web server.
• Client side code is usually written in • Server side code is usually written in
languages like HTML, CSS, and languages like PHP, Python, or Java, which
JavaScript, which are interpreted by the are executed by the server.
browser.
• Client side code is responsible for • Server side code is responsible for
creating the user interface, such as the processing the data, such as validating,
layout, design, and interactivity of a storing, or retrieving it from a database.
web page.
Server Side v/s Client Side
What are Servers?
• Servers are powerful computers or software programs that provide resources,
services, or functionality to other computers, devices, or programs, known as
clients.
• Servers play a crucial role in facilitating communication, data storage,
processing, and access to various resources.
• Web servers are computers or software programs that store websites, web
applications, and web content and deliver them to clients upon request.
Popular web servers include Apache, Nginx, Microsoft IIS, and others.
• Servers form the backbone of computer networks and the internet, enabling
the exchange of information, resources, and services between various
devices and systems.
Responsibilities of Servers
• Hosting Website Files: Web servers store website files, including HTML, CSS, JavaScript, images, videos,
and other resources that make up a website. When a user requests a webpage, the web server retrieves the
necessary files and delivers them to the user's browser for display.
• Processing Client Requests: Web servers receive and process incoming requests from client browsers or
applications. They interpret these requests, determine the appropriate response (such as fetching a webpage,
executing server-side code, or retrieving data from a database), and send the response back to the client.
• Handling HTTP Requests and Responses: Web servers communicate using the Hypertext Transfer Protocol
(HTTP). They handle incoming HTTP requests from clients and generate appropriate HTTP responses,
including status codes, headers, and content, to fulfill the client's request.
• Executing Server-Side Code: Web servers execute server-side code, such as PHP, Python, Ruby, Node.js, or
Java, to generate dynamic content on websites or web applications. Server-side code can interact with
databases, perform calculations, process form data, and customize content based on user input or other
parameters.
5. Database Connectivity: Web servers often interact with databases to retrieve and store data required by websites
and web applications. They establish connections to database servers, execute queries, process results, and
incorporate data into dynamic web pages.
6. Content Management: Web servers can serve static content directly from files while also handling dynamic
content generation through server-side scripting languages. They manage the delivery of multimedia content,
downloadable files, streaming media, and other resources to users.
7. Integration with Third-Party Services: Web servers can integrate with external APIs, services, or platforms to
extend functionality, access external data sources, perform additional processing, or interact with external systems
as part of web application workflows.
8. Error Handling and Page Redirects: Web servers manage error responses, such as 404 (Not Found) or 500
(Internal Server Error), and can be configured to redirect users to custom error pages or alternative content when
errors occur.
And many more....
Introduction to PHP
What is PHP?
• PHP, which stands for Hypertext Preprocessor, is a powerful server-side scripting
language designed for web development.
• It is one of the most widely used programming languages for creating dynamic web pages
and applications.
• PHP is an open-source language that is embedded within HTML code and can
communicate with databases such as MySQL, making it an essential tool for building
interactive and dynamic websites.
• PHP was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1994
and has since evolved into a robust language supported by a large community of
developers worldwide.
• Its syntax is similar to C, Java, and Perl, making it relatively easy to learn for those
familiar with these languages.
Basic Syntax of PHP
• Comments: In php, comments are those lines which are ignored by the machine.
⚬ Single Line Comments: the single-line comments begin with // comments.
⚬ Multi Line Comments: Multiline comments begin with /* and ends with */.
Example:
1. <?php // echo “hello world”; ?>
2. <?php
echo "Hello Geeks";
/* It will print the
message "Hello geeks" */ ?>
Variables in PHP: Variables in a program are used to store some values or data that can be used
later in a program.
• PHP variables always start with dollar sign ($).
Example: $num = 20; OR $name = “Shubham”;
Rules for declaring variables in PHP:
• Any variables declared in PHP must begin with a dollar sign ($), followed by the variable
name.
• variable names in PHP names must start with a letter or underscore and no numbers.
• PHP variables are case-sensitive, i.e., $sum and $SUM are treated differently.
• PHP is a loosely typed language, and we do not require to declare the data types of
variables, rather PHP assumes it automatically by analyzing the values.
Scope of Variables: Scope of a variable is defined as its extent in a program within which it can be
accessed, i.e. the scope of a variable is the portion of the program within which it is visible or can be
accessed.
Depending on the scopes, PHP has three variable scopes:
• Local variables: The variables declared within a function are called local variables to that
function and have their scope only in that particular function.
• Global variables: The variables declared outside a function are called global variables and
can be accessed directly outside a function. To get access within a function we need to use
the “global” keyword before the variable to refer to the global variable.
• Static variable: It is the characteristic of PHP to delete the variable, once it completes its
execution and the memory is freed. But sometimes we need to store the variables even after
the completion of function execution. To do this we use the static keywords and the
variables are then called static variables.
Data Types in PHP: Data Types define the type of data a variable can store. PHP allows
eight different types of data types.
The predefined data types are:
• Boolean
• Integer
• Double
• String
The user-defined (compound) data types are:
• Array
• Objects
The special data types are:
• NULL
• resource
Conditionals in PHP: PHP allows us to perform actions based on some type of
conditions that may be logical or comparative.
• PHP provides us with two conditional statements: if-else statement and switch
statement
If Else example:
<?php
$x = 12; OUTPUT:
The number is positive
if ($x > 0) {
echo "The number is positive";
}
?>
Switch in PHP: The switch statement is similar to the series of if-else statements. The switch
statement performs in various cases i.e. it has various cases to which it matches the condition
and appropriately executes a particular case block.
Eample Code:
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
Loops in PHP: Loop in PHP is used to execute a statement or a block of statements,
multiple times until and unless a specific condition is met.
• for loop: This loop is used when you know how many times you want to repeat a block of
code. It has three parts: the initialization, the condition, and the update.
For example:
For example:
For example:
?>
Arrays in PHP
Arrays in PHP is a type of data structure that allows us to store multiple elements of similar
data type under a single variable thereby saving us the effort of creating a different variable
for every data. The arrays are helpful to create a list of elements of similar types, which can be
accessed using their index or key.
=>An array is created using an array() function in PHP.
There are basically three types of arrays in PHP:
• Indexed or Numeric Arrays: An array with a numeric index where values are stored
linearly.
• Associative Arrays: An array with a string index where instead of linear storage, each
value can be assigned a specific key.
• Multidimensional Arrays: An array which contains single or multiple array within it and
can be accessed via multiple indices.
Examples of Type of Arrays
• Indexed Arrays :
// This is an indexed array of fruits
These arrays are $fruits = array("apple", "banana", "orange"); OUTPUT:
accessed through
apple
the indices of the echo $fruits[0]; // apple banana
elements echo $fruits[1]; // banana orange
echo $fruits[2]; // orange
<?php
OUTPUT:
function proGeek($num1, $num2, $num3)
{
The product is 30
$product = $num1 * $num2 * $num3;
echo "The product is $product";
}
?>
Arrow Functions
Arrow functions, also known as “short closures”, is a new feature introduced in PHP 7.4 that
provides a more concise syntax for defining anonymous functions. Arrow functions allow
you to define a function in a single line of code, making your code more readable and easier
to maintain.
2. Using get_browser() function: the get_browser () function, which returns an array of information
about the browser’s capabilities, such as the platform, the browser name, the version, the support for
JavaScript, etc.
Example: <?php $browser = get_browser(null, true);
echo $browser; ?>
Browser Control: Browser control in PHP refers to the ability to manipulate the web browser of
the user who visits a PHP web page.
There are many different ways to control the browser through php scripts such as:
• Using JavaScript to manipulate the browser’s DOM, events, and behavior. You can use the
echo () function to output JavaScript code in your PHP script, or use the <script> tag to
embed JavaScript code in your HTML output.
• Using HTML5 APIs to access the browser’s features, such as geolocation, local storage,
media devices, etc. You can use the <script> tag to embed JavaScript code that uses these
APIs in your HTML output.
• Using CSS to style and animate the browser’s elements, such as fonts, colors, transitions,
etc. You can use the echo () function to output CSS code in your PHP script, or use the
<style> tag to embed CSS code in your HTML output.
Handling HTTP Requests
The Hypertext Transfer Protocol (HTTP) is designed to enable communications between clients
and servers. HTTP works as a request-response protocol between a client and server. A web
browser may be the client, and an application on a computer that hosts a website may be the
server.
There are 2 HTTP request methods:
• GET: Requests data from a specified resource.
• POST: Submits data to be processed to a specified resource.
GET Method: In the GET method, the data is sent as URL parameters that are usually strings of name
and value pairs separated by ampersands (&).
• Example: http://www.example.com/action.php?name=Sam&weight=55
• Here, the bold parts in the URL denote the GET parameters and the italic parts denote the value of
those parameters. More than one parameter=value can be embedded in the URL by concatenating
with ampersands (&).
POST Method: In the POST method, the data is sent to the server as a package in a separate
communication with the processing script. Data sent through the POST method will not be
visible in the URL.
Example:
The query string (name/weight) is sent in the HTTP message body of a POST request.
Strings in PHP: Strings can be seen as a stream of characters.
• Just like any other language, Strings in PHP are surrounded by either double
quotation marks, or single quotation marks.
Example: echo "Hello";
• Unlike other data types like integers, doubles, etc. Strings do not have any fixed
limits or ranges. It can extend to any length as long as it is within the quotes.
• Strings within a single quote ignore the special characters, but double-quoted strings
recognize the special characters and treat them differently.
• The string starting with a dollar sign(“$”) are treated as variables and are replaced
with the content of the variables.
• There are many in-built methods/functions to manipulate strings.
Built-In String Functions
• strlen() function: This function is used to find the length of a string. This function accepts the
string as an argument and returns the length or number of characters in the string. output
Example: echo strlen("Hello world!"); Output: 12
2. strrev() function: This function is used to reverse a string. This function accepts a string as
an argument and returns its reversed string.
Example:
3. str_replace() function: This function takes three strings as arguments. The third argument is the
original string and the first argument is replaced by the second one.
Example:
echo str_replace("World", "Dolly", “Hello World”);
Output: Hello Dolly
4. trim() function: This function allows us to remove whitespaces or strings from both sides of a
string.
Eample : $x = " Hello World! "; OUTPUT: HelloWorld!
echo trim($x);
5. explode() function: The PHP explode() function splits a string into an array.
Example:
$x = "Hello World!";
$y = explode(" ", $x);
echo $y;
// output will be in the form of an array
6. substr() function: We can Slice a string in substrings to get a specific part of it
• You can return a range of characters by using the substr() function.
• Specify the start index and the number of characters you want to return.
Example : $x = "Hello World!"; OUTPUT: World
echo substr($x, 6, 5);
Slicing can be done in different ways
• Slice to the end: this will slice the string from given index to the end
Example : $x = "Hello World!";
echo substr($x, 6); OUTPUT: World!
2. Slice from the end: Use negative index to slice from the end of the string
Example: $x = "Hello World!";
echo substr($x, -5, 3); OUTPUT: orl
Note: negative index start from end of string and start from -1 and positive
index start from 0
Concantenation of Strings: It refers to the joining of two or more strings together into one
string.
• Another way is to use the double quotes around the two strings to join:
Example: $x = "Hello";
$y = "World";
$z = "$x $y";
echo $z; OUTPUT: Hello World
Form Processing
• Form processing contains a set of controls through which the client and server can
communicate and share information.
• HTML forms are used to send the user information to the server and returns the result back to
the browser.
• We can validate the data, store it in a database, send an email, or display a result to the user.
• Form Validation: Form validation is done to ensure that the user has provided the relevant
information. Basic validation can be done using HTML elements.
• The PHP superglobals $_GET and $_POST are used to collect form-data.
Processing a form in PHP: We can process from data by html attributes and the important one
are action and method, which specify the URL and the HTTP method for submitting the form,
respectively.
Example of Basic Form Handling
<html>
<body>
Welcome <?php
echo $_POST["name"]; ?>
<br>
Your email address is: <?php echo
$_POST["email"]; ?>
</body>
</html>
HTMl file PHP Script
OUTPUT:
File Handling in PHP
• File handling is an important part of any web application. We often need to open and process
a file for different tasks.
• File handling in PHP is similar as file handling is done by using any programming language
like C.
• PHP has many functions to work with normal files.
Writing to a file: fwrite() – New file can be created or text can be appended to
an existing file using fwrite() function. Arguments for fwrite() function are file
pointer and text that is to written to file. It can contain optional third argument
where length of text to written is specified
Example of writing to a file:
<?php
$file = fopen("demo.txt", 'w');
$text = "Hello world\n";
fwrite($file, $text);
?>
This code creates a file and write to it or appends to a file if already exist.
Setting Cookie In PHP: To set a cookie in PHP, the setcookie() function is used. The setcookie()
function needs to be called prior to any output generated by the script otherwise the cookie will
not be set.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
Parameters: The setcookie() function requires six arguments in general which are:
Deleting a cookie: To delete a cookie, use the setcookie() function with an expiration
date in the past
Session in PHP
A session is a way to store information (in variables) to be used across multiple pages.
Unlike a cookie, the information is not stored on the users computer.
Example: <?php
session_start();
?>
• Storing Session Data: Session data in key-value pairs using the $_SESSION[] superglobal
array.The stored data can be accessed during lifetime of a session.
Example: <?php
session_start();
$_SESSION["Rollnumber"] = "11";
$_SESSION["Name"] = "Ajay"; ?>
• Accessing Session Data: Data stored in sessions can be easily accessed by firstly
calling session_start() and then by passing the corresponding key to the $_SESSION
associative array.
Example:
<?php
session_start();
?>
OUTPUT: The Name of the student is :Ajay
The Roll number of the student is :11
• Destroying Session Data: We can delete Session data through the session_destroy()
function and we can delete certain part of data also using particular data item assoicated
with it .
Example: To destroy the session data for a Example: To destroy the complete
given roll number session data
<?php
<?php
session_start();
session_start();
session_destroy();
if(isset($_SESSION["Name"])){
unset($_SESSION["Rollnumber"]);
?>
}
?>