0% found this document useful (0 votes)
6 views

UNIT4-Server Side Processing and Scripting

The document outlines the curriculum for a course on PHP, covering its working principles, features, variables, constants, operators, and control structures. It explains the server-side execution of PHP scripts, the environment needed for development, and various programming concepts such as flow control and looping. Additionally, it includes examples and syntax for PHP programming, making it a comprehensive guide for students learning web development with PHP.

Uploaded by

Sakkaravarthi S
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

UNIT4-Server Side Processing and Scripting

The document outlines the curriculum for a course on PHP, covering its working principles, features, variables, constants, operators, and control structures. It explains the server-side execution of PHP scripts, the environment needed for development, and various programming concepts such as flow control and looping. Additionally, it includes examples and syntax for PHP programming, making it a comprehensive guide for students learning web development with PHP.

Uploaded by

Sakkaravarthi S
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

RAMCO INSTITUTE OF TECHNOLOGY

Department of Information Technology


Academic Year: 2024 – 2025 (Even Semester)
IT3401 & Web Essentials

UNIT IV – SERVER-SIDE PROCESSING AND SCRIPTING-PHP 9

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

1.PHP-Working principle of PHP


1.1 Overview of PHP

➢ PHP stands for Hypertext Preprocessor was introduced by Rasmus Lerdorf in 1994

➢ PHP is an open-source server-side scripting language used for dynamic web


development and can be embedded into HTML codes.

➢ 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.”

1.2 Definition of PHP

PHP (Hypertext Preprocessor) is a widely-used open-source server-side scripting


language designed for web development. It is embedded within HTML to create dynamic and
interactive web pages.

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.3 Features of PHP

1. Open Source

• PHP is free to download, use, and modify.

• Its source code is available to developers worldwide.

2. Cross-Platform Compatibility

• PHP runs on multiple platforms, such as Windows, macOS, Linux, and Unix.

• It supports various servers like Apache, Nginx, and IIS.


3. Server-Side Execution

• PHP scripts are executed on the server, and the output (HTML or other formats) is sent

to the client's browser.

4. Easy to Learn and Use

• PHP has a simple syntax that resembles C, making it easy for beginners to learn.

• It allows for quick development of web applications.

5. Embedded Within HTML

• PHP code can be seamlessly embedded into HTML, enabling developers to add dynamic

content to static pages.

6. Database Integration

• PHP supports various databases like MySQL, PostgreSQL, SQLite, MongoDB, and more.

• It is widely used for building data-driven applications.

7. Efficient and Fast

• PHP is optimized for web applications, offering fast execution of scripts.

• It reduces development time with built-in functions for various tasks.

8. Rich Library Support

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

10. Large Community Support

• PHP has an active community that provides resources, tutorials, and solutions to
developers worldwide.
11. Supports Object-Oriented and Procedural Programming

• PHP allows developers to choose between procedural programming and object-oriented


programming paradigms.

12. Versatile

• PHP can handle various tasks, such as:

o Generating dynamic page content.

o Sending emails.

o Creating, reading, writing, and deleting files on the server.

o Managing user authentication and sessions.

13. Extensibility

• PHP can be extended with custom extensions and plugins, enhancing its functionality.

14. Framework Support

• PHP supports numerous frameworks, such as Laravel, CodeIgniter, Symfony, and CakePHP,

to simplify and speed up development.

15. Supports Various Protocols

• PHP supports HTTP, HTTPS, FTP, SMTP, and more, making it ideal for a wide range of

applications.

1.3 Working Principle of PHP

➢ PHP (Hypertext Preprocessor) is a server-side scripting language used for web


development. The working principle of PHP involves processing scripts on the server to
generate dynamic web pages that are sent to the client's browser.

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

Step1: The client requests the webpage on the browser

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.

Step 6: And it sends the webpage back to the browser.

Prerequisites for PHP Development


We need a certain environment to write PHP scripts. Since PHP is a server-side language, it requires a
web server for the script to run.
For PHP development,we need:
• XAMPP Software.
• Code editor (e.g., Visual Studio Code)

XAMPP is an open source software which stands for:


