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

PHP NEW UNIT - 2

The document provides an overview of arrays in PHP, detailing the three types: indexed, associative, and multidimensional arrays, along with examples and common array functions. It also covers user-defined functions, their syntax, and various types including functions with parameters, return values, and recursion. Additionally, it explains the use of constants and file inclusion in PHP, highlighting the differences between include and require statements.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

PHP NEW UNIT - 2

The document provides an overview of arrays in PHP, detailing the three types: indexed, associative, and multidimensional arrays, along with examples and common array functions. It also covers user-defined functions, their syntax, and various types including functions with parameters, return values, and recursion. Additionally, it explains the use of constants and file inclusion in PHP, highlighting the differences between include and require statements.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Web Devlopment Using PHP UNIT – II M.T.

CHAUDHARY

 Array in php
 In PHP, an array is a data structure that can hold multiple values under
a single name. It can be used to store a list of items, where each item is
associated with a key.
 PHP array is an ordered map (contains value on the basis of key). It is
used to hold multiple values of similar type in a single variable.
 An array is a data structure that stores one or more data values having
some relation among them, in a single variable. For example, if you
want to store the marks of 10 students in a class, then instead of
de ining 10 different variables, it’s easy to de ine an array of 10
length.PHP supports three types of arrays:
1. Indexed Arrays
 Arrays with numeric keys.
 An array which is a collection of values only is called an indexed
array
 PHP index is represented by number which starts from 0. We can
store number, string and object in the PHP array. All PHP array
elements are assigned to an index number by default
Example
$fruits = ["Apple", "Banana", "Cherry"];
// or
$fruits = array("Apple", "Banana", "Cherry");
echo $fruits[0]; // Outputs: Apple
2. Associative Arrays
 Arrays with named keys.
 If the array is a collection of key-value pairs, it is called as an
associative array. The key component of the pair can be a
number or a string, whereas the value part can be of any type.
Associative arrays store the element values in association with
key values rather than in a strict linear index order.
Example:
$person = [
"name" => "John",
"age" => 30,
"city" => "New York"];
// or
$person = array(
"name" => "John",

SHRI ADARSH BCA COLLEGE , RADHANPUR 1


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

"age" => 30,


"city" => "New York"
);
echo $person["name"]; // Outputs: John
3. Multidimensional Arrays
 Arrays that contain other arrays.
 If each value in either an indexed array or an associative array
is an array itself, it is called a multi dimensional array. Values
are accessed using multiple indices
Example
$students = [
["John", 25, "A"],
["Jane", 22, "B"],
["Tom", 24, "A"]
];
echo $students[1][0]; // Outputs: Jane
// Associative multidimensional array
$employees = [
[
"name" => "Alice",
"age" => 30,
"position" => "Manager"
],
[
"name" => "Bob",
"age" => 25,
"position" => "Developer"
]
];
echo $employees[0]["position"]; // Outputs: Manager
 Array Functions
 Here’s a comprehensive list of PHP array functions with
examples for better understanding:
1. count()
 Counts the number of elements in an array.
$fruits = ["Apple", "Banana", "Cherry"];
echo count($fruits); // Outputs: 3
2. array_push()
 Adds one or more elements to the end of an array.
$fruits = ["Apple", "Banana"];
array_push($fruits, "Cherry", "Date");

SHRI ADARSH BCA COLLEGE , RADHANPUR 2


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

print_r($fruits);
// Output: Array ( [0] => Apple [1] => Banana [2] => Cherry [3] =>
Date )
3. array_pop()
$fruits = ["Apple", "Banana", "Cherry"];
$last = array_pop($fruits);
echo $last; // Outputs: Cherry
print_r($fruits);
// Output: Array ( [0] => Apple [1] => Banana )
4. in_array()
$fruits = ["Apple", "Banana", "Cherry"];
if (in_array("Banana", $fruits)) {
echo "Banana is in the array.";
} else {
echo "Banana is not in the array.";
}
// Output: Banana is in the array.
5. array_keys()
 Returns all the keys of an array.
