WT Unit-5

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

WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.

PROF & HOD

Unit-5
Unit- V:
Introduction to PHP: Declaring variables, data types, arrays, strings, operators,
expressions, control structures, functions, reading data from web form controls like text
boxes, radio buttons, lists etc., Handling File Uploads. Connecting to database (MySQL as
reference), executing simple queries, handling results, Handling sessions and cookies File
Handling in PHP: File operations like opening, closing, reading, writing, appending,
deleting etc. on text and binary files, listing directories.

Introduction to PHP:

PHP (Hypertext Preprocessor) is a widely-used open-source scripting language designed


for web development. It's particularly well-suited for creating dynamic web pages and
web applications. PHP scripts are executed on the server, generating HTML that is then
sent to the client's browser, allowing you to build interactive and data-driven websites.

Key Features of PHP:

1. Server-Side Scripting: PHP is primarily used for server-side scripting. This means
that PHP code is executed on the web server before the HTML is sent to the client's
browser. This enables you to generate dynamic content and interact with databases,
files, and other server resources.

2. Ease of Use: PHP is known for its relatively simple and straightforward syntax,
making it accessible for beginners and experienced developers alike.

3. Integration: PHP can be embedded directly into HTML, allowing you to mix PHP
code with HTML markup. This makes it easy to create templates and dynamically
generate content.

4. Database Connectivity: PHP has extensive support for interacting with databases,
including MySQL, PostgreSQL, SQLite, and more. You can use PHP to retrieve,
insert, update, and delete data from databases.

5. Vast Community and Resources: PHP has a large and active developer
community, resulting in a wealth of online resources, tutorials, forums, and
libraries.

1|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

6. Cross-Platform: PHP is compatible with various operating systems, including


Windows, Linux, and macOS, making it versatile for different server environments.

7. Extensibility: PHP supports extensions and libraries that provide additional


functionality, allowing you to easily integrate third-party tools and technologies.

Example PHP Code:

Here's a simple example of PHP code embedded within HTML to display the current date
on a web page:

<!DOCTYPE html>

<html>

<head>

<title>PHP Example</title>

</head>

<body>

<h1>Welcome to My PHP Page</h1>

<p>Today's date is: <?php echo date("Y-m-d"); ?></p>

</body>

</html>

In this example, the PHP code <?php echo date("Y-m-d"); ?> generates the current date
and displays it within the paragraph element.

Getting Started with PHP:

To start using PHP, you need a web server that supports PHP processing. Common
options include Apache, Nginx, and XAMPP. PHP files have a .php extension, and the
PHP code is enclosed within <?php and ?> tags.

PHP can be used for various tasks, including generating dynamic web pages, handling
form submissions, interacting with databases, creating user authentication systems, and

2|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

more. As you become more familiar with PHP, you can explore its extensive features and
capabilities for web development.

Declaring variables:

In PHP, you can declare variables to store data values that you can use throughout your
script. PHP variables have a dollar sign ($) as a prefix, followed by the variable name.
Here's how you declare variables in PHP:

$variableName = value;

Here's a breakdown of the components:

 $: This dollar sign indicates that you are declaring a variable.

 variableName: Replace this with your desired variable name. Variable names are
case-sensitive and must start with a letter or underscore (_). They can contain
letters, numbers, and underscores.

 value: This is the value you want to assign to the variable.

Here are some examples of declaring variables in PHP:

$name = "Alice"; // String variable

$age = 30; // Integer variable

$height = 5.7; // Floating-point (decimal) variable

$isStudent = true; // Boolean variable

$colors = array("red", "green", "blue"); // Array variable (before PHP 5.4)

$fruits = ["apple", "banana", "orange"]; // Array variable (PHP 5.4 and later)

PHP is a loosely typed language, which means you don't need to declare the data type
explicitly when declaring a variable. PHP infers the data type based on the assigned value.
Additionally, PHP variables are dynamically typed, meaning you can change the type of
data a variable holds during runtime.

For example:

3|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

$number = 5; // $number is an integer

$number = "five"; // $number is now a string

It's important to keep in mind that PHP variable names are case-sensitive ($variable and
$Variable are considered different variables), and they must start with a letter or
underscore.

Using meaningful variable names can make your code more readable and maintainable.
Additionally, adhering to consistent naming conventions, like camelCase or snake_case,
can help improve code clarity and collaboration.

Data Types:

PHP supports several data types that allow you to store and manipulate different types of
values. These data types include:

1. Integer: Represents whole numbers, both positive and negative.

$number = 42;

$negativeNumber = -10;

2. Float (Floating-Point): Represents decimal numbers (also known as floating-point


numbers or doubles).

$pi = 3.14;

$temperature = -12.5;

3. String: Represents sequences of characters, enclosed in single quotes ' or double


quotes ".

$name = "Alice";

$message = 'Hello, PHP!';

4. Boolean: Represents a true or false value.

$isStudent = true;

4|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

$hasAccount = false;

5.Array: Represents an ordered collection of values, indexed by numerical or


associative keys.

$colors = array("red", "green", "blue");

$person = array("name" => "John", "age" => 28);

6. Object: Represents an instance of a class, containing properties (variables) and


