WT Unit-5
WT Unit-5
WT Unit-5
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:
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.
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>
</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.
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
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;
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.
$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:
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:
$number = 42;
$negativeNumber = -10;
$pi = 3.14;
$temperature = -12.5;
$name = "Alice";
$isStudent = true;
$hasAccount = false;
class Person
public $name;
public $age;
$person->name = "Alice";
$person->age = 30;
$emptyValue = null;
function sayHello($name)
$functionRef = 'sayHello';
10.Iterable (PHP 7.1+): Represents a data structure that can be looped through, such
as arrays and objects implementing the Traversable interface.
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:
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.
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(
);
$person = [
];
Multidimensional Arrays:
$matrix = array(
array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9)
);
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.
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:
$name = "Alice";
String Concatenation:
$firstName = "John";
$lastName = "Doe";
String Length:
You can find the length (number of characters) of a string using the strlen() function:
Substring:
$text = "The quick brown fox jumps over the lazy dog";
String Functions:
PHP provides a rich set of functions for working with strings, such as:
trim(): Removes whitespace or specified characters from the beginning and end of
a string.
\\: Backslash
\n: Newline
\t: Tab
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:
+: Addition
-: Subtraction
*: Multiplication
/: Division
%: Modulus (remainder)
Php:
$a = 10;
$b = 5;
$sum = $a + $b; // 15
$difference = $a - $b; // 5
$product = $a * $b; // 50
$quotient = $a / $b; // 2
$remainder = $a % $b; // 0
2. Assignment Operators:
=: Assign
$x = 5;
$y = 3;
$x += $y; // $x is now 8
$x *= $y; // $x is now 15
$x /= $y; // $x is now 5
$x %= $y; // $x is now 2
3. Comparison Operators:
==: Equal to
$a = 5;
$b = 3;
4. Logical Operators:
|| or or: Logical OR
$condition1 = true;
$condition2 = false;
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:
$result = (5 + 3) * 2; // Evaluates to 16
4. Function Call Expression: Calling a function and using its return value.
$result = ($a > 0) && ($b < 10); // Evaluates to true or false
$age = 25;
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.
$age = 25;
} else
2. elseif and else Statements: The elseif and else statements are used in combination
with if to create multiple conditional branches.
$score = 75;
echo "Excellent!";
echo "Good!";
} else
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":
case "Wednesday":
case "Thursday":
case "Friday":
break;
case "Saturday":
case "Sunday":
break;
default:
3. for Loop: The for loop allows you to execute a block of code a specific number of
times.
4. while Loop: The while loop executes a block of code as long as a condition is true.
$counter = 0;
$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
$x++;
6. foreach Loop: The foreach loop is used to iterate through elements in an array or
other iterable objects
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.
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.
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)
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.
Returning Values:
return $a + $b;
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.
return $x * $y;
You can provide default values for parameters. If a value is not provided when the
function is called, the default value will be used.
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:
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.
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:
<!DOCTYPE html>
<html>
<head>
<title>Form Example</title>
</head>
<body>
<label for="name">Name:</label>
<br>
<label for="email">Email:</label>
<br>
</form>
</body>
</html>
In this example, the form submits data using the POST method to a file named
"process_form.php".
<!DOCTYPE html>
<html>
<head>
<title>Form Processing</title>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
} else
?>
</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:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Gender:</p>
<label>
</label>
<label>
</label>
<label>
</label>
<br>
</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>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST["gender"])) {
$selectedGender = $_POST["gender"];
} else {
} else {
?>
</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.
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.
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>
</head>
<body>
<h2>Shopping List</h2>
<ul>
<li>Apples</li>
<li>Bananas</li>
<li>Oranges</li>
</ul>
</body>
</html>
An ordered list is a numbered list of items. Like unordered lists, each item is enclosed in
an <li> element.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<ol>
</ol>
</body>
</html>
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>
</head>
<body>
<h2>Glossary</h2>
<dl>
<dt>HTML</dt>
<dt>CSS</dt>
</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 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:
Create an HTML form that includes an <input> element with type="file" to allow users
to choose and upload a file.
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
</form>
</body>
</html>
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") {
$targetFile = $targetDirectory .
basename($_FILES["uploadedFile"]["name"]);
$uploadSuccess =
move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $targetFile);
if ($uploadSuccess)
} else
?>
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.
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:
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.
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.
Store uploaded files outside of the web root directory to prevent direct access.
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.
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:
// Create a connection
// Check connection
if ($conn->connect_error) {
Once the connection is established, you can perform various database operations using the
$conn object.
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " .
$row["email"] . "<br>";
} else {
$conn->close();
Using PDO:
try {
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$result = $conn->query($sql);
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " .
$row["email"] . "<br>";
$conn = null;
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 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();
INSERT Query:
$email = "john@example.com";
} else
$mysqli->close();
Using PDO:
1. SELECT Query:
try {
$pdo->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$result = $pdo->query($query);
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " .
$row["email"] . "<br>";
$pdo = null;
INSERT Query:
try {
$pdo->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$email = "jane@example.com";
$stmt = $pdo->prepare($query);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
if ($stmt->execute()) {
} else {
$pdo = null;
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.
1. SELECT Query:
} 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.
SELECT Query:
try {
$pdo = new PDO("mysql:host=$servername;dbname=$database", $username,
$password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo = null;
} catch (PDOException $e)
{
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.
1. SELECT Query:
phpCopy code
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.
1. SELECT Query:
phpCopy code
Name: " . $row["name"] . " - Email: " . $row["email"] . "<br>"; } $pdo = null; } catch
(PDOException $e) { echo "Error: " . $e->getMessage(); }
In the PDO code above, the foreach loop iterates over the result set directly, treating each
row as an associative array by default.
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, 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();
$username = $_SESSION['username'];
4. Destroy a session:
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:
2. Retrieve a cookie:
$username = $_COOKIE['username'];
3. Delete a cookie:
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:
file_put_contents('file.txt', $data);
3. Appending to a file:
if (file_exists('file.txt'))
// File exists
5. Deleting a file:
unlink('file.txt');
$targetDirectory = 'uploads/';
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.
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";
if ($fileHandle)
} else
The $mode parameter specifies the mode in which the file should be opened:
"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";
if ($fileHandle)
while (!feof($fileHandle))
$line = fgets($fileHandle);
echo $line;
fclose($fileHandle);
} else
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";
if ($fileHandle)
fwrite($fileHandle, $data);
fclose($fileHandle);
} else
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 are common operations before and after working with file
contents.
fclose($fileHandle);
fclose($binaryFileHandle);
Reading text from a file can be done using functions like fread() or fgets().
while (!feof($fileHandle))
$line = fgets($fileHandle);
echo $line;
} fclose($fileHandle);
Reading text from a file can be done using functions like fread() or fgets().
while (!feof($fileHandle))
$line = fgets($fileHandle);
echo $line;
fclose($fileHandle);
fwrite($fileHandle, $data);
fclose($fileHandle);
fwrite($fileHandle, $data);
fclose($fileHandle);
Reading binary data from a file can be done using functions like fread().
fclose($binaryFileHandle);
Writing binary data to a file can be done using functions like fwrite().
fwrite($binaryFileHandle, $data);
fclose($binaryFileHandle);
Deleting Files:
if (unlink("file_to_delete.txt"))
} else
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:
$contents = scandir($directory);
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:
$contents = scandir($directory);
}}
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.