$person = ["name" => "John", "age" => 30, "city" => "New
York"];
$keys = array_keys($person);
print_r($keys);
// Output: Array ( [0] => name [1] => age [2] => city )
6. array_values()
 Returns all the values of an array.
$person = ["name" => "John", "age" => 30, "city" => "New York"];
$values = array_values($person);
print_r($values);
// Output: Array ( [0] => John [1] => 30 [2] => New York )
7. array_filter()
 Filters elements of an array using a callback
function.
$numbers = [1, 2, 3, 4, 5];
$filtered = array_filter($numbers, fn($num) => $num > 3);
print_r($filtered);
// Output: Array ( [3] => 4 [4] => 5 )
8. array_slice()
 Extracts a portion of an array.
$fruits = ["Apple", "Banana", "Cherry", "Date", "Elderberry"];
$slice = array_slice($fruits, 1, 3);

SHRI ADARSH BCA COLLEGE , RADHANPUR 3


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

print_r($slice);
// Output: Array ( [0] => Banana [1] => Cherry [2] => Date )
9. array_splice()
 Removes and replaces a portion of an array.
$fruits = ["Apple", "Banana", "Cherry", "Date"];
array_splice($fruits, 1, 2, ["Mango", "Pineapple"]);
print_r($fruits);
// Output: Array ( [0] => Apple [1] => Mango [2] =>
Pineapple [3] => Date )
10. array_reverse()
 Reverses the order of elements in an array.
$fruits = ["Apple", "Banana", "Cherry"];
$reversed = array_reverse($fruits);
print_r($reversed);
// Output: Array ( [0] => Cherry [1] => Banana [2] =>
Apple )
11. array_unique()
 Removes duplicate values from an array.
$numbers = [1, 2, 2, 3, 4, 4, 5];
$unique = array_unique($numbers);
print_r($unique);
Output: Array([0] => 1 [1] => 2 [3] => 3 [4] => 4 [6] => 5 )
12. sort()
 Sorts an array in ascending order.
$numbers = [4, 2, 8, 1];
sort($numbers);
print_r($numbers);
// Output: Array ( [0] => 1 [1] => 2 [2] => 4 [3] => 8 )
13. array_combine()
 Creates an associative array by combining two
arrays: one for keys and the other for values
$keys = ["name", "age", "city"];
$values = ["John", 30, "New York"];
$combined = array_combine($keys, $values);
print_r($combined);
// Output: Array ( [name] => John [age] => 30 [city] =>
New York )
14. array_map()
 Applies a callback function to each element of an
array
$numbers = [1, 2, 3, 4];

SHRI ADARSH BCA COLLEGE , RADHANPUR 4


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

$squared = array_map(fn($num) => $num * $num,


$numbers);
print_r($squared);
// Output: Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 )

 PHP Functions
1. User-defined functions
 In PHP, user-de ined functions allow you to create your own
functions to perform speci ic tasks. A user-de ined function is
created using the function keyword, followed by a name,
parameters (optional), and the function body.
 Meaningful Names: Use descriptive and
meaningful function names that re lect the purpose
of the function.
 Small and Focused Functions: Functions should
perform a single task and be as small as possible.
 Use Parameters: Avoid using global variables
inside functions; use parameters instead to pass
data.
 Avoid Side Effects: Functions should avoid
modifying global variables unless absolutely
necessary.
 Syntax of User-Defined Functions
function functionName($parameter1, $parameter2) {
// Code to execute
return $result; // Optional return
}
 Key points
 Function name: The name must be a valid identifier and
should follow PHP naming conventions.
 Parameters: Functions can accept parameters
(arguments) to work with.
 Return value: Functions may return a value using the
return keyword. If no return value is provided, the
function will return NULL by default.
1. Simple Function without Parameters
// Function without parameters
function greet() {
echo "Hello, World!";
}

SHRI ADARSH BCA COLLEGE , RADHANPUR 5


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

// Calling the function


greet(); // Output: Hello, World!
2. Function with Parameters
// Function with parameters
function greetPerson($name) {
echo "Hello, " . $name . "!";
}
// Calling the function with a parameter
greetPerson("Alice"); // Output: Hello, Alice!
greetPerson("Bob"); // Output: Hello, Bob!
3. Function with Return Value
// Function that returns a value
function add($a, $b) {
return $a + $b;
}
// Calling the function and storing the result
$result = add(5, 3);
echo $result; // Output: 8
4. Function with Default Parameter Values
 You can define default values for function parameters. If no
argument is provided for those parameters, the default value is
used
// Function with default values
function greetPerson($name = "Guest") {
echo "Hello, " . $name . "!";
}
// Calling the function with and without argument
greetPerson("John"); // Output: Hello, John!
greetPerson(); // Output: Hello, Guest!
5. Function with Variable Number of Arguments (Using ...)
 You can create a function that accepts a variable number of
arguments using the ... (variadic) operator
// Function with a variable number of arguments
function sumNumbers(...$numbers) {
$sum = 0;
foreach ($numbers as $num) {
$sum += $num;
}
return $sum;
}
// Calling the function with different numbers of arguments

SHRI ADARSH BCA COLLEGE , RADHANPUR 6


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

echo sumNumbers(1, 2, 3); // Output: 6