methods (functions).

class Person

public $name;

public $age;

$person = new Person();

$person->name = "Alice";

$person->age = 30;

7. Null: Represents the absence of a value.

$emptyValue = null;

8. Resource: Represents a reference to an external resource, such as a database


connection or file handle.

$fileHandle = fopen("example.txt", "r");

5|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

9. Callable: Represents a callback function that can be called dynamically.

function sayHello($name)

echo "Hello, $name!";

$functionRef = 'sayHello';

$functionRef('Alice'); // Outputs: "Hello, Alice!"

10.Iterable (PHP 7.1+): Represents a data structure that can be looped through, such
as arrays and objects implementing the Traversable interface.

$fruits = array("apple", "banana", "orange");

foreach ($fruits as $fruit)

echo $fruit . " ";

These data types allow you to work with a wide range of values and perform various
operations in PHP. Additionally, PHP is a dynamically typed language, so you don't need
to declare the data type explicitly when declaring a variable; PHP infers it based on the
assigned value.

Arrays:

In PHP, an array is a versatile data structure that can hold multiple values under a single
variable name. Arrays are commonly used for storing and manipulating lists of related
data. PHP supports both indexed arrays (numeric indices) and associative arrays (string
indices).

Indexed Arrays:

6|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

An indexed array uses numeric indices to access its elements. The first element has an
index of 0, the second element has an index of 1, and so on.

$fruits = array("apple", "banana", "orange");

// or using short array syntax (PHP 5.4+)

$fruits = ["apple", "banana", "orange"];

echo $fruits[0]; // Outputs: "apple"

echo $fruits[1]; // Outputs: "banana"

echo $fruits[2]; // Outputs: "orange"

Associative Arrays:

An associative array uses string keys (also known as indices) instead of numeric
indices. Each key is associated with a value.

$person = array(

"name" => "Alice",

"age" => 30,

"city" => "New York"

);

// or using short array syntax (PHP 5.4+)

$person = [

"name" => "Alice",

"age" => 30,

"city" => "New York"

];

echo $person["name"]; // Outputs: "Alice"

echo $person["age"]; // Outputs: 30


7|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

echo $person["city"]; // Outputs: "New York"

Multidimensional Arrays:

Arrays can also be nested to create multidimensional arrays. A multidimensional


array is essentially an array of arrays.

$matrix = array(

array(1, 2, 3),

array(4, 5, 6),

array(7, 8, 9)

);

echo $matrix[0][0]; // Outputs: 1

echo $matrix[1][2]; // Outputs: 6

echo $matrix[2][1]; // Outputs: 8

Array Functions:

PHP provides a wide range of built-in functions for working with arrays. These functions
allow you to add elements, remove elements, sort arrays, merge arrays, and perform
various other operations.

Here are a few examples of array functions:

$numbers = [3, 1, 4, 1, 5, 9];

$length = count($numbers); // Get the number of elements in the array

$sum = array_sum($numbers); // Calculate the sum of array elements

$sortedNumbers = sort($numbers); // Sort the array in ascending order

8|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Strings:

In PHP, a string is a sequence of characters that represents text. Strings can include letters,
numbers, symbols, spaces, and special characters. PHP provides various functions and
features to work with strings, allowing you to manipulate, concatenate, format, and
perform other operations on text data.

Creating Strings:

You can create strings in PHP using single quotes (') or double quotes ("). Both single and
double quotes are used interchangeably, but there are a few differences:

$singleQuoted = 'This is a single-quoted string.';

$doubleQuoted = "This is a double-quoted string.";

// Embedding variables in double-quoted strings

$name = "Alice";

$greeting = "Hello, $name!";

String Concatenation:

You can concatenate (combine) strings using the . operator:

$firstName = "John";

$lastName = "Doe";

$fullName = $firstName . " " . $lastName; // Concatenates the strings

String Length:

You can find the length (number of characters) of a string using the strlen() function:

$phrase = "Hello, world!";

$length = strlen($phrase); // Returns the length of the string

Substring:

You can extract a portion of a string using the substr() function:

9|P ag e LOYOLA INST IT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

$text = "The quick brown fox jumps over the lazy dog";

$substring = substr($text, 10, 5); // Extracts "brown"

String Functions:

PHP provides a rich set of functions for working with strings, such as:

 strtolower(): Converts a string to lowercase.

 strtoupper(): Converts a string to uppercase.

 trim(): Removes whitespace or specified characters from the beginning and end of
a string.

 str_replace(): Replaces occurrences of a substring with another substring.

 strpos(): Finds the position of the first occurrence of a substring in a string.

Here's an example of using some of these functions:

$text = " Hello, PHP! ";


$lowercase = strtolower($text); // " hello, php! "
$uppercase = strtoupper($text); // " HELLO, PHP! "
$trimmed = trim($text); // "Hello, PHP!"
$replaced = str_replace("PHP", "world", $text); // " Hello, world! "
$position = strpos($text, "PHP"); // Returns the position of "PHP"
Escape Sequences:

Escape sequences allow you to include special characters within strings:

 \": Double quote

 \': Single quote

 \\: Backslash

 \n: Newline

 \r: Carriage return

10 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

 \t: Tab

$message = "She said, \"Hello!\"";

$newline = "Line 1\nLine 2";

Strings are a fundamental part of PHP programming, used for everything from basic text
output to complex text manipulation and processing. Understanding how to work with
strings effectively is crucial for building dynamic and interactive web applications

OPERATORS:

In PHP, operators are symbols or keywords that perform operations on values and
variables. They allow you to perform arithmetic, comparison, logical, and other types of
operations in your code. PHP supports a wide range of operators, each serving a specific
purpose. Let's explore some of the most common types of operators:

1. Arithmetic Operators:

Arithmetic operators perform basic mathematical operations.

 +: Addition

 -: Subtraction

 *: Multiplication

 /: Division

 %: Modulus (remainder)

 **: Exponentiation (PHP 5.6+)

Php:

$a = 10;

$b = 5;

$sum = $a + $b; // 15

$difference = $a - $b; // 5

$product = $a * $b; // 50

11 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

$quotient = $a / $b; // 2

$remainder = $a % $b; // 0

$exponent = $a ** $b; // 100000

2. Assignment Operators:

Assignment operators are used to assign values to variables.

 =: Assign

 +=: Add and assign

 -=: Subtract and assign

 *=: Multiply and assign

 /=: Divide and assign

 %=: Modulus and assign

 **=: Exponentiation and assign (PHP 5.6+)

$x = 5;

$y = 3;

$x += $y; // $x is now 8

$x -= $y; // $x is now 5 again

$x *= $y; // $x is now 15

$x /= $y; // $x is now 5

$x %= $y; // $x is now 2

$x **= $y; // $x is now 8

3. Comparison Operators:

Comparison operators are used to compare values.

 ==: Equal to

12 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

 != or <>: Not equal to

 ===: Identical (equal value and type)

 !==: Not identical

 <: Less than

 >: Greater than

 <=: Less than or equal to

 >=: Greater than or equal to

$a = 5;

$b = 3;

$result1 = $a == $b; // false

$result2 = $a > $b; // true

$result3 = $a !== $b; // true

4. Logical Operators:

Logical operators are used to combine or manipulate Boolean values.

 && or and: Logical AND

 || or or: Logical OR

 ! or not: Logical NOT

$condition1 = true;

$condition2 = false;

$result = $condition1 && $condition2; // false

$result = $condition1 || $condition2; // true

$result = !$condition1; // false

13 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

These are just a few examples of the many operators available in PHP. Operators are
fundamental to performing various tasks in your PHP scripts, from simple arithmetic
calculations to complex decision-making logic. Understanding how to use operators
effectively is essential for writing efficient and functional PHP code.

Expressions:

In programming, an expression is a combination of values, variables, operators, and


function calls that can be evaluated to produce a result. Expressions can be as simple as a
single value or as complex as a combination of values and operations. They are used
extensively in programming to compute values, make decisions, and perform various
tasks.

Here are a few examples of expressions in PHP:

1. Arithmetic Expression: An arithmetic expression involves mathematical


operations.

$result = (5 + 3) * 2; // Evaluates to 16

2. String Concatenation Expression: Combining strings using the concatenation


operator .

$greeting = "Hello, " . "world!";

3. Comparison Expression: Comparing values using comparison operators.

$isGreater = 10 > 5; // Evaluates to true

4. Function Call Expression: Calling a function and using its return value.

$length = strlen("Hello"); // Evaluates to 5

5. Logical Expression: Combining Boolean values using logical operators.

$result = ($a > 0) && ($b < 10); // Evaluates to true or false

6. Ternary Conditional Expression: Using the ternary conditional operator (? :) to


create a compact if-else expression.

14 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

$result = ($a > $b) ? "Greater" : "Smaller";

7. Array Access Expression: Accessing elements within an array using indices.

$colors = ["red", "green", "blue"];

$selectedColor = $colors[1]; // Evaluates to "green"

8. Variable Expression: Using a variable's value.

$age = 25;

9. Complex Expression: Combining multiple expressions to achieve a more


complex result.

$totalPrice = $quantity * $unitPrice + ($quantity * $unitPrice * $taxRate);

Expressions are the building blocks of programs. They allow you to perform
calculations, make decisions, and manipulate data dynamically. Understanding how to
construct and evaluate expressions is crucial for effective programming in any language,
including PHP.

Control Structures:

Control structures in programming are constructs that enable you to control the flow of
execution within your code. They allow you to make decisions, repeat actions, and
execute different blocks of code based on conditions. PHP provides various control
structures that help you create logic and control the behavior of your scripts.

Here are some common control structures in PHP:

1. if Statement: The if statement allows you to execute a block of code if a certain


condition is true.

$age = 25;

if ($age >= 18)

echo "You are an adult.";

} else

15 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

echo "You are not an adult.";

2. elseif and else Statements: The elseif and else statements are used in combination
with if to create multiple conditional branches.

$score = 75;

if ($score >= 90)

echo "Excellent!";

} elseif ($score >= 70)

echo "Good!";

} else

echo "Needs improvement.";

