UNIT4-Server Side Processing and Scripting
UNIT4-Server Side Processing and Scripting
PHP - Working principle of PHP - PHP Variables - Constants - Operators – Flow Control and Looping
- Arrays - Strings - Functions - File Handling - File Uploading – Email Basics - Email with
attachments - PHP and HTML - Simple PHP scripts - Databases with PHP
➢ PHP stands for Hypertext Preprocessor was introduced by Rasmus Lerdorf in 1994
➢ It is an interpreted language and it does not require a compiler. The language quickly
evolved and was given the name “PHP,” which initially named was “Personal Home
Page.”
PHP can also perform various tasks such as form data processing, database interaction,
session management, and more. It is known for its simplicity, flexibility, and wide adoption
across web development projects.
1. Open Source
2. Cross-Platform Compatibility
• PHP runs on multiple platforms, such as Windows, macOS, Linux, and Unix.
• PHP scripts are executed on the server, and the output (HTML or other formats) is sent
• PHP has a simple syntax that resembles C, making it easy for beginners to learn.
• PHP code can be seamlessly embedded into HTML, enabling developers to add dynamic
6. Database Integration
• PHP supports various databases like MySQL, PostgreSQL, SQLite, MongoDB, and more.
• PHP provides a wide range of built-in libraries for handling tasks such as file
manipulation, image processing, and encryption.
9. Secure
• With proper implementation, PHP can provide secure web applications by using
features like data sanitization, encryption, and secure session handling.
• PHP has an active community that provides resources, tutorials, and solutions to
developers worldwide.
11. Supports Object-Oriented and Procedural Programming
12. Versatile
o Sending emails.
13. Extensibility
• PHP can be extended with custom extensions and plugins, enhancing its functionality.
• PHP supports numerous frameworks, such as Laravel, CodeIgniter, Symfony, and CakePHP,
• PHP supports HTTP, HTTPS, FTP, SMTP, and more, making it ideal for a wide range of
applications.
➢ PHP being a server-side language, the entire workflow is on the server itself. A PHP
interpreter is also installed into the server to check for PHP files. While on the client-side,
the only requirement is a web browser and internet connection.
Let us understand step-by-step how a PHP page works:
Step 2: The server (where PHP software is installed) then checks for the .php file associated with
the request
Step 3: If found, it sends the file to the PHP interpreter (since PHP is an interpreted language), which
checks for requested data into the database.
Step 4: The interpreter then sends back the requested data output as an HTML webpage (since a
browser does not understand .php files).
Step 5: The web server receives the HTML file from the interpreter.
2. After installation, open the XAMPP control panel and start the Apache webserver.
2. PHP Variables & Constants
2.1 PHP Variables
➢ Variables are used to store data or values that can be manipulated or used throughout a
PHP script.
➢ PHP variables are dynamically typed, meaning they can hold values of any data type.
➢ To declare a variable in PHP, use the dollar sign ($) followed by the variable name.
➢ PHP Variables are Case-Sensitive, so fruit and Fruit are considered different variables.
Variables Naming rules:
1. Variables in PHP Must Begin with a Dollar sign ($) Followed by a Letter or an Underscore:
In PHP all the variable names must begin with a dollar sign followed by a letter or an
underscore, they cannot begin with a number or any other special character. Let us see an
example:
$Firstname = "Yash"; // valid variable name
$_surname = "Agarwal"; // valid variable name
$151020name = 25; // invalid variable name
2. Variables in PHP can be Assigned values of any Data Type Including Integer, Float, String,
Array, Object, Boolean, and Null:
In PHP we can assign values if any data type which can include integer, float, string, array,
object, boolean, and null. Let us see an example:
$num = 10; // integer
$value = 25.50; // float
$firstname = "John Doe"; // string
$type = array("Red", "Green", "Blue"); // Array
$isArmstrong = true; // boolean
$mango = null; // null
3. Variable Names in PHP are Case-Sensitive :
In PHP the variable names are case sensitive hence if we write $yash and $Yash both of them
are considered as two different variables.
<?php
$color="yellow";
echo "The color of the house is ". $color. "<br>";
echo "The color of the house is". $COLOR. "<br>";
echo "The color of the house is ". $coLOR. "<br>";
?>
Scope of Variables in PHP:
➢ In PHP, variable scope refers to the range in which a variable can be accessed and manipulated
within a PHP script.
➢ There are three main types of variable scopes in PHP:
o global,
o local,
o static.
➢ Each type of scope has its own rules regarding where and how variables can be accessed.
i) Global Variable:
A variable declared outside a function or class has a global scope, meaning it can be accessed
from anywhere in the script. It can be accessed both inside and outside functions.
Example:
<?php
$a = "Yash"; // global scope
function printa(){
echo $a;
}
printa();
?>
Output:
Yash
Example:
<?php
function print(){
$a = "Yash"; // local scope
echo $a;
}
printa();
echo $a;
?>
Output:
Yash
variable not defined
iii) Static Scope:
A variable declared inside the function with the static keyword has a static scope. It means that
the variable retains its value between function calls. It can only be accessed inside the function
where it was declared.
Example:
<?php
function zero(){
static $z = 0; // static scope
$z++;
echo $z;
}
zero();
zero();
zero();
?>
Output:
1
2
3
Example:
<?php
print “<h2>PHP Works </h2>”;
print “Hello World”;
?>
Example:
<?php
echo “Hello”;
?>
• Constants are used to store values that remain constant and cannot be modified during the
execution of a script.
• Constants are automatically global and can be accessed from anywhere within the script
without the need for any special keywords or syntax.
• Constants follow naming conventions in PHP, typically using uppercase letters with
underscores for multiple words, making them easily distinguishable from variables.
• Constants are commonly used for storing configuration settings, such as database credentials or
application-specific values, providing a centralized and consistent approach to managing these
settings.
• Constants enhance code readability by using meaningful names for important values, making
the code easier to understand and maintain. They also promote code consistency by ensuring
that values are consistently used throughout the codebase.
• Constants are determined at compile-time, making them available and ready to use as soon as
the script starts running.
To create a constant in PHP, use either the define() function or the const keyword.
For example:
define('GREETING', 'Hello, World!');
echo GREETING;
For example:
const GREETING = 'Hello, World!';
echo GREETING; // Output: Hello, World!
3. Operators in PHP
➢ One of the fundamental aspects of PHP programming is the use of operators. Operators are
symbols or keywords that perform specific operations on variables and values.
➢ In PHP, operators are used to perform arithmetic, comparison, assignment, logical, and bitwise
operations.
PHP Arithmetic Operators:
In PHP, Arithmetic operators are used to perform mathematical operations on numeric values.
These operators include addition (+), subtraction (-), multiplication (*), division (/), and modulus (%).
The modulus operator returns the remainder of a division operation.
1. Union Operator
The union operator is used to merge two or more arrays together. It is represented by the + operator in
PHP.
Example:
$array1 = array("a", "b");
$array2 = array("o", "p");
$mergedArray = $array1 + $array2;
print_r($mergedArray);
Output:
Array ( [0] => a [1] => b [2] => o [3] => p )
In the above example, the + operator is used to merge the array1and array2 arrays into a single array
called $mergedArray.
2. Equality Operator
The equality operator is used to check if two arrays have the same values, ignoring their keys. It is
represented by the == operator in PHP.
Example:
$array1 = array("a", "b");
$array2 = array("b", "a");
if ($array1 == $array2) {
echo "The arrays are equal.";
} else {
echo "The arrays are not equal.";} Output: The arrays are equal.
3. Identity Operator
The identity operator is used to check if two arrays are identical, including their keys and values. It is
represented by the === operator in PHP.
Example Program:
$array1 = array("a", "b");
$array2 = array("b", "a");
if ($array1 === $array2) {
echo "The arrays are identical.";
} else {
echo "The arrays are not identical.";
}
Output:
The arrays are not identical.
5. Arrays
➢ In PHP, an array is a data structure that can hold multiple values of different data types in a
single variable. It allows for efficient storage and retrieval of data using keys or indices. Arrays
can be created and manipulated using built-in functions and operators in PHP.
Create an Array in PHP
<?php
// Create an array with three elements
$fruits = ['apple', 'banana', 'orange'];
// Display the array
print_r($fruits);
?>
Output:
Array
(
[0] => apple
[1] => banana
[2] => orange
)
Advantages of PHP Array
• Flexibility:
Arrays can store a mixture of different data types, including strings, numbers, and objects,
making them a versatile tool for organizing and manipulating data.
• Efficient data storage:
Arrays can store large amounts of data in a relatively small space, and they can be accessed
quickly and easily using built-in PHP functions.
• Easy to use:
PHP provides a wide range of functions for working with arrays, including functions for
adding, deleting, and searching for elements. This makes it easy to manipulate array data and
perform common operations quickly and efficiently.
• Iteration:
Arrays can be easily iterated over using PHP's foreach loop, making it easy to loop through and
process large sets of data.
• Customizable sorting: PHP provides a variety of built-in functions for sorting arrays,
including sort(), asort(), and ksort(), which allow you to customize the way your data is sorted
based on your needs.
• Support for multidimensional arrays:
PHP allows you to create multidimensional arrays, which can store data in a hierarchical
format, making it easier to organize and work with complex data sets.
3. Multidimensional Arrays
Multidimensional arrays in PHP are arrays that contain other arrays as elements. They are
useful for storing complex data structures, such as tables or matrices, and allow us to access
elements using multiple keys, which represent the indices of the nested arrays.
Example
$students = [['Yash', 20, 'A'], ['Srinjoy', 22, 'B'], ['Swagata', 21, 'C']];
Output: 20
4. Sparse Arrays
Sparse arrays are arrays that have gaps or missing keys between the existing elements. They are
not commonly used in PHP but can be useful for storing large amounts of data with many
empty elements.
For example:
$sparse_array = [1 => 'one', 3 => 'three', 5 => 'five'];
5.Dynamic Arrays
Dynamic arrays are arrays that can change size dynamically at runtime. In PHP, all arrays are
dynamic by default, which means we can add or remove elements as needed using built-in
functions and operators. For example:
6. Strings in PHP
Strings in PHP:
• A string is a sequence of characters that can be used to represent text data.
• PHP provides many built-in functions for working with strings, such
as strlen(), substr(), str_replace(), and more.
• Strings can be concatenated using the "." operator or interpolated into other strings using
double quotes.
• PHP also supports various string manipulation functions, such as trimming whitespace or
converting cases.
i. strlen() function in PHP: The strlen() function in PHP is used to determine the length of a string.
$str = "Hello, world!";
$length = strlen($str);
echo "The length of the string is: " . $length;
ii. str_word_count() Function in PHP: In PHP, the str_word_count() function is used to count the
number of words in a string. It takes a string as its input and returns an integer value representing the
number of words in the string.
$string = "This is a sample string";
$word_count = str_word_count($string);
echo "The number of words in the string is: " . $word_count;
iii. strrev() Function in PHP: In PHP, the strrev() function is used to reverse a string. Here is an
example of how to use the strrev() function
$string = "Hello World!";
$reversedString = strrev($string);
echo $reversedString;
iv. strpos() function in PHP:
The strpos() function in PHP is used to find the position of the first occurrence of a substring within a
string. Here is an example of how to use the strpos() function:
$string = "The quick brown fox jumps over the lazy dog.";
$position = strpos($string, "fox");
echo $position;
v. str_replace() Function in PHP:
str_replace() is a PHP function used to replace all occurrences of a substring in a string with another
substring. It takes three parameters: the substring to search for, the substring to replace it with, and the
string to search in.
$string = "The quick brown fox jumped over the lazy dog.";
$newString = str_replace("fox", "cat", $string);
echo $newString;
Output:
The quick brown cat jumped over the lazy dog.
vi. explode() Function in PHP:
In PHP, the explode() function is used to split a string into an array based on a specified
delimiter.
Example:
$string = "apple, banana, orange, mango";
$fruits = explode(", ", $string);
print_r($fruits);
Output:
Array
(
[0] => apple
[1] => banana
[2] => orange
[3] => mango
)
In this example, we first define a string containing a list of fruits separated by a comma and a
space. We then use explode() to split the string into an array using the comma and space as the
delimiter. The resulting array contains the individual fruits as elements.
vii. strtolower() Function in PHP:
strtolower() is a PHP function that is used to convert a string to lowercase letters. It takes one
parameter, which is the string to be converted and returns the converted string.
Example:
$string = "This is a STRING";
$lowercase_string = strtolower($string);
echo $lowercase_string;
Output:
this is a string
viii. strtoupper() Function in PHP:
strtoupper() is a built-in PHP function that is used to convert a string to uppercase letters.
$str = "hello world";
$str_upper = strtoupper($str);
echo $str_upper;
Output:
HELLO WORLD
In the example above, the strtoupper() function is applied to the "hello world" string. The resulting
string is then assigned to a new variable $str_upper. Finally, the uppercase string is displayed using the
echo statement.
ix. substr() Function in PHP:
The substr() function in PHP is used to extract a portion of a string.
Example:
$string = "Hello, world!";
$substring = substr($string, 0, 5);
echo $substring; // Output: Hello
Output: Hello
In this example, we pass the $string variable and starting position of 0 to the substr() function.
We also specify the length of the substring we want to extract as 5. This will extract the
first 5 characters of the $string variable and store it in the $substring variable. Finally, we print the
value of the $substring using the echo statement.
7. Functions in PHP
Functions in PHP:
➢ In PHP, a function is a block of code designed to perform a specific task. Functions can be
defined and called within PHP scripts.
➢ In PHP, functions are defined using the function keyword, followed by the function name and a
pair of parentheses. Also specify parameters within the parantheses to accept input values
➢ The function body consists of a block of code enclosed within curly braces, which contains the
instructions to be executed when the function is called.
Syntax for defining a Function:
function functionName($parameter1, $parameter2, ...) {
// Function body: Code to be executed
return $value; // Optional, returns a value to the caller
}
1. function: The keyword used to declare a function.
2. functionName: The name of the function. Function names should start with a letter or
underscore and can contain letters, numbers, or underscores.
3. Parameters: Optional variables passed to the function for processing.
4. Return: The optional return statement is used to send a value back to the calling code.
Advantages of Functions:
1.Promotes Code reusability
2. Saves development time and effort
3.Modularity
4.Code readability
Types of Functions:
1. Built-in function
2. User defined function
Built-in function
• String Functions: PHP offers numerous string manipulation functions, such as
strlen() for getting the length of a string,
substr() for extracting substrings,
str_replace() for replacing text within a string,
strtolower() and strtoupper() for converting case, and
implode() for joining array elements into a string.
• Mathematical Functions: PHP provides a variety of mathematical functions, including basic
arithmetic operations like abs() for absolute value, sqrt() for square root, pow() for
exponentiation, round() for rounding numbers, and rand() for generating random numbers.
• Array Functions: PHP offers a rich set of functions for working with arrays. Examples include
count() for getting the number of elements in an array, array_push() and array_pop() for adding
and removing elements from an array, array_merge() for merging arrays, and array_filter() for
filtering array elements based on a callback function.
• Date and Time Functions: PHP provides functions to work with dates and times, such as
date() for formatting dates, time() for getting the current Unix timestamp, strtotime() for
converting textual date representations into timestamps, and functions for manipulating and
comparing dates, like strtotime() and date_diff().
• File System Functions: PHP offers functions for interacting with the file system, such as
file_exists() for checking if a file exists, file_get_contents() for reading file
contents, file_put_contents() for writing data to a file, and unlink() for deleting files.
• Database Functions: PHP provides functions for connecting to databases, executing queries,
and retrieving results. Popular ones include mysqli_connect() for establishing a connection to a
MySQL database, mysqli_query() for executing SQL queries, and mysqli_fetch_assoc() for
fetching rows from query results.
User-defined function
A user-defined function in PHP is a custom function created by the programmer to perform
specific tasks that are not provided by PHP's built-in functions. These functions are defined using the
function keyword and can include optional parameters and a return value.
Syntax of a User defined function
function functionName($parameter1, $parameter2, ...) {
// Code to be executed
return $value; // Optional
}
Any function created or defined in PHP will be of one of the below mentioned type
- A function without parameters and without return value
- A function with parameters and without return value
- A function without parameters and with return value
- A function with parameters and with return value
How It Works
1. User selects a file in the HTML form and clicks "Upload."
2. Form submits the file to upload.php using the POST method.
3. PHP script processes the file:
o $_FILES["file"] gives access to the uploaded file.
o move_uploaded_file() moves the file from the temporary location to the uploads
directory.
4. Result displayed:
o If the file is successfully uploaded, a success message is shown.
o If an error occurs, an error message is displayed.
9.Email Basics-Email with attachment
PHP provides the mail() function for sending emails. This function can send plain text emails
with a subject, message, and recipient(s).
Syntax: mail() function
bool mail(string $to, string $subject, string $message, string $headers);
Parameters
1. to (Required):
o The recipient's email address.
o Can include multiple email addresses separated by commas.
o Example: "[email protected]" or "[email protected], [email protected]"
2. subject (Required):
o The subject of the email.
o Keep it short and relevant.
o Example: "Welcome to Our Service"
3. message (Required):
o The body content of the email.
o Can include plain text or HTML.
o Example: "Hello, welcome to our service!"
If sending HTML, you must include appropriate headers.
4. headers (Optional):
o Additional email headers, such as From, Reply-To, and CC/BCC.
o Required for setting the sender's information and specifying content type (plain text or
HTML).
o Example:
php
CopyEdit
$headers = "From: [email protected]\r\n";
$headers .= "Reply-To: [email protected]\r\n";
$headers .= "Content-type: text/html; charset=UTF-8\r\n";
5. parameters (Optional):
o Additional command-line parameters for the email program (e.g., sendmail).
o Often used to specify the "Return-Path" for bounce handling.
Example: "-f [email protected]"
Example: Sending a Basic Email.
<?php
$to = "[email protected]"; // Recipient email address
$subject = "Hello from PHP"; // Email subject
$message = "This is a test email sent from a PHP script."; // Email body
$headers = "From: [email protected]"; // Sender information