echo sumNumbers(4, 5, 6, 7, 8); // Output: 30
6. Function with Reference Parameter
You can pass a parameter by reference, which allows the
function to modify the original variable's value.
// Function with reference parameter
function increment(&$number) {
$number++;
}
// Calling the function with a reference
$value = 10;
increment($value);
echo $value; // Output: 11 (the value is modified)
7. Recursive Function
 A recursive function is a function that calls itself. It's commonly
used for tasks that can be broken down into smaller, similar
tasks, like calculating factorials
// Recursive function to calculate factorial
function factorial($n) {
if ($n <= 1) {
return 1;
}
return $n * factorial($n - 1);
}
// Calling the recursive function
echo factorial(5); // Output: 120
8. Function Returning an Array
 A function can return an array as a result.
// Function returning an array
function getFruits() {
return ["Apple", "Banana", "Cherry"];
}
// Calling the function and storing the result
$fruits = getFruits();
print_r($fruits);
// Output: Array ( [0] => Apple [1] => Banana [2] => Cherry )
 Miscellaneous Functions
1. Define()
 The define() function defines a constant.
 Define a case-sensitive constant

SHRI ADARSH BCA COLLEGE , RADHANPUR 7


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

 Constants are much like variables, except for the


following differences:
 A constant's value cannot be changed after it is set
 Constant names do not need a leading dollar sign ($)
 Constants can be accessed regardless of scope
 Constant values can only be strings and numbers
 Syntax
define(name,value,case_insensitive)
<?php
define("GREETING","Hello you! How are you today?");
echo constant("GREETING");
?>
Output
Hello you! How are you today?
2. Include() or require()
 In PHP, the include statement is used to include and evaluate the
contents of one PHP file in another. It allows you to reuse code
across multiple files, improving maintainability and
organization.
 The include (or require) statement takes all the
text/code/markup that exists in the specified file and copies it
into the file that uses the include statement.
 It is possible to insert the content of one PHP file into another
PHP file (before the server executes it), with the include or
require statement.
 Key Points
File Inclusion: The contents of the included file are
copied into the script where the include statement
appears.
Error Handling:
If the file cannot be included, PHP generates a warning
But continue executing the script.
Relative and Absolute Paths: You can use relative paths
(e.g., include 'folder/file.php';) or absolute paths (e.g., include
'/var/www/html/file.php';)
Syntax
include ('file name');
Example
Suppose you have a file named header.php with the
following content

SHRI ADARSH BCA COLLEGE , RADHANPUR 8


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

header.php:
<?php
echo "<h1>Welcome to My Website</h1>";
?>
You can include this file in another script as follows
main.php
<?php
include 'header.php';
echo "<p>This is the main content of the page.</p>";
?>
Output
Welcome to My Website
This is the main content of the page.
Difference between include() and require()
 require will produce a fatal error (E_COMPILE_ERROR) and stop the
script
 include will only produce a warning (E_WARNING) and the script will
continue

3. include_once()
 The include_once statement in PHP is similar to
include, but it ensures that the specified file is
included only once during the script execution. This
prevents errors caused by multiple inclusions of the
same file, such as re-declaring classes, functions, or
variables
Syntax
include_once ('file name');
Example
file1.php
<?php
echo "This is file1.php.<br>";
?>
main.php
<?php
include_once 'file1.php';
include_once 'file1.php'; // This will not include file1.php again
// This will also not cause an error.
echo "This is the main script.";
?>
Output

SHRI ADARSH BCA COLLEGE , RADHANPUR 9


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

This is file1.php.
This is the main script.
 Key Points
1. Avoids Multiple Inclusions
 Ensures that the file is included only once, even if
include_once is called multiple times
2. Error Handling
 If the file is not found, include_once generates a
warning but allows script execution to continue

Key Difference between include_once() and require_once()

Include_once() Require_once()
Generates a warning if the Generates a fatal error if the
file cannot be included but file cannot be included and
continues script execution stops script execution
The script continues to The script halts immediately if
execute even if the file is the file is missing or cannot be
missing or cannot be included included
Use when the file is not Use when the file is essential
critical to the application, and for the application to function
the script can proceed correctly
without it

3. Header()
 The header() function in PHP is used to send raw
HTTP headers to the browser before any output is
sent. It allows you to manipulate HTTP headers,
such as redirection, content type, cache control, and
more.
 Common Uses of header()
1. Redirecting to Another Page
<?php
header("Location: https://www.example.com");
exit(); // Ensure no further code is executed
?>
The Location header tells the browser to navigate to a
different URL.
Always use exit() after redirection to stop further script
execution
2. Setting Content Type

SHRI ADARSH BCA COLLEGE , RADHANPUR 10


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