3.switch Statement: The switch statement allows you to perform different actions based
on different values of a variable.

$dayOfWeek = "Wednesday";

switch ($dayOfWeek)

case "Monday":

case "Tuesday":

16 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

case "Wednesday":

case "Thursday":

case "Friday":

echo "It's a weekday.";

break;

case "Saturday":

case "Sunday":

echo "It's a weekend day.";

break;

default:

echo "Invalid day.";

3. for Loop: The for loop allows you to execute a block of code a specific number of
times.

for ($i = 1; $i <= 5; $i++)

echo "Iteration $i<br>";

4. while Loop: The while loop executes a block of code as long as a condition is true.

$counter = 0;

while ($counter < 3)

echo "Count: $counter<br>";

17 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

$counter++;

5. do-while Loop: The do-while loop is similar to the while loop, but it guarantees
that the block of code is executed at least once.

$x = 1;

Do

echo "Value of x: $x<br>";

$x++;

} while ($x <= 5);

6. foreach Loop: The foreach loop is used to iterate through elements in an array or
other iterable objects

$fruits = ["apple", "banana", "orange"];

foreach ($fruits as $fruit)

echo "$fruit<br>";

Control structures provide the foundation for creating complex algorithms, making
decisions, and repeating actions in your PHP scripts. By mastering these structures, you
can create dynamic and responsive applications that cater to various scenarios and user
interactions.

18 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Functions:

In PHP, a function is a reusable block of code that performs a specific task. Functions are
used to organize code into manageable and modular pieces, making your code easier to
read, maintain, and debug. Functions encapsulate a set of instructions and can be called
from different parts of your program to execute the same logic.

Here's how you define and use functions in PHP:

Defining a Function:

To define a function, use the function keyword followed by the function name, a pair of
parentheses (), and a pair of curly braces {} containing the function's code.

function greet($name)

echo "Hello, $name!";

In this example, the function greet() takes a parameter $name and outputs a greeting
message with the provided name.

Calling a Function:

To call a function, simply write its name followed by parentheses containing any required
arguments.

greet("Alice"); // Outputs: "Hello, Alice!"

Returning Values:

Functions can also return values using the return keyword.

function add($a, $b)

return $a + $b;

19 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

$result = add(5, 3); // $result is now 8

Function Parameters:

Functions can accept parameters (also known as arguments), which are values passed into
the function when it's called. These parameters can be used within the function's code.

function multiply($x, $y)

return $x * $y;

$product = multiply(4, 5); // $product is now 20

Default Values for Parameters:

You can provide default values for parameters. If a value is not provided when the
function is called, the default value will be used.

function power($base, $exponent = 2)

return $base ** $exponent;

$result1 = power(3); // Squares 3 (default exponent is 2)

$result2 = power(2, 4); // 2 raised to the power of 4

Scope:

Variables defined within a function have a local scope, meaning they are only accessible
within that function. Variables defined outside functions have a global scope and can be
accessed from any part of the script.

Built-in Functions:

20 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

PHP also provides a wide range of built-in functions that perform various tasks, such as
manipulating strings, working with arrays, interacting with databases, and more.

$length = strlen("Hello"); // Returns the length of the string

$uppercase = strtoupper("hello"); // Converts a string to uppercase

Creating and using functions is a fundamental concept in programming that promotes


code reusability, organization, and maintainability. By breaking down complex logic into
smaller functions, you can write more structured and efficient PHP applications.

Reading Data From Web Form Controls Like Text Boxes:

To read data from web form controls like text boxes in PHP, you need to retrieve the
values submitted by the user when the form is submitted. This involves using the $_POST
or $_GET superglobal arrays, depending on the form's method attribute (POST or GET).

Here's a step-by-step example of how to read data from text boxes in a web form using
PHP:

1. Create an HTML form with text boxes:

<!DOCTYPE html>

<html>

<head>

<title>Form Example</title>

</head>

<body>

<form method="post" action="process_form.php">

<label for="name">Name:</label>

<input type="text" id="name" name="name">

<br>

<label for="email">Email:</label>

21 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

<input type="email" id="email" name="email">

<br>

<input type="submit" value="Submit">

</form>

</body>

</html>

In this example, the form submits data using the POST method to a file named
"process_form.php".

2. Create the PHP script to process the form data (process_form.php):

<!DOCTYPE html>

<html>

<head>

<title>Form Processing</title>

</head>

<body>

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$name = $_POST["name"]; // Retrieve the value of "name" field

$email = $_POST["email"]; // Retrieve the value of "email" field

echo "Name: $name<br>";

echo "Email: $email<br>";

} else

22 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

echo "Form not submitted.";

?>

</body>

</html>

In this script, we use the $_POST superglobal to access the values submitted through the
form. The $_POST array is associative, where the keys correspond to the name attributes
of the form controls.

When the user submits the form, the data entered into the text boxes will be displayed on
the "process_form.php" page.

Remember that user input should be validated and sanitized to ensure data security and
integrity. Additionally, you can use functions like isset() to check if a specific field has
been submitted and handle validation and error handling appropriately.

Note: If you used the GET method in your form (method="get"), you would use the
$_GET superglobal instead of $_POST to retrieve the form data.

