Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 52

UNIT III

SERVER-SIDE
DEVELOPEMNT AND
PHP
What is Server-Side Development?

Server-side development refers to the process


of creating and maintaining the backend
(server-side) logic of a website, web
application, or software. In server-side
development, the focus is on managing the
server, databases, and application logic that
run on the server to process data, perform
computations, and interact with the client-
side (front end) of the application.
Client Side v/s Server Side

• 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

• PHP can be embedded with HTML.


• PHP files are saved with the “.php”
extension.
• PHP scripts can be written anywhere in
the document within PHP tags along
with normal HTML.
• A PHP script starts with <?php and ends
with ?>

php code example


• Printing data to Browser: the "echo" or “print” statement is used to output data or text to the
browser or the web server.
Example: echo "Hello, World!"; OR print "Hello, world!";

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

PHP supports four types of looping techniques:

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

// This loop prints the numbers from 1 to 10


for ($i = 1; $i <= 10; $i++) {
echo $i . "\n";
}
2. While Loop: This loop is used when you want to repeat a block of code as long as a
condition is true. The condition is checked before the loop body is executed.

For example:

// This loop prints the numbers from 1 to 10


$i = 1;
while ($i <= 10) {
echo $i . "\n";
$i++;
}
3. Do-While Loop: This loop is similar to the while loop, but the condition is checked after
the loop body is executed. This means that the loop body is always executed at least once.

For example:

// This loop prints the numbers from 1 to 10


$i = 1;
do {
echo $i . "\n";
$i++;
} while ($i <= 10);
4. Foreach Loop: This loop is used to iterate over arrays. For every counter of loop, an array
element is assigned and the next counter is shifted to the next element.
For example:

// This loop prints the keys and values of an associative array


<?php
$arr = array (10, 20, 30, 40, 50, 60);
foreach ($arr as $val) {
echo "$val \n";
}

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

2. Associative Arrays : // This is an associative array of students and their marks


They have key value $students = array("Ajay" => 80, "Vijay" => 75, "Sanjay" => 90);
pairs and values can OUTPUT:
be accessed through echo $students["Ajay"]; // 80
80
the key elements echo $students["Vijay"]; // 75
75
echo $students["Sanjay"]; // 90
90
3. MultiDimensional Arrays: They have nested elements inside every element.
// This is a multidimensional array of products and their details
$products = array(
"laptop" => array(
"brand" => "Dell",
"price" => 50000
), OUTPUT:
"mobile" => array(
"brand" => "Samsung", Dell
"price" => 20000
15
),
"tablet" => array(
"brand" => "Apple",
"price" => 30000
)
);
// You can access the values by using multiple indices
echo $products["laptop"]["brand"]; // Dell
echo $products["tablet"]["stock"]; // 15
Functions
• A function is a block of code that performs a specific task and can be reused.
• A function is defined using the function keyword, followed by a name, a list of parameters, and
a body.

• PHP provides us with two major types of functions:


⚬ Built-in functions : PHP provides us with huge collection of built-in library functions.
These functions are already coded and stored in form of functions. To use those we just
need to call them as per our requirement like, var_dump, fopen(), print_r(), gettype() and so
on.
⚬ User Defined Functions : Apart from the built-in functions, PHP allows us to create our
own customised functions called the user-defined functions. Using this we can create our
own packages of code and use it wherever necessary by simply calling it.
Example of a Simple function:

<?php

// function along with three parameters

OUTPUT:
function proGeek($num1, $num2, $num3)
{
The product is 30
$product = $num1 * $num2 * $num3;
echo "The product is $product";
}

// Calling the function


proGeek(2, 3, 5);

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

Syntax: $fn = $fun(x) => some_operations


Example:
<?php
// Declare an array
$arr = [1, 2, 3, 4, 5, 6, 7];

$sum = array_reduce($arr, fn($carry, $item) => $carry + $item);