<?php
header("Content-Type: application/json");
echo json_encode(["message" => "Hello, world!"]);
?>
Changes the Content-Type of the response. Common values:
text/html: Default for HTML content.
application/json: For JSON responses.
text/plain: For plain text responses
3. Forcing File Download
<?php
$file = 'example.pdf';
header("Content-Disposition:attachment;
filename=\"$file\"");
header("Content-Type: application/pdf");
readfile($file);
exit();
?>
The Content-Disposition header forces the browser to
download the file instead of displaying it
4. Custom HTTP Response Codes
<?php
header("HTTP/1.1 404 Not Found");
echo "Page not found";
exit();
?>
Sends a custom HTTP status code like 404 Not Found or 500
Internal Server Error
Key Notes
 The header() function must be called before any
output (e.g., echo, print) is sent to the browser.
 Otherwise, you get a "Headers already sent" error
 You can send multiple headers by calling header()
multiple times
5. Die()
 The die() function in PHP is used to terminate the
execution of a script immediately. Optionally, it can
output a message before stopping the execution. It is an
alias of the exit() function, and both work identically
1. Stopping Script Execution
 When something critical fails, you can use die() to stop
the script immediately

SHRI ADARSH BCA COLLEGE , RADHANPUR 11


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

<?php
if (!file_exists("data.txt")) {
die("Error: File not found!");
}
echo "This line will not be executed if the file is missing.";
?>
2. Database Connection Failure
<?php
$conn = mysqli_connect("localhost", "username", "password",
"database");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully.";
?>
3. Debugging
 You can use die() to output variable data and stop the
script for debugging purposes
<?php
$data = ["name" => "Alice", "age" => 30];
die(print_r($data, true)); // Output the array and stop execution
?>
Key Notes
die() and exit() are interchangeable. Use whichever is more
readable in context
After calling die(), no code in the script will be executed
die() is often used for basic error handling, such as halting a
script if a file is missing or a database connection fails

 PHP String Functions


1. strlen()
 Returns the length of a string
<?php
$str = "Hello, World!";
echo "Length of the string: " . strlen($str);
?>
Output
Length of the string: 13
2. strrev()
 Reverses a string
<?php

SHRI ADARSH BCA COLLEGE , RADHANPUR 12


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

$str = "Hello, PHP!";


echo "Reversed string: " . strrev($str);
?>
Output
Reversed string: !PHP ,olleH
3. strpos()
 Finds the position of the irst occurrence of a substring
<?php
$str = "Hello, World!";
$pos = strpos($str, "World");
echo "Position of 'World': " . $pos;
?>
Output
Position of 'World': 7
4. str_replace()
 Replaces all occurrences of a search string with a
replacement
<?php
$str = "Hello, World!";
$newStr = str_replace("World", "PHP", $str);
echo $newStr;
?>
Output
Hello, PHP!
5. strtolower()
 Converts a string to lowercase.
<?php
$str = "HELLO, WORLD!";
echo strtolower($str);
?>
Output
hello, world!
6. strtoupper()
 Converts a string to uppercase.
<?php
$str = "hello, world!";
echo strtoupper($str);
?>
Output
HELLO, WORLD!
7. uc irst()

SHRI ADARSH BCA COLLEGE , RADHANPUR 13


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

 Converts the irst character of a string to uppercase


<?php
$str = "hello, world!";
echo ucfirst($str);
?>
Output
Hello, world!
8. lc irst()
 Converts the irst character of a string to lowercase
<?php
$str = "Hello, World!";
echo lcfirst($str);
?>
Output
hello, World!
9. substr()
 Returns a portion of a string
<?php
$str = "Hello, World!";
echo substr($str, 7, 5); // Extracts "World"
?>
Output
World
10. explode()
 Splits a string into an array by a speci ied delimiter
<?php
$str = "Apple,Orange,Banana";
$arr = explode(",", $str);
print_r($arr);
?>
Output
Array
(
[0] => Apple
[1] => Orange
[2] => Banana
)
11. implode()
 Joins array elements into a string using a speci ied
delimiter
<?php

SHRI ADARSH BCA COLLEGE , RADHANPUR 14


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

$arr = ["Apple", "Orange", "Banana"];


$str = implode(", ", $arr);
echo $str;
?>
Output
Apple, Orange, Banana
12. str_repeat()
 Repeats a string a speci ied number of times
<?php
$str = "PHP ";
echo str_repeat($str, 3);
?>
Output
PHP PHP PHP
 PHP Date/Time Functions
 PHP provides a wide range of date and time functions
to handle dates, times, and their formatting. Below are
some commonly used PHP date/time functions with
examples
1. date()
 Formats a timestamp as a string