Radio Buttons:

Radio buttons are a type of input control in HTML that allow users to select one option
from a group of choices. Radio buttons are often used when you want users to make a
single selection from a set of mutually exclusive options.

Here's how you can use radio buttons in an HTML form and process the selected value
using PHP:

1. Create an HTML form with radio buttons:

<!DOCTYPE html>

<html>

<head>

<title>Radio Button Example</title>

23 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

</head>

<body>

<form method="post" action="process_radio.php">

<p>Gender:</p>

<label>

<input type="radio" name="gender" value="male"> Male

</label>

<label>

<input type="radio" name="gender" value="female"> Female

</label>

<label>

<input type="radio" name="gender" value="other"> Other

</label>

<br>

<input type="submit" value="Submit">

</form>

</body>

</html>

In this example, the form contains a group of radio buttons with the same name attribute
("gender") but different value attributes.

2. Create the PHP script to process the selected radio button value
(process_radio.php):

<!DOCTYPE html>

<html>
24 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

<head>

<title>Radio Button Processing</title>

</head>

<body>

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

if (isset($_POST["gender"])) {

$selectedGender = $_POST["gender"];

echo "Selected Gender: $selectedGender";

} else {

echo "No gender selected.";

} else {

echo "Form not submitted.";

?>

</body>

</html>

In this script, we use the $_POST superglobal to access the selected radio button value
based on its name attribute. We use the isset() function to check if the radio button was
selected before trying to access its value.

When the user submits the form, the selected gender option will be displayed on the
"process_radio.php" page.

25 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Radio buttons are commonly used for various user selections, such as gender, payment
methods, or preferences. Make sure to provide clear labels and meaningful values for
radio buttons to enhance the user experience. As with any form input, input validation and
sanitation are important considerations.

Lists:

In HTML, lists are used to group and present content in an organized manner. There are
three main types of lists: unordered lists (<ul>), ordered lists (<ol>), and definition lists
(<dl>). Lists are often used to display items, options, or definitions in a structured format.

Here's how you can use lists in HTML:

Unordered List (<ul>):

An unordered list is a list of items with bullet points. Each item is wrapped in an <li> (list
item) element.

<!DOCTYPE html>

<html>

<head>

<title>Unordered List Example</title>

</head>

<body>

<h2>Shopping List</h2>

<ul>

<li>Apples</li>

<li>Bananas</li>

<li>Oranges</li>

</ul>

26 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

</body>

</html>

Ordered List (<ol>):

An ordered list is a numbered list of items. Like unordered lists, each item is enclosed in
an <li> element.

<!DOCTYPE html>

<html>

<head>

<title>Ordered List Example</title>

</head>

<body>

<h2>Steps to Bake a Cake</h2>

<ol>

<li>Preheat the oven.</li>

<li>Mix the ingredients.</li>

<li>Pour the batter into a pan.</li>

<li>Bake for 30 minutes.</li>

</ol>

</body>

</html>

Definition List (<dl>):

A definition list is used to define terms and their corresponding definitions. It consists of
pairs of <dt> (definition term) and <dd> (definition description) elements.
27 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

<!DOCTYPE html>

<html>

<head>

<title>Definition List Example</title>

</head>

<body>

<h2>Glossary</h2>

<dl>

<dt>HTML</dt>

<dd>Hypertext Markup Language</dd>

<dt>CSS</dt>

<dd>Cascading Style Sheets</dd>

</dl>

</body>

</html>

These are basic examples of how to use lists in HTML. Lists are versatile and can be
styled using CSS to enhance their appearance. They provide a clear and organized way to
present information on your web pages.

Handling File Uploads:

Handling file uploads in PHP involves receiving files that users submit through a form,
processing those files, and potentially storing them on the server. Here's a step-by-step
guide on how to handle file uploads using PHP:

1. Create an HTML Form:

Create an HTML form that includes an <input> element with type="file" to allow users
to choose and upload a file.

28 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

<!DOCTYPE html>

<html>

<head>

<title>File Upload</title>

</head>

<body>

<form action="upload.php" method="post" enctype="multipart/form-data">

<input type="file" name="uploadedFile">

<input type="submit" value="Upload">

</form>

</body>

</html>

2. Process the Uploaded File in PHP:

Create a PHP script that handles the uploaded file. This script will be specified in the
action attribute of the form.

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$targetDirectory = "uploads/"; // Directory where the uploaded files will be


stored

$targetFile = $targetDirectory .
basename($_FILES["uploadedFile"]["name"]);

$uploadSuccess =
move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $targetFile);

29 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

if ($uploadSuccess)

echo "File uploaded successfully.";

} else

echo "Error uploading file.";

?>

In this PHP script (upload.php), the following steps are performed:

 The target directory for storing uploaded files is specified.

 The $_FILES superglobal is used to access information about the uploaded file.

 The move_uploaded_file() function is used to move the uploaded file from the
temporary directory to the desired location.

3. Configure Server Settings:

Make sure that your server's PHP configuration allows file uploads. You may need to
adjust the values of the following PHP configuration directives in your php.ini file:

 file_uploads: Set to On to allow file uploads.

 upload_max_filesize: Specify the maximum size of uploaded files.

 post_max_size: Specify the maximum size of POST data (including uploaded


files).