How Browsers handle PHP?
• PHP is a server-side scripting language, which means that it runs on the web server and not on
the browser. The browser only receives the output of the PHP script, which is usually HTML,
CSS, JavaScript, or other web formats.
• When a browser requests a PHP file from a web server, the web server recognizes the file
extension (.php) and passes the file to the PHP interpreter. The PHP interpreter executes the
PHP code and generates the output, which is then sent back to the web server. The web server
then sends the output to the browser, which renders it as a web page.
• The browser does not need to know or care about the PHP code, as it only sees the final output.
• Browser control and detection refers to the ability to identify and manipulate the web browser
of the user who visits a PHP web page.
• Browser control and detection can be useful for providing browser-specific content, such as
different layouts, styles, or functionalities.
Diagram showing Browser handling PHP
Superglobals in PHP
These are specially-defined array variables in PHP that make it easy for you to get information
about a request or its context. The superglobals are available throughout your script. These
variables can be accessed from any function, class or any file without doing any special task
such as declaring any global variable etc. They are mainly used to store and get information
from one page to another etc in an application.

Below is the list of superglobal variables available in PHP:


• $GLOBALS 8. $_FILES
• $_SERVER 9. $_ENV
• $_REQUEST
• $_GET
• $_POST
• $_SESSION
• $_COOKIE
Browser Detection: Browser detection is the process of identifying and manipulating the web
browser of the user who visits a PHP web page. Browser detection can be useful for providing
browser-specific content, such as different layouts, styles, or functionalities.

There are two methods to detect the browser::


• Using $_SERVER: The $_SERVER superglobal variable, which contains information about the
server and the request, such as the HTTP_USER_AGENT, which gives the browser name and
version.
Example: <?php echo $_SERVER['HTTP_USER_AGENT']; ?>

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:

POST /test/demo_form.php HTTP/1.1


Host: gfs.com
SAM=451&MAT=62

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.

• To concatenate, or combine, two strings you can use the . operator:


Example: $x = "Hello";
$y = "World";
$z = $x . $y;
echo $z; OUTPUT: HelloWorld

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

Opening file in PHP


fopen() – PHP fopen() function is used to open a file. First parameter of fopen() contains name
of the file which is to be opened and second parameter tells about mode in which file needs to
be opene
Example: <?php
$file = fopen(“demo.txt”,'w');
?>
Note: another function readfile() can also be used to open a file
File Modes in PHP
Files can be opened in any of the following modes :
• “w” – Opens a file for write only. If file not exist then new file is created and if file already
exists then contents of file is erased.
• “r” – File is opened for read only.
• “a” – File is opened for write only. File pointer points to end of file. Existing data in file is
preserved.
• “w+” – Opens file for read and write. If file not exist then new file is created and if file
already exists then contents of file is erased.
• “r+” – File is opened for read/write.
• “a+” – File is opened for write/read. File pointer points to end of file. Existing data in file is
preserved. If file is not there then new file is created.
• “x” – New file is created for write only.
Closing a file: fclose() – file is closed using fclose() function.:
Example: <?php
$file = fopen("demo.txt", 'r');
//some code to be executed
fclose($file);
?>

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.

Creating a file: The fopen() function is also used to create a file.


In PHP, a file is created using the same function used to open files.

Example: $myfile = fopen("testfile.txt", "w")


Cookies in Web:
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the
user's computer. Each time the same computer requests a page with a browser, it will send the
cookie too. With PHP, you can both create and retrieve cookie values.

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:

• Name: It is used to set the name of the cookie.


• Value: It is used to set the value of the cookie.
• Expire: It is used to set the expiry timestamp of the cookie after which the cookie can’t be
accessed.
• Path: It is used to specify the path on the server for which the cookie will be available.
• Domain: It is used to specify the domain for which the cookie is available.
• Security: It is used to indicate that the cookie should be sent only if a secure HTTPS connection
exists.

Note: Only Name argument is required.. remaining are optional arguments


Example
Modifying a cookie: To modify a cookie, just set (again) the cookie using the
setcookie() function

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.

What is PHP Session?


When you work with an application, you open it, do some changes, and then you close it. This is
much like a Session. The computer knows who you are. It knows when you start the application
and when you end. But on the internet there is one problem: the web server does not know who
you are or what you do, because the HTTP address doesn't maintain state.
Session variables solve this problem by storing user information on the server to be used across
multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user
closes the browser.
Steps involved in PHP sessions
• Starting a PHP Session: The first step is to start up a session. After a session is started,
session variables can be created to store information. The PHP session_start() function is
used to begin a new session.It also creates a new session ID for the user.

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();

echo 'The Name of the student is :' . $_SESSION["Name"] . '<br>';


echo 'The Roll number of the student is :' . $_SESSION["Rollnumber"] . '<br>';

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

You might also like