<?php
// Get the current date and time
echo date("Y-m-d H:i:s"); // Outputs: 2024-12-18
15:30:00
?>
2. time()
 Returns the current Unix timestamp (number of seconds
since January 1, 1970)
<?php
echo time(); // Outputs: 1702904200 (example
timestamp)
?>
3. mktime()
 Returns the Unix timestamp for a speci ic date and time
<?php
// Get the Unix timestamp for 1st January 2025 at
12:00:00
$timestamp = mktime(12, 0, 0, 1, 1, 2025);
echo date("Y-m-d H:i:s", $timestamp); // Outputs:
2025-01-01 12:00:00

SHRI ADARSH BCA COLLEGE , RADHANPUR 15


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

?>
4. getdate()
 Returns an associative array containing date information
for a given timestamp
<?php
$date_info = getdate();
print_r($date_info);
?>
5. date_default_timezone_set()
 Sets the default timezone for all date/time functions
<?php
// Set the timezone to New York
date_default_timezone_set('America/New_York');
// Get the current date and time in New York
echo date("Y-m-d H:i:s");
?>
6. checkdate()
 Checks if a given date is valid
<?php
$month = 2;
$day = 29;
$year = 2024; // Leap year
if (checkdate($month, $day, $year)) {
echo "Valid date.";
} else {
echo "Invalid date.";
}
?>
Output
Valid date.
7. idate()
 Returns a speci ic part of a date as an integer (e.g., year,
month, day)
<?php
$timestamp = time();
echo idate("Y", $timestamp); // Outputs: 2024
echo idate("m", $timestamp); // Outputs: 12
echo idate("d", $timestamp); // Outputs: 18
?>
8. date_create()
 Creates a new DateTime object

SHRI ADARSH BCA COLLEGE , RADHANPUR 16


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

<?php
$date = date_create("2024-12-18");
echo date_format($date, "Y-m-d H:i:s"); // Outputs:
2024-12-18 00:00:00
?>
9. date_add()
 Adds a time interval to a DateTime object
<?php
$date = date_create("2024-12-18");
date_add($date,
date_interval_create_from_date_string("10 days"));
echo date_format($date, "Y-m-d"); // Outputs: 2024-
12-28
?>
10. date_diff()
 Calculates the difference between two DateTime objects
<?php
$date1 = date_create("2024-12-18");
$date2 = date_create("2024-12-25");
$diff = date_diff($date1, $date2);
echo $diff->format("%R%a days"); // Outputs: +7 days
?>
 PHP Math Functions
 PHP provides a variety of math functions that allow you
to perform mathematical operations such as rounding,
inding the maximum or minimum values, working
with random numbers, and performing more complex
calculations. Below are some of the commonly used
PHP math functions with examples
1. abs()
 Returns the absolute value of a number
<?php
echo abs(-5); // Outputs: 5
echo abs(5); // Outputs: 5
?>
2. round()
 Rounds a loating-point number to the nearest integer or
to a speci ic number of decimal places
<?php
echo round(3.456); // Outputs: 3
echo round(3.456, 2); // Outputs: 3.46

SHRI ADARSH BCA COLLEGE , RADHANPUR 17


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

echo round(3.456, 1); // Outputs: 3.5


?>
3. ceil()
 Rounds a number up to the nearest integer, regardless of
its decimal part
<?php
echo ceil(3.2); // Outputs: 4
echo ceil(3.9); // Outputs: 4
?>
4. loor()
 Rounds a number down to the nearest integer, regardless
of its decimal part
<?php
echo floor(3.7); // Outputs: 3
echo floor(3.2); // Outputs: 3
?>.
5. pow()
 Returns the result of raising a number to the power of
another number
<?php
echo pow(2, 3); // Outputs: 8 (2^3)
?>
6. sqrt()
<?php
echo sqrt(16); // Outputs: 4
echo sqrt(25); // Outputs: 5
?>
7. min() and max()
 Returns the minimum and maximum value from a set of
values
<?php
echo min(1, 2, 3, 4, 5); // Outputs: 1
echo max(1, 2, 3, 4, 5); // Outputs: 5
?>
8. rand()
 Generates a random integer. You can optionally specify a
range for the random number
<?php
echo rand(); // Outputs a random number
between 0 and PHP_INT_MAX

SHRI ADARSH BCA COLLEGE , RADHANPUR 18


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

echo rand(1, 100); // Outputs a random number


between 1 and 100
?>
9. exp()
 Returns the exponentiation of Euler's number (e) raised to
the power of a number
<?php
echo exp(1); // Outputs: 2.718281828459 (e^1)
?>
10. fmod()
 Returns the remainder of the division of two numbers
( loating-point division)
<?php
echo fmod(10, 3); // Outputs: 1 (remainder of 10
divided by 3)
?>
11. is_numeric()
 Checks if a value is a valid number or numeric string