4. Create the Upload Directory:

Create the directory where you want to store the uploaded files. In the example above, it's
the "uploads" directory. Ensure that the web server has appropriate write permissions to
this directory.

30 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

5. Security Considerations:

File uploads can be a security risk if not handled properly. Some security considerations
include:

 Validate file types and extensions to prevent users from uploading harmful files.

 Generate unique filenames for uploaded files to prevent overwriting.

 Store uploaded files outside of the web root directory to prevent direct access.

 Use input validation and sanitization to prevent malicious input.

Handling file uploads requires careful attention to security and proper error handling to
ensure that your application functions as expected and keeps user data safe.

Connecting To Database (Mysql As Reference):

To connect to a MySQL database from a PHP script, you'll need to use the MySQLi
(MySQL Improved) or PDO (PHP Data Objects) extension. These extensions provide an
interface for interacting with MySQL databases. Here, I'll show you how to use both
extensions to connect to a MySQL database in PHP.

Using MySQLi:

1. Create a Database Connection:

$servername = "localhost"; // Replace with your database server name

$username = "username"; // Replace with your MySQL username

$password = "password"; // Replace with your MySQL password

$database = "dbname"; // Replace with your database name

// Create a connection

$conn = new mysqli($servername, $username, $password, $database);

31 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

// Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

2. Perform Database Operations:

Once the connection is established, you can perform various database operations using the
$conn object.

$sql = "SELECT id, name, email FROM users";

$result = $conn->query($sql);

if ($result->num_rows > 0) {

while ($row = $result->fetch_assoc()) {

echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " .
$row["email"] . "<br>";

} else {

echo "0 results";

// Close the connection

$conn->close();

Using PDO:

1. Create a Database Connection:

$servername = "localhost"; // Replace with your database server name


32 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

$username = "username"; // Replace with your MySQL username

$password = "password"; // Replace with your MySQL password

$database = "dbname"; // Replace with your database name

try {

$conn = new PDO("mysql:host=$servername;dbname=$database", $username,


$password);

$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);

} catch (PDOException $e) {

echo "Connection failed: " . $e->getMessage();

2. Perform Database Operations:

You can perform database operations using the $conn object.

$sql = "SELECT id, name, email FROM users";

$result = $conn->query($sql);

foreach ($result as $row)

echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " .
$row["email"] . "<br>";

// Close the connection

$conn = null;

33 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Both MySQLi and PDO offer powerful features for connecting to databases, executing
queries, and fetching results. PDO is more versatile as it supports multiple database
systems, while MySQLi is tailored specifically for MySQL. It's important to properly
sanitize inputs and handle errors when interacting with databases to ensure data integrity
and security.

Executing Simple Queries

Executing simple queries in PHP involves using the database connection you've
established to send SQL queries to the database and retrieve results. Here are examples of
how to execute SELECT, INSERT, UPDATE, and DELETE queries using both MySQLi
and PDO extensions.

Using MySQLi:

1. SELECT Query:

php
$mysqli = new mysqli($servername, $username, $password, $database);
$query = "SELECT id, name, email FROM users";
$result = $mysqli->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " .
$row["email"] . "<br>";
}
} else {
echo "0 results";
}

$mysqli->close();

34 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

INSERT Query:

$mysqli = new mysqli($servername, $username, $password, $database);

$name = "John Doe";

$email = "john@example.com";

$query = "INSERT INTO users (name, email) VALUES ('$name', '$email')";

if ($mysqli->query($query) === TRUE)

echo "New record created successfully";

} else

echo "Error: " . $mysqli->error;

$mysqli->close();

Using PDO:

1. SELECT Query:

try {

$pdo = new PDO("mysql:host=$servername;dbname=$database",


$username, $password);

$pdo->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);

$query = "SELECT id, name, email FROM users";

$result = $pdo->query($query);

foreach ($result as $row) {

35 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " .
$row["email"] . "<br>";

$pdo = null;

} catch (PDOException $e) {

echo "Error: " . $e->getMessage();

INSERT Query:

try {

$pdo = new PDO("mysql:host=$servername;dbname=$database",


$username, $password);

$pdo->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);

$name = "Jane Smith";

$email = "jane@example.com";

$query = "INSERT INTO users (name, email) VALUES (:name, :email)";

$stmt = $pdo->prepare($query);

$stmt->bindParam(':name', $name);

$stmt->bindParam(':email', $email);

if ($stmt->execute()) {

echo "New record created successfully";

36 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

} else {

echo "Error: " . $stmt->errorInfo()[2];

$pdo = null;

} catch (PDOException $e) {

echo "Error: " . $e->getMessage();

These examples show how to execute simple queries using both MySQLi and PDO.
Remember to properly sanitize inputs and handle errors to ensure the security and
reliability of your database operations.

Handling Results:

When executing queries in PHP, you'll often need to handle and work with the results
returned from the database. The result of a query is typically a result set, which is a
collection of rows that match the query criteria. Here's how you can handle and process
query results using both MySQLi and PDO extensions.

Handling Results with MySQLi:

1. SELECT Query:

$mysqli = new mysqli($servername, $username, $password, $database);


$query = "SELECT id, name, email FROM users";
$result = $mysqli->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " .
$row["email"] . "<br>";
}
37 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

} else {
echo "0 results";
}
$mysqli->close();
2. Working with Result Rows:

In the code above, the fetch_assoc() method retrieves the next row of the result set as an
associative array, where column names are used as keys. You can use other methods like
fetch_row() for indexed arrays or fetch_object() for objects.

Handling Results with PDO:

SELECT Query:
try {
$pdo = new PDO("mysql:host=$servername;dbname=$database", $username,
$password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$query = "SELECT id, name, email FROM users";


$result = $pdo->query($query);

foreach ($result as $row)


{
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " . $row["email"] .
"<br>";
}

$pdo = null;
} catch (PDOException $e)

38 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

{
echo "Error: " . $e->getMessage();
}

When executing queries in PHP, you'll often need to handle and work with the results
returned from the database. The result of a query is typically a result set, which is a
collection of rows that match the query criteria. Here's how you can handle and process
query results using both MySQLi and PDO extensions.

Handling Results with MySQLi:

1. SELECT Query:

phpCopy code

$mysqli = new mysqli($servername, $username, $password, $database); $query =


"SELECT id, name, email FROM users"; $result = $mysqli->query($query); if ($result-
>num_rows > 0) { while ($row = $result->fetch_assoc()) { echo "ID: " . $row["id"] . " -
Name: " . $row["name"] . " - Email: " . $row["email"] . "<br>"; } } else { echo "0 results";
} $mysqli->close();

2. Working with Result Rows:

In the code above, the fetch_assoc() method retrieves the next row of the result set as an
associative array, where column names are used as keys. You can use other methods like
fetch_row() for indexed arrays or fetch_object() for objects.

Handling Results with PDO:

1. SELECT Query:

phpCopy code

try { $pdo = new PDO("mysql:host=$servername;dbname=$database", $username,


$password); $pdo->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION); $query = "SELECT id, name, email FROM users";
$result = $pdo->query($query); foreach ($result as $row) { echo "ID: " . $row["id"] . " -

39 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Name: " . $row["name"] . " - Email: " . $row["email"] . "<br>"; } $pdo = null; } catch
(PDOException $e) { echo "Error: " . $e->getMessage(); }

Working with Result Rows:

In the PDO code above, the foreach loop iterates over the result set directly, treating each
row as an associative array by default.

When working with query results, consider the following points:

 Use the appropriate method (fetch_assoc(), fetch_row(), fetch_object(), etc.) to


retrieve rows in the format you need.

 Loop through the result set to process each row.

 Close or nullify the connection or statement when you're done to release resources.

Remember to sanitize and validate data retrieved from the database to ensure security and
integrity.

Handling Sessions And Cookies File Handling In PHP:

Handling sessions, cookies, and file handling are crucial aspects of web development.
Here's a brief overview of how to handle sessions, cookies, and file operations in PHP.

Handling Sessions:

Sessions allow you to maintain user data across multiple pages during a user's visit to your
website. PHP provides a way to manage sessions using the $_SESSION superglobal.

1. Start a session:

session_start();

2. Store data in session:


$_SESSION['username'] = 'user123';

3. Retrieve session data:

$username = $_SESSION['username'];

4. Destroy a session:

40 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

session_destroy();

Handling Cookies:

Cookies are small pieces of data stored on the user's computer. PHP provides a way to set
and retrieve cookies using the setcookie() function and the $_COOKIE superglobal.

1. Set a cookie:

setcookie('username', 'user123', time() + 3600, '/');

2. Retrieve a cookie:

$username = $_COOKIE['username'];

3. Delete a cookie:

setcookie('username', '', time() - 3600, '/');

File Handling in PHP:

File handling involves reading, writing, and manipulating files on the server. PHP
provides a variety of functions for file operations.
1. Reading a file:

$contents = file_get_contents('file.txt');

2. Writing to a file:

$data = "Hello, world!";

file_put_contents('file.txt', $data);

3. Appending to a file:

$data = "New data to append";

file_put_contents('file.txt', $data, FILE_APPEND);

4. Checking if a file exists:

if (file_exists('file.txt'))

41 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

// File exists

5. Deleting a file:

unlink('file.txt');

Uploading a file (handling file uploads):

$targetDirectory = 'uploads/';

$targetFile = $targetDirectory . basename($_FILES["uploadedFile"]["name"]);

move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $targetFile);

Remember to handle errors, sanitize user input, and secure your file operations to
ensure data integrity and prevent security vulnerabilities.

File Operations Like Opening:

In PHP, you can perform various file operations like opening, reading, writing, and
closing files. Here's a step-by-step guide on how to perform these operations:

Opening Files:

To open a file, you can use the fopen() function. This function returns a file handle that
you can use for subsequent file operations.

$filename = "example.txt";

$mode = "r"; // "r" for read mode

$fileHandle = fopen($filename, $mode);

if ($fileHandle)

echo "File opened successfully.";

42 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

// Perform other operations here

fclose($fileHandle); // Close the file when done

} else

echo "Error opening the file.";

The $mode parameter specifies the mode in which the file should be opened:

 "r": Read mode (file must exist)

 "w": Write mode (creates a new file or truncates an existing file)

 "a": Append mode (creates a new file or appends to an existing file)

 "x": Exclusive create mode (creates a new file, fails if it already exists)

Reading Files:

To read the contents of a file, you can use functions like fread() or fgets().

$filename = "example.txt";

$mode = "r";

$fileHandle = fopen($filename, $mode);

if ($fileHandle)

while (!feof($fileHandle))

$line = fgets($fileHandle);

echo $line;

43 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

fclose($fileHandle);

} else