• X = cross platform
• A = Apache
• M = MariaDB
• P = PHP
• P = Perl
Steps to set up XAMPP:
1. Download and install XAMPP from the official website link:
https://www.apachefriends.org/index.html

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

ii) Local Variable:


A variable declared inside a function has a local scope, meaning it can only be accessed within
that function. It cannot be accessed outside of that function.

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

PHP print Vs echo:

print function used to create simple unformatted output.

Example:
<?php
print “<h2>PHP Works </h2>”;
print “Hello World”;
?>

echo simple statement that can be used with or without paranthesis.

Example:
<?php
echo “Hello”;
?>

print in PHP echo in PHP


Print can only output one string Echo can output one or more strings
Print is slower than echo Echo is faster than print
Print always return 1 Echo does not return any value
2.2 PHP Constants

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

Create a PHP Constant

To create a constant in PHP, use either the define() function or the const keyword.

Using define() function:

For example:
define('GREETING', 'Hello, World!');
echo GREETING;

Using const() Keyword:

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.

PHP Relational Operators (Comparison Operators)


In PHP, Comparison operators are used to comparing two values and return a Boolean
(true or false) value based on the comparison result.
PHP Logical Operators
PHP provides various logical operators that are used to combine and manipulate boolean expressions.

PHP Assignment Operators:


In PHP, Assignment operators are used to assign values to variables. These operators are shorthand
versions of common assignments, such as addition or subtraction, and can make code more concise
and readable.
PHP Array Operators
PHP provides several operators that can be used to manipulate arrays. These operators include union,
equality, identity, inequality, and non-identity operators.

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.

4. Flow Control and Looping