<?php
echo is_numeric("123"); // Outputs: true
echo is_numeric("12.34"); // Outputs: true
echo is_numeric("Hello"); // Outputs: false
?>
 PHP Global Variables

 In PHP, global variables are variables that are


accessible from any part of the script, but their
behavior depends on the scope in which they are used.
PHP provides a set of prede ined global variables as
well as the ability to de ine custom global variables
1. $_GLOBALS
 An associative array containing all global variables in the
current script
<?php
$x = 10;
$y = 20;
function add() {
$GLOBALS['z']=$GLOBALS['x']+$GLOBALS['y'];
}
add();
echo $z; // Outputs: 30 ?>

SHRI ADARSH BCA COLLEGE , RADHANPUR 19


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

2. $_SERVER
 Contains information about headers, paths, and script
locations
<?php
echo $_SERVER['PHP_SELF']; // Current script
name
echo $_SERVER['SERVER_NAME']; // Server
name
echo $_SERVER['HTTP_HOST']; // Host name
?>
3. $_REQUEST
 Used to collect data from HTML forms, combining data
from $_GET, $_POST, and $_COOKIE
<?php
// Accessing form data (GET or POST)
echo $_REQUEST['username'];
?>
4. $_GET
 Contains data sent via the URL query string
<?php
// URL: example.com?name=John
echo $_GET['name']; // Outputs: John
?>
5. $_POST
 Contains data sent via HTTP POST
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
echo $_POST['email'];
}
?>
6. $_FILES
 Used to handle ile uploads
<?php
if ($_FILES['file']['error'] == 0) {
echo "File uploaded: " . $_FILES['file']['name'];
}
?>
7. $_COOKIE
 Contains data stored in cookies
<?php

SHRI ADARSH BCA COLLEGE , RADHANPUR 20


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

// Setting a cookie
setcookie("user", "John", time() + 3600);
// Accessing a cookie
echo $_COOKIE['user']; // Outputs: John
?>
8. $_SESSION
 Contains session variables
<?php
session_start();
$_SESSION['username'] = "John";
echo $_SESSION['username']; // Outputs: John
?>
9. $_ENV
 Contains environment variables
<?php
echo $_ENV['HOME']; // Displays the value of the
'HOME' environment variable (if set)
?>
 Working with Forms in PHP
 PHP Form handling
 PHP form handling refers to the process of capturing
and processing data submitted through an HTML form.
PHP can handle form data sent via the GET or POST
methods
Create an HTML Form: Use HTML to design the
form that collects user input.
Set the Form's Action and Method:
Action: Specifies the PHP script where the form
data will be sent.
Method: Defines how the data is sent (GET or POST).
Access Form Data in PHP: Use PHP's superglobal
arrays:
$_GET: For forms submitted using the GET
method.
$_POST: For forms submitted using the POST
method.
<!DOCTYPE html>
<html>
<body>
<h2>Simple Form</h2>

SHRI ADARSH BCA COLLEGE , RADHANPUR 21


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

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


<label for="name">Name:</label><br>
<input type="text" id="name" >
<label for="email">Email:</label><br>
<input type="email" id="email"
name="email"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
 GET Vs POST

GET POST
Appends data to the Sends data in the
URL (visible) request body (not
visible)
Limited to 2048 No character limit.
characters (browser-
dependent)
Less secure; data More secure; data
visible in the URL hidden from URL

 Accessing form data


In PHP, you can access form data using superglobal arrays like
$_GET and $_POST, depending on the form's submission method. These
arrays contain key-value pairs, where the keys correspond to the name
attributes of the form elements
Steps to Access Form Data in PHP
HTML FORM
1. HTML Form Creation
Define the form elements with a name attribute.
Specify the submission method (GET or POST) in the <form>
tag
2. PHP Script to Process Data
Use $_GET for forms with method="get".
Use $_POST for forms with method="post"
Example: Accessing Form Data Using POST
<!DOCTYPE html>
<html>

SHRI ADARSH BCA COLLEGE , RADHANPUR 22


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

<body>
<form action="process.php" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
PHP Script (process.php)
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Access form data
$username = $_POST["username"];
$password = $_POST["password"];
// Display data
echo "Username: " . htmlspecialchars($username) . "<br>";
echo "Password: " . htmlspecialchars($password) . "<br>";
}
?>
 Use of Hidden fields to save State
Hidden fields in an HTML form are used to pass information
from one page to another without displaying it to the user. These fields
are particularly useful in maintaining the state of an application
during navigation or when handling multiple forms across pages
How Hidden Fields Work
A hidden field is created using the <input type="hidden"> tag in
an HTML form.
Data stored in the hidden field is submitted to the server along
with the form.
The server can access the value of the hidden field through PHP
superglobals ($_POST or $_GET)
Common Use Cases
1. Maintaining State Between Pages
 Hidden fields can store data, such as user input or session