echo "Error opening the file.";

Make sure to close the file using fclose() when you're done with it to free up system
resources.

Appending to Files:

To append data to an existing file, you can use append mode "a".

$filename = "example.txt";

$mode = "a"; // Append mode

$fileHandle = fopen($filename, $mode);

if ($fileHandle)

$data = "Appended content!";

fwrite($fileHandle, $data);

fclose($fileHandle);

echo "Data appended successfully.";

} else

echo "Error opening the file.";

44 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

These are the basic file operations in PHP. Remember to handle errors gracefully and to
properly validate and sanitize user inputs to ensure the security and integrity of your file
handling operations.

Closing, Reading, Writing, Appending, Deleting Etc. On Text And Binary Files :

Opening and Closing Files:

Opening and closing files are common operations before and after working with file
contents.

// Opening a file in read mode (text)

$fileHandle = fopen("text_file.txt", "r");

// Opening a file in binary mode

$binaryFileHandle = fopen("binary_file.bin", "rb");

// Remember to close the file handles when done

fclose($fileHandle);

fclose($binaryFileHandle);

Reading from Text Files:

Reading text from a file can be done using functions like fread() or fgets().

$fileHandle = fopen("text_file.txt", "r");

while (!feof($fileHandle))

$line = fgets($fileHandle);

echo $line;

} fclose($fileHandle);

45 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Reading from Text Files:

Reading text from a file can be done using functions like fread() or fgets().

$fileHandle = fopen("text_file.txt", "r");

while (!feof($fileHandle))

$line = fgets($fileHandle);

echo $line;

fclose($fileHandle);

Writing to Text Files:

Writing text to a file can be done using functions like fwrite().

$fileHandle = fopen("text_file.txt", "w");

$data = "Hello, world!\n";

fwrite($fileHandle, $data);

fclose($fileHandle);

Appending to Text Files:

Appending text to a file can be done using append mode "a".

$fileHandle = fopen("text_file.txt", "a");

$data = "Appended content!\n";

fwrite($fileHandle, $data);

fclose($fileHandle);

46 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Reading from Binary Files:

Reading binary data from a file can be done using functions like fread().

$binaryFileHandle = fopen("binary_file.bin", "rb");

$data = fread($binaryFileHandle, filesize("binary_file.bin"));

fclose($binaryFileHandle);

Writing to Binary Files:

Writing binary data to a file can be done using functions like fwrite().

$binaryFileHandle = fopen("binary_file.bin", "wb");

$data = pack("C*", 65, 66, 67); // Write binary data

fwrite($binaryFileHandle, $data);

fclose($binaryFileHandle);

Deleting Files:

Deleting files can be done using the unlink() function.

if (unlink("file_to_delete.txt"))

echo "File deleted successfully.";

} else

echo "Error deleting the file.";

These examples demonstrate how to perform various file operations on both text
and binary files in PHP. Make sure to handle errors, close file handles, and
validate/sanitize user inputs to ensure proper functionality and security.
47 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT
WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

Listing Directories.

To list directories and their contents in PHP, you can use the scandir() function. This
function returns an array of file and directory names within the specified directory.

Here's how you can use scandir() to list directories and their contents:

$directory = "path/to/directory"; // Replace with the actual directory path

$contents = scandir($directory);

foreach ($contents as $item)

if ($item != "." && $item != "..")

echo $item . "<br>";

In this example, scandir() retrieves the list of items in the specified directory, including .
(current directory) and .. (parent directory). The loop then iterates through the array and
prints each item's name, excluding . and ...

If you want to filter the results to only display directories, you can use the is_dir()
function:

$directory = "path/to/directory"; // Replace with the actual directory path

$contents = scandir($directory);

foreach ($contents as $item) {

if ($item != "." && $item != ".." && is_dir($directory . "/" . $item)) {

echo $item . "<br>";

}}

48 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT


WEB TECHNOLOGIES Prepared By: T.V.GOPALA KRISHNA, ASSOC.PROF & HOD

In this modified example, the is_dir() function is used to check if each item is a directory
before printing it.

Remember to replace "path/to/directory" with the actual path to the directory you want to
list. Additionally, ensure that you have the necessary file system permissions to access the
directory and its contents.

@@@@@@@@@@@@@@@ALL THE BEST@@@@@@@@@@@@@@@@

49 | P a g e LOYOLA INSTIT UT E OF T ECHNOLOGY AND MANAGEMENT

You might also like