Flow Control: PHP supports a number of traditional programming constructs for controlling the flow
of execution of a program.
PHP If Statement:
The If Statement evaluates a condition and executes a block of code only if the condition is true.
Syntax:
if (condition) {
// code to execute if the condition is true
}
Example:
<?php
$number = 10;
if ($number > 5) {
echo "The number is greater than 5";
}?>
PHP Else Statement In PHP, the else statement (control structures in PHP) is used in conjunction with
an if statement to execute code if the if condition is false. The syntax for an if-else statement is as
follows:
Syntax:
if (condition) {
// code to be executed if the condition is true
} else
{ // code to be executed if the condition is false }
Example Program:
<?php
$age = 18;
if ($age >= 18) {
echo "You are eligible to vote.";
} else {
echo "You are not eligible to vote.";
}
?>
PHP Switch Statement In PHP, a switch statement provides a way to execute different blocks of code
based on the value of a variable or expression.
Syntax:
switch (expression) {
case value1:
// code to execute if expression equals value1
break;
case value2:
// code to execute if expression equals value2
break;
// add as many cases as needed
default:
// code to execute if none of the cases match
break;
}
Example Program:
$color = "red";
switch ($color) {
case "red":
echo "The color is red.";
break;
case "green":
echo "The color is green.";
break;
case "blue":
echo "The color is blue.";
break;
default:
echo "The color is unknown.";
break;
}
Looping in PHP:
The looping control structure is used when a set of instructions needs to be repeated multiple times
based on a given condition.
Types of Loops:
i. for loop
ii. while loop
iii. do-while loop
i. for loop:
In PHP, a for loop is used to execute a block of code repeatedly for a specified number of times. The
general syntax for a for loop in PHP is as follows:
Syntax:
for (initialization; condition; increment) {
// code to be executed
}
• Initialization: This sets the initial value of the loop variable. It is executed only once at the
beginning of the loop.
• Condition: In this part of the for loop, we write the condition that is checked before each
iteration of the loop. If the condition is true, the loop continues to execute. If the condition is
false, the loop terminates.
• Increment: In this part of the for loop the operation is performed after each iteration of the loop.
It is usually used to increment or decrement the loop variable value.
Example- for loop that prints the numbers from 1 to 10:
for ($i = 1; $i <= 3; $i++) {
echo $i . "\n";
} Output:
1
2
3
ii. while loop:
A while loop is a control structure in PHP that allows to repeatedly execute a block of
code as long as a specified condition is true. The syntax for a while loop is as follows:
Syntax:
while (condition) {
// code to be executed
}
Example Program:
$num = 1;
while ($num <= 5) {
echo $num . " ";
$num++;
}
iii. do-while loop:
A Do-While loop in PHP is a type of loop that allows to execute a block of code repeatedly while
a certain condition remains true. The key difference between a Do-While loop and a While loop is
that the Do-While loop in php will always execute the code block at least once, regardless of
whether the condition is initially true or false.
Syntax:
do {
// code to be executed
} while (condition);
• The "do" keyword starts the loop and indicates the beginning of the code block to be executed.
• The code block is contained within curly braces {} and can contain any number of statements.
• The "while" keyword is followed by a condition that will be evaluated at the end of each
iteration of the loop.
• If the condition is true, the loop will continue to execute, starting again at the beginning of the
code block.
• If the condition is false, the loop will exit and the program will continue executing the next
statement after the loop.
The key difference between a do-while loop and a while loop is that a do-while loop will always
execute the code in the block at least once, even if the condition is false from the beginning. In
contrast, a while loop will not execute the block of code at all if the condition is false from the
beginning.
Example:
$num = 1;
do {
echo $num;
$num++;
} while ($num <= 5);

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.

Types of Arrays in PHP


The main types of arrays in php are:
1. Indexed or Numeric Arrays
2. Associative arrays
3. Multidimensional arrays
4. Sparse arrays
5. Dynamic arrays

1. Indexed or Numeric Arrays


Indexed or numeric arrays are the simplest and most common type of array in PHP. They use
numeric keys to access and store values, where the first element of an indexed array has a key
of 0, and subsequent elements have incremental numeric keys.
Example:
// Create an indexed array with four elements
$myArray = ['apple', 'banana', 'cherry', 'date'];
// Access elements of the array using their numeric keys
echo $myArray[0]; // Output: apple
echo $myArray[1]; // Output: banana
echo $myArray[2]; // Output: cherry
echo $myArray[3]; // Output: date
// Change the value of an element in the array
$myArray[1] = 'orange';
echo $myArray[1]; // Output: orange
// Add a new element to the end of the array
$myArray[] = 'berry';
echo $myArray[4]; // Output: berry
// Get the number of elements in the array
$numElements = count($myArray);
echo $numElements; // Output: 5
// Loop through the array and output each element
for ($i = 0; $i < count($myArray); $i++) {
echo $myArray[$i] . ' ';
}
2. Associative Arrays
➢ Associative arrays are a type of array in PHP that use named keys instead of numeric indices
to access and store values.
➢ Each key is associated with a value, which can be of any data type. Associative arrays are
useful for storing and retrieving data using human-readable keys, such as names or IDs.
➢ Let us how to create, access, and manipulate associative arrays in PHP:
Create an associative array:
To create an associative array in PHP, we need to assign values to named keys instead of numeric
indices. Here's an example:
$person = [
'name' => 'Yash Agarwal',
'age' => 21,
'email' => '[email protected]',
];
Accessing Values in an Associative Array:
To access values in an associative array, we can use the named keys as indices.
echo 'Name: '. $person['name'] . '<br>';
echo 'Age: '. $person['age'] . '<br>';
echo 'Email: '. $person['email'] . '<br>';

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.

Commonly Used Functions to Manipulate Strings

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

1. A function without parameters and without return value:


Ex:
function wishHi()
{
echo "Hi", "<br/>";
}
wishHi();
2. A function with parameters and without return value
Ex:
function wish($message)
{
echo $message , "<br/>";
}
wish("good morning");
wish("good afternoon");

3. A function with parameters and without return value


Ex:
function add($num1,$num2)
{
return $num1 + $num2;
}
echo add(2,2), "<br/>";
4. A function without parameters and with return value:
Ex:
function ValueOfPi()
{
return 3.142;
}
echo ValueOfPi(),"<br/>";

8. File Handling and File Uploading


PHP-File Handling
• In PHP, a "file" typically refers to a digital document or a resource that is stored on a
computer's file system.
• Files in PHP can come in various formats, such as text files, binary files, and more.
• File handling in PHP refers to working with files, such as creating files, reading files, writing
files, and manipulating the files within the PHP.
PHP Open File-fopen()
• open a file with the fopen() function.
• It takes two arguments: the filename and the mode in which you want to open the file (read,
write, append, etc.).
For Example:
$file = fopen("example.txt", "r");
• example.txt is the name of the file we want to open.
• "r" indicates that we are opening the file in read-only mode.
PHP Close File-fclose()
• It's essential to close a file once done with it. Use the fclose() function to do this.
• For example,
fclose($file); // Closes the file
PHP Read File-fread()
• Reading a file is a common task, and PHP makes it straightforward with fread().
• This function allows to read the content of a file
Example Program:
$file = fopen("example.txt", "r");
$data = fread($file, filesize("example.txt"));
fclose($file);
• filesize("example.txt") calculates the size of the "example.txt" file in bytes, which is then used
as the number of bytes to read.
• So, this line of code reads the content of the "example.txt" file, which is stored in the variable
$data. After this line executes, $data will contain the entire content of the "example.txt" file.
PHP Write File-fwrite()
• Writing to a file is useful when the programmer want to store data or configuration changes.
Example:
$file = fopen("example.txt", "w"); // Open in write mode
$content = "file handling in php";
fwrite($file, $content);
fclose($file);
PHP Delete File-unlink()
• The unlink() function is used to remove a file from server or directory.
For Example
unlink("example.txt"); // Deletes example.txt
PHP File Uploading
➢ File uploading in PHP is the process of transferring a file from a user's local system to a
server using an HTML form and PHP. This allows users to submit and store files (such as
images, documents, or videos) to a web server for further processing or storage.
➢ PHP file upload features allows to upload binary and text files
➢ The move_uploaded_file() function in PHP is used to move an uploaded file from its temporary
location (where it's stored during the file upload process) to a designated directory on the
server.
➢ HTML Form: A form with an enctype="multipart/form-data" attribute allows the user to
select a file and send it to the server via an HTTP POST request.
➢ PHP Script: The PHP script uses the $_FILES superglobal to access the uploaded file's
details and manage it (e.g., validating, renaming, or moving it to a permanent location on the
server).
Key Components
1. HTML Form:
o Contains an <input> field with type="file".

o Sends the file to the server using the POST method.

2. PHP Superglobal $_FILES:


o Provides information about the uploaded file, such as:

▪ name: Original name of the file.

▪ type: MIME type of the file.

▪ tmp_name: Temporary file location on the server.

▪ size: File size in bytes.

▪ error: Error code related to the upload.

3. File Handling Functions:


o move_uploaded_file(): Moves the uploaded file from its temporary location to a
permanent directory.
Syntax:
bool move_uploaded_file(string $from, string $to) // returns true on success and false on failure
$from: The temporary path of the uploaded file (from $_FILES["file"]["tmp_name"]).
$to: The destination path where the file should be moved.
o pathinfo(): Retrieves file information like extension and filename.
Steps for File Uploading in PHP
1. Create an HTML Form:
o Use the <form> tag with the enctype="multipart/form-data" attribute to specify that the
form will handle file uploads.
o Include an <input> element with the type="file" attribute to allow users to select files.

2. Handle the Uploaded File in PHP:


o Use the PHP global variable $_FILES to access the uploaded file's details.

o Use functions like move_uploaded_file() to save the uploaded file to a specific


directory on the server.
3. File Validation:
o Validate the file type, size, and other properties to ensure secure and appropriate
uploads.
4. Store File Information:
o Store the uploaded file's information (e.g., path, name) in a database or display it to the
user as needed.

Create an HTML form to allow users to select and upload a file.


<!DOCTYPE html>
<html>
<head>
<title>Simple File Upload</title>
</head>
<body>
<h2>Upload a File</h2>
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file">Choose a file:</label>
<input type="file" name="file" id="file">
<br><br>
<button type="submit">Upload</button>
</form>
</body>
</html>
Handle the File Upload in PHP
Use PHP to process the uploaded file.
<?php
// Step 1: Check if a file is uploaded
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["file"])) {

// Step 2: Define the target directory


$targetDir = "uploads/"; // Make sure this directory exists with write permission.
$targetFile = $targetDir . basename($_FILES["file"]["name"]);
// Step 3: Move the uploaded file to the target directory
if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) {
echo "File uploaded successfully: " . htmlspecialchars($_FILES["file"]["name"]);
} else {
echo "File upload failed.";
}
} else {
echo "No file was uploaded.";
}
?>

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