identifiers, that needs to persist across multiple pages
 Carrying Context Information

SHRI ADARSH BCA COLLEGE , RADHANPUR 23


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

 Pass context information, like user IDs or preferences,


from one form submission to another
2. Multi-Step Forms
 Hidden fields are often used to carry data forward in multi-step forms
 Example: Using Hidden Fields to Save State
<!DOCTYPE html>
<html>
<body>
<form action="process.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<!-- Hidden Field -->
<input type="hidden" name="user_id" value="12345">
<input type="submit" value="Submit">
</form>
</body>
</html>
PHP Script (process.php)
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Access form data
$name = htmlspecialchars($_POST["name"]);
$user_id = htmlspecialchars($_POST["user_id"]);
echo "Name: " . $name . "<br>";
echo "User ID: " . $user_id . "<br>";
}
?>
 PHP Form validating
 Form validation is a process of checking that user input is correct and
safe before processing it. PHP can validate form data on both the
client-side (using JavaScript) and the server-side. Server-side
validation is crucial because it ensures that malicious users cannot
bypass validation by disabling JavaScript
Steps for PHP Form Validation
 Create an HTML Form:
Design the form with the required input fields.
Use the name attribute for each input to access the data in PHP.
 Validate Form Data in PHP:

SHRI ADARSH BCA COLLEGE , RADHANPUR 24


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

Ensure all required fields are filled.


Check for valid data formats (e.g., email, numbers).
Sanitize data to remove potentially harmful input.
 Display Validation Errors:
If input is invalid, display an error message near the relevant field.
 Process Valid Data:
If all data is valid, process or store it as needed
HTML Form
<!DOCTYPE html>
<html>
<body>
<h2>PHP Form Validation</h2>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>"
method="post">
Name: <input type="text" name="name">
<span style="color:red;">*<?php echo $nameErr ?? '';
?></span><br><br>
Email: <input type="text" name="email">
<span style="color:red;">* <?php echo $emailErr ?? '';
?></span><br><br>
Age: <input type="text" name="age">
<span style="color:red;">* <?php echo $ageErr ?? '';
?></span><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
PHP Validation Script
<?php
$name = $email = $age = "";
$nameErr = $emailErr = $ageErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate Name
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = sanitizeInput($_POST["name"]);
if (!preg_match("/^[a-zA-Z-' ]*$/", $name)) {
$nameErr = "Only letters and spaces allowed";

SHRI ADARSH BCA COLLEGE , RADHANPUR 25


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

}
}
// Validate Email
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = sanitizeInput($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
// Validate Age
if (empty($_POST["age"])) {
$ageErr = "Age is required";
} else {
$age = sanitizeInput($_POST["age"]);
if (!filter_var($age, FILTER_VALIDATE_INT)) {
$ageErr = "Age must be a number";
}
}
// If no errors, process data
if (empty($nameErr) && empty($emailErr) && empty($ageErr)) {
echo "Name: $name<br>Email: $email<br>Age: $age";
}
}
// Function to sanitize input
function sanitizeInput($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Explanation
 Validate Each Field:
 Use empty() to check if the field is filled.
 Use regular expressions (e.g., preg_match()) or built-in PHP functions
(e.g., filter_var()) for specific formats.

SHRI ADARSH BCA COLLEGE , RADHANPUR 26


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

 Sanitize Input:
 Use htmlspecialchars() to convert special characters to HTML entities
and prevent XSS attacks.
 Use trim() to remove extra spaces.
 Display Errors:
 Use variables like $nameErr to store error messages for each field.
 Display these messages near the corresponding input fields.
 Process Valid Data:
 If all inputs are valid, proceed to process or save the data

 PHP File upload


One of the common features required in a typical PHP web
application is the provision of letting the user upload files. Uploading
files from a client is very easy in PHP
The process of uploading a file follows these steps
 The user opens the page containing a HTML form featuring a text files,
a browse button and a submit button.
 The user clicks the browse button and selects a file to upload from the
local PC.
 The full path to the selected file appears in the text filed then the user
clicks the submit button.
 The selected file is sent to the temporary directory on the server.
 The PHP script that was specified as the form handler in the form's
action attribute checks that the file has arrived and then copies the file
into an intended directory.
 The PHP script confirms the success to the user.
Create the HTML Form
he form uses the POST method and enctype="multipart/form-data" to
handle file uploads
<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form action="upload.php" method="post"
enctype="multipart/form-data">
<label for="fileUpload">Choose a file:</label>

SHRI ADARSH BCA COLLEGE , RADHANPUR 27


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

<input type="file" name="fileToUpload" id="fileUpload">


<input type="submit" value="Upload File" name="submit">
</form>
</body>
</html>
Create the PHP Script (upload.php)
<?php
// Specify the target directory
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
// Check if a file is selected
if (isset($_POST["submit"])) {
if ($_FILES["fileToUpload"]["size"] > 0) {
echo "File selected: " . $_FILES["fileToUpload"]["name"] . "<br>";
} else {
echo "No file selected!<br>";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($targetFile)) {
echo "Sorry, file already exists.<br>";
$uploadOk = 0;
}
// Limit file size (optional, e.g., 5MB)
if ($_FILES["fileToUpload"]["size"] > 5000000) {
echo "Sorry, your file is too large.<br>";
$uploadOk = 0;
}
// Allow specific file formats (optional)
$allowedTypes = ["jpg", "jpeg", "png", "gif", "pdf"];
if (!in_array($fileType, $allowedTypes)) {
echo "Sorry, only JPG, JPEG, PNG, GIF, and PDF files are
allowed.<br>";
$uploadOk = 0;
}

SHRI ADARSH BCA COLLEGE , RADHANPUR 28


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

// Check if $uploadOk is set to 0 (an error occurred)


if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.<br>";
} else {
// Attempt to upload the file
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
$targetFile)) {
echo "The file " .
htmlspecialchars(basename($_FILES["fileToUpload"]["name"])) . " has been
uploaded.";
} else {
echo "Sorry, there was an error uploading your file.<br>";
}
}
?>
Directory Setup
 Create a folder named uploads in the same directory as your PHP
script.
 Set the proper permissions for the uploads folder to ensure the PHP
script can write to it
Security Recommendations
 Validate and sanitize filenames to prevent directory traversal attacks.
 Use unique filenames to prevent overwriting existing files.
 Restrict file types and sizes to reduce the risk of malicious files being
uploaded.
 Store uploaded files outside the web root and serve them via a secure
script

 Redirecting user
In PHP, you can redirect a user to another page or URL using the
header() function
Basic Syntax
header("Location: URL");
exit;
1. Redirect to Another Page on the Same Website
<?php
// Redirect to another page on the same server

SHRI ADARSH BCA COLLEGE , RADHANPUR 29


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

header("Location: welcome.php");
exit;
?>
2. Redirect to an External URL
<?php
// Redirect to an external website
header("Location: https://www.example.com");
exit;
?>

 PHP Sending E-mails


Sending emails in PHP can be done using the built-in
mail() function or external libraries like PHPMailer or
SwiftMailer for more robust and feature-rich email functionality
1. Using PHP’s Built-in mail() Function
 The mail() function is a simple way to send emails but
lacks advanced features like authentication. Below is an
example
Syntax
mail(to, subject, message, headers, parameters);
Example
<?php
$to = "[email protected]";
$subject = "Test Email";
$message = "This is a test email sent from PHP.";
$headers = "From: [email protected]\r\n" .
"Reply-To: [email protected]\r\n" .
"X-Mailer: PHP/" . phpversion();
// Send the email
if (mail($to, $subject, $message, $headers)) {
echo "Email sent successfully!";
} else {
echo "Failed to send email.";
}
?>
Key Points for mail()

SHRI ADARSH BCA COLLEGE , RADHANPUR 30


Web Devlopment Using PHP UNIT – II M.T.CHAUDHARY

1. Requires Proper Mail Server Configuration


 The mail() function depends on the server's mail setup.
For example:
 On Linux, sendmail or Postfix must be configured.
 On Windows, SMTP settings in php.ini must be configured
2. No Authentication
 The mail() function doesn’t support authentication,
making it unsuitable for many modern email services
3. Basic Use Only
 Use mail() for basic email sending needs, as it lacks
advanced features like attachments, HTML formatting, or
SMTP authentication

2. Sending Emails Using PHPMailer


 PHPMailer is a popular library for sending emails in PHP.
It supports SMTP authentication, HTML emails,
attachments, and more

3. Using SwiftMailer
 SwiftMailer is another robust library for sending emails,
supporting SMTP, attachments, and HTML
 Difference mail(), PhpMailer, SwiftMailer.

Method Features Complexity When to Use


mail() Simple, no Low Basic email
authentication sending
without
modern
needs
PHPMailer SMTP, HTML, Medium Advanced
attachments, and reliable
secure email sending
SwiftMailer Similar to Medium Robust
PHPMailer, emails with
modern API attachments
or templates

SHRI ADARSH BCA COLLEGE , RADHANPUR 31

You might also like