if (mail($to, $subject, $message, $headers)) {


echo "Email sent successfully!";
} else {
echo "Failed to send email.";
}
?>
10. PHP and HTML - Simple PHP scripts
o PHP (Hypertext Preprocessor) and HTML (HyperText Markup Language) work together
seamlessly to create dynamic and interactive web applications.
o HTML provides the structure and user interface, while PHP adds logic, data processing, and
server-side capabilities. This combination allows developers to build feature-rich
websites.
Key Features of PHP and HTML Integration
1. Dynamic Content: PHP generates content dynamically, while HTML structures it for
display.
2. Form Handling: PHP processes user input from HTML forms (e.g., login forms, search
bars).
3. Server-Side Logic: PHP executes logic like calculations, database queries, and file
handling.
4. User Interaction: HTML collects input, and PHP responds to user actions.

Embedding PHP in HTML:


PHP code can be embedded directly into an HTML document using PHP tags (<?php ?>).
<html>
<body>
<h1>Welcome to My Website</h1>
<p>The current date is: <?php echo date('Y-m-d'); ?></p>
</body>
</html>
Generating HTML with PHP: PHP can generate entire HTML structures dynamically.
<?php
echo "<html><body>";
echo "<h1>Welcome</h1>";
echo "<p>This content is generated by PHP.</p>";
echo "</body></html>";
?>
Form Handling: HTML forms collect user input, and PHP processes it.
<form action="process.php" method="post">
<input type="text" name="name" placeholder="Enter your name" required>
<button type="submit">Submit</button>
</form>
<!-- process.php -->
<?php
$name = $_POST['name']; // Retrieve form data
echo "Hello, " . htmlspecialchars($name); // Display user input
?>
Advantages of PHP and HTML Integration
1. Ease of Use:
2. Interactive Applications:
3. Dynamic Content Generation:
4. Cross-Platform:

Applications of PHP and HTML


• E-Commerce Websites: Product catalogs, shopping carts, and payment processing.
• CMS Development: WordPress, Joomla, and other platforms use PHP for content management.
• Dynamic Forms: Feedback forms, calculators, and survey tools.
11. Databases with PHP
PHP and MySQL are commonly used together to build dynamic, data-driven web applications.
Below are the steps and a simple CRUD (Create, Read, Update, Delete) program to demonstrate
how to work with PHP and MySQL.
Steps for PHP and MySQL Connectivity
1.Set Up MySQL Database:
• Create a database using a MySQL client or tool like phpMyAdmin.
• Example SQL to create a database and table:
CREATE DATABASE demo_db;
USE demo_db;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
2. Connect PHP to MySQL:
• Use mysqli or PDO for database connections.
• Establish a connection using mysqli_connect() or PDO methods

3. Perform CRUD Operations:


• Create: Insert data into the database.
• Read: Fetch data from the database.
• Update: Modify existing data in the database.
• Delete: Remove data from the database.
Simple CRUD Program
Database Configuration :
<?php
// Database connection details
$host = "localhost";
$user = "root";
$password = "";
$database = "demo_db";
// Create connection
$conn = mysqli_connect($host, $user, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
1. Create Operation:
<?php
// Insert a new user
$name = "John Doe";
$email = "[email protected]";
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully!";
} else {
echo "Error: " . mysqli_error($conn);
}
?>
2. Read Operation:
<?php
// Fetch all users
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
echo "<h3>Users List:</h3>";
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row['id'] . " | Name: " . $row['name'] . " | Email: " . $row['email'] . "<br>";
}
} else {
echo "No records found.";
}
?>
3. Update Operation
<?php
// Update a user's email
$user_id = 1;
$new_email = "[email protected]";

$sql = "UPDATE users SET email='$new_email' WHERE id=$user_id";


if (mysqli_query($conn, $sql)) {
echo "Record updated successfully!";
} else {
echo "Error: " . mysqli_error($conn);
}
?>
?>
4. Delete Operation
<?php
// Delete a user by ID
$user_id = 1;
$sql = "DELETE FROM users WHERE id=$user_id";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully!";
} else {
echo "Error: " . mysqli_error($conn);
}
?>

You might also like