Unit-5
Server side programming with PHP
Difference between client-side and server-side scripting language
Client-side Scripting Server – side Scripting
Web servers are used to execute server-side
Web browsers execute client-side scripting.
scripting.
This type of scripting basically refers to the This type of scripting usually occurs on a
code present in the HTML page of a client. website’s back-end.
Languages like VB Script, CSS, HTML,
Languages like ASP, Python, PHP, etc., are
JavaScript, etc., are used in the case of client-
used in the case of server-side scripting.
side scripting.
It is also used for validations and functionality They are basically used to create dynamic
for user events. pages.
It runs on the user’s computer. It runs on the webserver.
It does not provide security for data. It provides more security for data.
No need of interaction with the server. It is all about interacting with the servers.
It is used at the back – end where the source
It is used at the front – end which users can
code is not visible or hidden in the client
see from the browser.
browser.
Structure of PHP Page.
A popular open source general programming language, PHP or Hypertext Preprocessor may
be built into an HTML.
The .php extension is used to store PHP files.
In PHP tags, PHP scripts and standard HTML may be written in any page.
The PHP language statements are enclosed in PHP tags with the following form:
Syntax:
<?php
…..PHP Code…..
?>
PHP is an embedded scripting language when used in web pages.
Web Programming (3360713) Page 1 of 66
This means that PHP code is embedded in HTML code.
You use HTML tags to enclose the PHP language that you embed in your HTML file
Example:
File name: P1.html
<!DOCTYPE html>
<html>
<body>
<h1>Basic Stucture of PHP</h1>s
<?php
echo ‘Hello PHP…!’;
?>
</body>
</html>
Web Programming (3360713) Page 2 of 66
File name: helloprint.php
<?php
echo ‘Hello PHP…!’;
?>
PHP Variables
A variable in PHP is the name of the memory location that holds data.
In PHP, a variable is declared using the $ sign followed by the variable name.
Rules for PHP variables:
A variable starts with the $ sign, followed by the name of the variable
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive ($age and $AGE are two different variables)
Syntax:
$variablename=values;
Example:
Filename: variable.php
<?php
$x = 5;
$y = 4;
echo $x + $y;
?>
Web Programming (3360713) Page 3 of 66
Data Types in PHP
PHP has a total of eight data types which we use to construct our variables:
Integers − are whole numbers, without a decimal point, like 4195.
Doubles − are floating-point numbers, like 3.14159 or 49.1.
Booleans − have only two possible values either true or false.
NULL − is a special type that only has one value: NULL.
Strings − are sequences of characters, like 'PHP supports string operations.'
Arrays − are named and indexed collections of other values.
Objects − are instances of programmer-defined classes, which can package up both other kinds of
values and functions that are specific to the class.
Resources − are special variables that hold references to resources external to PHP (such as database
connections).
Example:
File name: datatypes.php
<!DOCTYPE html>
<html>
<body>
<?php
echo "String datatype...";
$a = "Virat Kohli is the captain of Indian Test Cricket Team!";
echo $a."<br><br>";
echo "integer datatype...";
$a = 30;
$b = 40;
echo $a." ";
echo $b."<br><br>";
echo "float datatype...";
Web Programming (3360713) Page 4 of 66
$a = 2.79;
echo $a."<br><br>";
echo "Boolean datatype...";
$a = true;
echo $a."<br><br>";
echo "Null datatype...";
$x = null;
?>
</body>
</html>
Example:2
<!DOCTYPE html>
<html>
<body>
<?php
$a=readline('Enter Name:');
Web Programming (3360713) Page 5 of 66
echo "Name is ".$a;
?>
</body>
</html>
Example:3
<?php
// Input section
// $a = 10
$a = (int)readline('Enter an integer: ');
// $b = 9.78
$b = (float)readline('Enter a floating'
. ' point number: ');
// Entered integer is 10 and
// entered float is 9.78
echo "Entered integer is " . $a
. " and entered float is " . $b;
?>
Web Programming (3360713) Page 6 of 66
The escape-sequence replacements are
\n is replaced by the newline character
\r is replaced by the carriage-return character
\t is replaced by the tab character
\$ is replaced by the dollar sign itself ($)
\" is replaced by a single double-quote (")
\\ is replaced by a single backslash (\)
Decision Making in PHP
1. If Statement
2. Else Statement
3. Elseif Statement
4. Switch Statement
If Statement
Syntax:
if ( expression ) {
// code to execute if the expression evaluates to true
}
Example:
<!DOCTYPE html>
Web Programming (3360713) Page 7 of 66
<html>
<body>
<?php
$a=10;
$b=5;
if ($a > $b)
echo "a is bigger than b";
?>
</body>
</html>
Else Statement
Syntax:
if ( expression ) {
// code to execute if the expression evaluates to true
} else {
// code to execute in all other cases
}
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$a=10;
$b=20;
if ($a > $b) {
Web Programming (3360713) Page 8 of 66
echo "a is bigger than b";
}
else {
echo "a is NOT bigger than b";
}
?>
</body>
</html>
Elseif Statement
Syntax:
if ( expression ) {
// code to execute if the expression evaluates to true
}
elseif (another expression) {
// code to execute if the previous expression failed
// and this one evaluates to true
}
else {
// code to execute in all other cases
}
Example:
<!DOCTYPE html>
<html>
Web Programming (3360713) Page 9 of 66
<body>
<?php
$a=10;
$b=20;
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
?>
</body>
</html>
Switch Statement
Syntax:
switch ( expression ) {
case result1:
// execute this if expression results in result1
break;
case result2:
// execute this if expression results in result2
break;
default:
// execute this if no break statement
// has been encountered hitherto
}
Example:
<!DOCTYPE html>
Web Programming (3360713) Page 10 of 66
<html>
<body>
<?php
$i=10;
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
default:
echo "i is greater than 3";
}
?>
</body>
</html>
Loops in PHP
In PHP, we have the following looping statements:
while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
for - loops through a block of code a specified number of times
foreach - loops through a block of code for each element in an array
while Loop
Syntax:
Web Programming (3360713) Page 11 of 66
while (condition is true) {
code;
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$a = 0;
while($a < 5) {
echo "Value: $a <br>";
$a++;
}
?>
</body>
</html>
do while Statement
Syntax:
do {
// code to be executed
} while ( expression );
Web Programming (3360713) Page 12 of 66
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$a = 10;
do {
echo "Value: $a <br>";
$a++;
} while ($a < 15);
?>
</body>
</html>
for loop:
Syntax:
for (initialization; condition; increment/decrement counter) {
code;
}
Example:
<!DOCTYPE html>
<html>
<body>
<?php
Web Programming (3360713) Page 13 of 66
for ($a = 1; $a <= 5; $a++) {
echo "$a <br>";
}
?>
</body>
</html>
foreach loop
Syntax:
foreach ($array as $value) {
code;
}
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$topics = array("JavaScript", "HTML", "CSS");
foreach ($topics as $value) {
echo "$value <br>";
}
?>
</body>
</html>
Web Programming (3360713) Page 14 of 66
Array in PHP:
An array is a special variable that we use to store or hold more than one value in a single variable
without having to create more variables to store those values.
To create an array in PHP, we use the array function array( ).
There are different types of arrays in PHP. They are:
1. Numeric/Indexed Arrays
2. Associative Arrays
3. Multidimensional Arrays
1. Numeric/Indexed Arrays:
A numerical array is a type of array which can store strings, numbers, and objects.
PHP index is represented by number which starts from 0.
Example:
<!DOCTYPE html>
<html>
<body>
<?php
// Numeric/ indexed arrays 1st way
$cars = array('Mecedes Benz', 'Hilux', 'Highlander', 'Hummer', 'Limozien');
var_dump($cars);
?>
</body>
</html>
1st way:
Web Programming (3360713) Page 15 of 66
<!DOCTYPE html>
<html>
<body>
<?php
// Numeric/ indexed arrays 1st way
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
</body>
</html>
2nd way:
<!DOCTYPE html>
<html>
<body>
<?php
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
</body>
</html>
Web Programming (3360713) Page 16 of 66
2. Associative Arrays:
PHP allows you to associate name/label with each array elements in PHP using => symbol.
Such way, you can easily remember the element because each element is represented by
label than an incremented number.
There are two ways to define associative array:
Example:
1st way:
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
2nd way:
$salary["Sonoo"]="550000";
$salary["Vimal"]="250000";
$salary["Ratan"]="200000";
Example: associate_array1.php
<!DOCTYPE html>
<html>
<body>
<?php
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "Vimal salary: ".$salary["Vimal"]."<br/>";
echo "Ratan salary: ".$salary["Ratan"]."<br/>";
?>
</body>
</html>
Web Programming (3360713) Page 17 of 66
Example: associate_array2.php
<!DOCTYPE html>
<html>
<body>
<?php
$salary["Sonoo"]="550000";
$salary["Vimal"]="250000";
$salary["Ratan"]="200000";
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "Vimal salary: ".$salary["Vimal"]."<br/>";
echo "Ratan salary: ".$salary["Ratan"]."<br/>";
?>
</body>
</html>
3. Multidimentional Arrays:
A two-dimensional array is an array of arrays (a three-dimensional array is an array of arrays of
arrays).
Example:
Web Programming (3360713) Page 18 of 66
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
?>
</body>
</html>
Web Programming (3360713) Page 19 of 66
Array Functions:
Function Description
array() Creates an array
Changes all keys in an array to lowercase or
array_change_key_case()
uppercase
array_chunk() Splits an array into chunks of arrays
Returns the values from a single column in the
array_column()
input array
Creates an array by using the elements from
array_combine()
one "keys" array and one "values" array
array_count_values() Counts all the values of an array
Compare arrays, and returns the differences
array_diff()
(compare values only)
Compare arrays, and returns the differences
array_diff_assoc()
(compare keys and values)
Web Programming (3360713) Page 20 of 66
Compare arrays, and returns the differences
array_diff_key()
(compare keys only)
Compare arrays, and returns the differences
array_diff_uassoc() (compare keys and values, using a user-
defined key comparison function)
Compare arrays, and returns the differences
array_diff_ukey() (compare keys only, using a user-defined key
comparison function)
array_fill() Fills an array with values
array_fill_keys() Fills an array with values, specifying keys
Filters the values of an array using a callback
array_filter()
function
Flips/Exchanges all keys with their associated
array_flip()
values in an array
Compare arrays, and returns the matches
array_intersect()
(compare values only)
Web Programming (3360713) Page 21 of 66
Compare arrays and returns the matches
array_intersect_assoc()
(compare keys and values)
Compare arrays, and returns the matches
array_intersect_key()
(compare keys only)
Compare arrays, and returns the matches
array_intersect_uassoc() (compare keys and values, using a user-
defined key comparison function)
Compare arrays, and returns the matches
array_intersect_ukey() (compare keys only, using a user-defined key
comparison function)
array_key_exists() Checks if the specified key exists in the array
array_keys() Returns all the keys of an array
Sends each value of an array to a user-made
array_map()
function, which returns new values
array_merge() Merges one or more arrays into one array
Merges one or more arrays into one array
array_merge_recursive()
recursively
Web Programming (3360713) Page 22 of 66
array_multisort() Sorts multiple or multi-dimensional arrays
Inserts a specified number of items, with a
array_pad()
specified value, to an array
array_pop() Deletes the last element of an array
array_product() Calculates the product of the values in an array
Inserts one or more elements to the end of an
array_push()
array
Returns one or more random keys from an
array_rand()
array
Returns an array as a string, using a user-
array_reduce()
defined function
Replaces the values of the first array with the
array_replace()
values from following arrays
Replaces the values of the first array with the
array_replace_recursive()
values from following arrays recursively
Web Programming (3360713) Page 23 of 66
array_reverse() Returns an array in the reverse order
Searches an array for a given value and
array_search()
returns the key
Removes the first element from an array, and
array_shift()
returns the value of the removed element
array_slice() Returns selected parts of an array
Removes and replaces specified elements of an
array_splice()
array
array_sum() Returns the sum of the values in an array
Compare arrays, and returns the differences
array_udiff() (compare values only, using a user-defined key
comparison function)
Compare arrays, and returns the differences
(compare keys and values, using a built-in
array_udiff_assoc()
function to compare the keys and a user-
defined function to compare the values)
Web Programming (3360713) Page 24 of 66
Compare arrays, and returns the differences
array_udiff_uassoc() (compare keys and values, using two user-
defined key comparison functions)
Compare arrays, and returns the matches
array_uintersect() (compare values only, using a user-defined key
comparison function)
Compare arrays, and returns the matches
(compare keys and values, using a built-in
array_uintersect_assoc()
function to compare the keys and a user-
defined function to compare the values)
Compare arrays, and returns the matches
array_uintersect_uassoc() (compare keys and values, using two user-
defined key comparison functions)
array_unique() Removes duplicate values from an array
Adds one or more elements to the beginning of
array_unshift()
an array
array_values() Returns all the values of an array
Applies a user function to every member of an
array_walk()
array
Web Programming (3360713) Page 25 of 66
Applies a user function recursively to every
array_walk_recursive()
member of an array
Sorts an associative array in descending order,
arsort()
according to the value
Sorts an associative array in ascending order,
asort()
according to the value
Create array containing variables and their
compact()
values
count() Returns the number of elements in an array
current() Returns the current element in an array
Deprecated from PHP 7.2. Returns the current
each()
key and value pair from an array
Sets the internal pointer of an array to its last
end()
element
Imports variables into the current symbol table
extract()
from an array
Web Programming (3360713) Page 26 of 66
in_array() Checks if a specified value exists in an array
key() Fetches a key from an array
Sorts an associative array in descending order,
krsort()
according to the key
Sorts an associative array in ascending order,
ksort()
according to the key
list() Assigns variables as if they were an array
Sorts an array using a case insensitive "natural
natcasesort()
order" algorithm
Sorts an array using a "natural order"
natsort()
algorithm
next() Advance the internal array pointer of an array
pos() Alias of current()
prev() Rewinds the internal array pointer
Web Programming (3360713) Page 27 of 66
Creates an array containing a range of
range()
elements
Sets the internal pointer of an array to its first
reset()
element
rsort() Sorts an indexed array in descending order
shuffle() Shuffles an array
sizeof() Alias of count()
sort() Sorts an indexed array in ascending order
Sorts an array by values using a user-defined
uasort() comparison function and maintains the index
association
Sorts an array by keys using a user-defined
uksort()
comparison function
Sorts an array by values using a user-defined
usort()
comparison function
Web Programming (3360713) Page 28 of 66
Function in PHP:
A function is a piece of code that takes another input in the form of a parameter, processes it, and
then returns a value.
A PHP Function feature is a piece of code that can be used over and over again and accepts
argument lists as input, and returns a value.
There are two types of functions
1. In built Function
2. User define Function
User Define Function:
A function is a piece of code which takes one more input in the form of parameter and does
some processing and returns a value.
A function is block of code written in a program to perform some specific task.
Creating and Calling Function
In PHP, the function name is any name that ends in an open and closed parenthesis.
The keyword function is often used to start a function name.
To invoke a function, simply type its name followed by the parenthesis.
A number cannot be the first character in a feature name. It can begin with a letter or an underscore.
The case of a feature name is unimportant.
Syntax:
function function_name()
//Statement to be executed
Web Programming (3360713) Page 29 of 66
Example:
<!DOCTYPE html>
<html>
<body>
<?php
function welcMsg()
echo "Hello PHP!";
welcMsg();
?>
</body>
</html>
Function Arguments:
Arguments are listed within parentheses after the function name.
You can add as many arguments as you want; just use a comma to divide them.
Parameters are the information or variables contained within the function's parenthesis.
Web Programming (3360713) Page 30 of 66
These are used to store the values that can be executed at runtime.
Example:
<!DOCTYPE html>
<html>
<body>
<?php
function StudentsName($firstname)
echo "$firstname<br>";
StudentsName("Janani");
StudentsName("Helen");
StudentsName("Stella");
StudentsName("Kamal");
StudentsName("Bablu");
?>
</body>
</html>
Web Programming (3360713) Page 31 of 66
Passing Arguments By Reference:
Arguments are generally passed by value in PHP, which ensures that the function uses a copy
of the value and the variable passed into the function cannot be modified.
Changes to the argument modify the variable passed in when a function argument is passed by
reference.
The & operator is used to convert a function argument into a reference.
Example:
<!DOCTYPE html>
<html>
<body>
<?php
function addition(&$val) {
$val += 10;
$number =5;
addition($number);
Web Programming (3360713) Page 32 of 66
echo "Answer of given number is ".$number;
?>
</body>
</html>
Functions - Returning Value
This means the PHP Function can be called by its name, and
when executing the function, it will return some value.
Example:
<!DOCTYPE html>
<html>
<body>
<?php
function circle($r){
return 3.14*$r*$r;
echo "Area of circle is: ".circle(3);
?>
</body>
</html>
Web Programming (3360713) Page 33 of 66
Setting Default Values for Passing Arguments
It is possible to specify a default argument value in the function. While calling the Function in
PHP,
it will take the default value if no arguments are passed.
Example:
<!DOCTYPE html>
<html>
<body>
<?php
function setval(int $a = 5) {
echo "The value is : $a <br>";
setval(50);
setval();
setval(13);
setval(40);
?>
</body>
</html>
Web Programming (3360713) Page 34 of 66
String in PHP:
A string is a sequence of one or more characters that may consist of letters, numbers, or
symbols.
All written communication is made up of strings.
You can create a string in PHP by enclosing a sequence of characters in either single or double
quotes. like, “ This is String ” or ‘ This is string ’.
String manipulation in PHP refers to the various operations performed on strings
to modify, extract, or manipulate their content.
PHP provides a rich set of functions and techniques for working with strings,
including concatenation, searching, replacing, splitting, and formatting.
Developers can manipulate strings by utilizing functions
like strlen() , substr(), str_replace(), explode(), and more.
Example:
<!DOCTYPE html>
<html>
<body>
<?php
// Sample string
$string = "Hello, World!";
// Calculate the length of the string
// Validate strlen()
$length = strlen($string);
echo "Length of the string: ". $length. "<br>";
// Count the number of words in the string
Web Programming (3360713) Page 35 of 66
$wordCount = str_word_count($string);
// Display the result
echo "Number of words in the string: ". $wordCount."<br>";
// Perform text replacement
$newString = str_replace("World", "Universe", $string);
// Display the result
echo "Modified string: ". $newString."<br>";
// Reverse the string
$reversedString = strrev($string);
// Display the result
echo "Reversed string: ". $reversedString ."<br>";
// Validate substr()
$subString = substr($string, 7);
echo "Substring from position 7: " . $subString. "<br>";
// Validate str_replace()
$newString = str_replace("World", "PHP", $string);
echo "Replaced string: ". $newString. "<br>";
// Validate strpos()
$position = strpos($string, ",");
echo "Position of the comma: ". $position. "<br>";
// Validate str_split()
$charArray = str_split($string);
echo "Character array: ";
print_r($charArray);
echo "<br>";
// Validate strtolower()
$lowercaseString = strtolower($string);
echo "Lowercase string: ". $lowercaseString. "<br>";
// Validate strtoupper()
$uppercaseString = strtoupper($string);
echo "Uppercase string: ". $uppercaseString. "<br>";
Web Programming (3360713) Page 36 of 66
// Validate trim()
$trimmedString = trim(" Hello, World! ");
echo "Trimmed string: ". $trimmedString. "<br>";
// Validate explode()
$wordsArray = explode(" ", $string);
echo "Exploded array: ";
print_r($wordsArray);
// Validate implode()
$joinedString = implode("-", $wordsArray);
echo "Joined string: ". $joinedString. "<br>";
// Validate sprintf()
$formattedString = sprintf("Today is %s, %d %s", "Monday", 5, "June");
echo "Formatted string: ". $formattedString. "<br>";
// Validate ucfirst()
$ucFirstString = ucfirst($string);
echo "String with the first character capitalized: ". $ucFirstString. "<br>";
// Validate ucwords()
$ucWordsString = ucwords($string);
echo "String with each word's first character capitalized: ". $ucWordsString. "<br>";
?>
</body>
</html>
Web Programming (3360713) Page 37 of 66
Form Processing in PHP:
Example:
<!DOCTYPE html>
<html>
<body>
<form action="form_valid.php" method="post">
<p>Name: <input type="text" name="txtname"></p>
<p>Email: <input type="email" name="txtemail"></p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
Example:
<!DOCTYPE html>
<html>
<body>
Web Programming (3360713) Page 38 of 66
<?php
// Check if the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// Get the name and email from $_POST
$name = $_POST["txtname"];
$email = $_POST["txtemail"];
if (empty($name))
{
echo "Name is required";
exit;
}
if (empty($email))
{
echo "Email is required";
exit;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo "Invalid email format";
exit;
}
// Provide feedback to the user
echo "Hello $name, your email is $email.";
}
Web Programming (3360713) Page 39 of 66
?>
</body>
</html>
Web Programming (3360713) Page 40 of 66
File Uploading in PHP:
Example:
File_uploading.html
<!DOCTYPE html>
<html>
<body>
<form method="post" action="file_uploading2.php" enctype="multipart/form-data">
<input type="file" name="myFile" />
<input type="submit" name="Upload" value="Upload">
</form>
</body>
</html>
Web Programming (3360713) Page 41 of 66
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$target_path = __DIR__ . "\uploads";
$target_path = $target_path.basename( $_FILES['myFile']['name']);
if(move_uploaded_file($_FILES['myFile']['tmp_name'], $target_path))
{
echo "File uploaded successfully!";
}
else{
echo "Sorry, file not uploaded, please try again!";
}
?>
</body>
</html>
Example with Validation:
Web Programming (3360713) Page 42 of 66
<!DOCTYPE html>
<html>
<body>
<?php
if (!isset($_FILES["myFile"]))
{
die("There is no file to upload.");
}
$filepath = $_FILES['myFile']['tmp_name'];
$fileSize = filesize($filepath);
$fileinfo = finfo_open(FILEINFO_MIME_TYPE);
$filetype = finfo_file($fileinfo, $filepath);
if ($fileSize === 0)
{
die("The file is empty.");
}
if ($fileSize > 3145728)
{ // 3 MB (1 byte * 1024 * 1024 * 3 (for 3 MB))
die("The file is too large");
}
$allowedTypes = [
'image/png' => 'png',
Web Programming (3360713) Page 43 of 66
'image/jpeg' => 'jpg'
];
if (!in_array($filetype, array_keys($allowedTypes)))
{
die("File not allowed.");
}
$filename = basename($filepath); // I'm using the original name here, but you can also change
the name of the file here
$extension = $allowedTypes[$filetype];
$targetDirectory = __DIR__ . "\uploads"; // __DIR__ is the directory of the current PHP file
$newFilepath = $targetDirectory . "/" . $filename . "." . $extension;
if (!copy($filepath, $newFilepath))
{ // Copy the file, returns false if failed
die("Can't move file.");
}
unlink($filepath); // Delete the temp file
echo "File uploaded successfully :)";
?>
</body>
</html>
Web Programming (3360713) Page 44 of 66
Date and Time Zone in PHP:
1. Set the Default Timezone
PHP uses this timezone to calculate date and time-related functions when a specific timezone is
not provided.
You can set the default timezone using the date_default_timezone_set() function or the
date.timezone directive in the php.ini configuration file.
1.1. Using date_default_timezone_set()
To set the default timezone in your PHP script, use the date_default_timezone_set() function
with the desired timezone as its parameter.
Example:
date_default_timezone_set('Europe/London');
1.2.Using the php.ini Configuration File
Alternatively, you can set the default timezone in the php.ini file using the date.timezone
directive.
Open your php.ini file and search for date.timezone. If it's commented out, uncomment it and
set the desired timezone:
Example:
date.timezone = "Europe/London"
2. Working with DateTime Objects
Web Programming (3360713) Page 45 of 66
PHP's DateTime class provides an easy way to work with dates and times, including timezone
conversions.
To create a new DateTime object, use the following syntax:
Syntax:
$dateTime = new DateTime('now', new DateTimeZone('Europe/London'));
The first parameter is the date and time, and the second parameter is an instance of the
DateTimeZone class representing the desired timezone.
In this example, we created a DateTime object for the current date and time in the
'Europe/London' timezone.
3. Converting Between Timezones
To convert a DateTime object between timezones, you can use the setTimezone() method. This
method accepts a DateTimeZone object representing the target timezone. Here's an example:
Syntax:
$dateTime = new DateTime('now', new DateTimeZone('Europe/London'));
$dateTime->setTimezone(new DateTimeZone('America/New_York'));
In this example, we created a DateTime object for the current date and time in the
'Europe/London' timezone and then converted it to the 'America/New_York' timezone.
4. Formatting Dates and Times with Timezones
To display a DateTime object's date and time in a specific format, you can use the format()
method. This method accepts a format string as its parameter. Here's an example:
Syntax:
$dateTime = new DateTime('now', new DateTimeZone('Europe/London'));
echo $dateTime->format('Y-m-d H:i:s T');
This example will output the current date and time in the 'America/New_York' timezone, along
with the timezone abbreviation (e.g., '2023-03-23 12:34:56 EDT').
5. Date and Time Functions in PHP
Example:
<!DOCTYPE html>
<html>
<body>
Web Programming (3360713) Page 46 of 66
<?php
//echo date_default_timezone_set('Europe/London')."<br><br>";
$day =date('d/m/y');
echo $day ."<br>";
echo date("d/m/Y") . "<br>";
echo date("d-m-Y") . "<br>";
echo date("d.m.Y"). "<br>"; ?>
</body>
</html>
Example:
<?php
$date=date_create("2018-07-27");
echo date_format($date,"Y/m/d");
?>
Output:
2018/07/27
Example:
echo date_default_timezone_get();
Output:
UTC
Example:
echo "old time ". date_default_timezone_get();
$timeZ = 'America/Chicago';
if( date_default_timezone_set( $timeZ) ){
echo " New time ". date_default_timezone_get();
}
Web Programming (3360713) Page 47 of 66
Output:
old time UTC New time America/Chicago
Example:
<?php
date_default_timezone_set("America/chicago");
echo date_default_timezone_get();
?>
Output:
America/chicago
Example:
$date=date_create("2025-02-25");
echo date_format($date,"Y/m/d H:i:s");
Output:
2025/02/25 00:00:00
Regular Expressions in PHP:
Regex, or regular expressions, in PHP is a sequence of characters that forms a search pattern. It
is used for string matching, searching, and manipulation, allowing developers to validate input,
extract data, and perform complex text transformations.
Web Programming (3360713) Page 48 of 66
PHP provides built-in functions like preg_match(), preg_replace(), and preg_split() to work
with regular expressions effectively.
A regular expression (or regex) is a sequence of characters that defines a search pattern.
For example, the regex /[a-z]+/ matches one or more lowercase letters, while the regex /[0-
9]{3}-[0-9]{3}-[0-9]{4}/ matches a phone number in the format xxx-xxx-xxxx.
A regex can consist of literal characters (such as a, b, c, etc.), special characters (such
as ^, $, ., *, etc.), and character classes (such as [a-z], [0-9], \w, \d, etc.).
Each character or group of characters has a specific meaning and function in the regex.
The preg_ functions are a set of built-in functions that allow you to perform various operations
with regular expressions, such as matching, replacing, splitting, and filtering.
The most commonly used preg_ functions are:
preg_match($pattern, $subject, $matches) –
o This function tries to match a regex $pattern against a string $subject.
o If a match is found, it returns true and stores the matched subpatterns in an array
$matches. Otherwise, it returns false.
preg_replace($pattern, $replacement, $subject) –
o This function replaces all occurrences of a regex $pattern in a string $subject with a
string $replacement.
o It returns the modified string or null if an error occurs.
preg_split($pattern, $subject) –
o This function splits a string $subject into an array of substrings using a regex $pattern as
the delimiter.
o It returns the array of substrings or false if an error occurs.
preg_grep($pattern, $array) –
o This function filters an array $array of strings by returning only those that match a regex
$pattern.
o It returns the filtered array or false if an error occurs.
To use the preg_ functions, you need to enclose your regex in delimiters (such as /, #, or ~)
and optionally add modifiers (such as i, m, or g) after the closing delimiter.
Example:
<!DOCTYPE html>
<html>
<body>
<?php
// Match any word that starts with "cat"
$pattern = "/\bcat\w*/i"; // The "i" modifier makes the match case-insensitive
$subject = "I like cats and caterpillars but not catacombs.";
if (preg_match($pattern, $subject, $matches)) {
echo "Match found: " . $matches[0] . "\n"; // Output: Match found: cats
} else {
echo "No match found.\n";
Web Programming (3360713) Page 49 of 66
}
// Replace all occurrences of "dog" with "puppy"
$pattern = "/dog/";
$replacement = "puppy";
$subject = "The dog chased the cat and the dog barked at the mailman.";
$new_subject = preg_replace($pattern, $replacement, $subject);
echo $new_subject. "<br>";
// Output: The puppy chased the cat and the puppy barked at the mailman.
// Split a string by commas or spaces
$pattern = "/[,\s]+/";
$subject = "red, green blue , yellow";
$array = preg_split($pattern, $subject);
print_r($array); // Output: Array ( [0] => red [1] => green [2] => blue [3] => yellow )
echo "<br>";
// Filter an array of email addresses by domain name
$pattern = "/@gmail\.com$/";
$array = ["alice@gmail.com", "bob@yahoo.com", "charlie@hotmail.com",
"david@gmail.com"];
$new_array = preg_grep($pattern, $array);
print_r($new_array);
// Output: Array ( [0] => alice@gmail.com [3] => david@gmail.com )
?>
</body>
</html>
Exception Handling in PHP:
Exception handling is used to change the normal flow of the code execution if a specified error
(exceptional) condition occurs.
This condition is called an exception.
Web Programming (3360713) Page 50 of 66
Exception handling is a mechanism in programming that allows a system to handle unexpected
events or errors that occur during the execution of a program.
These unexpected events, known as exceptions, can disrupt the normal flow of an application.
In PHP, the errors are handled with the help of −
The die() function
The die() function is an alias of exit() in PHP.
Syntax:
die("message");
The Error Handler Function
Why Do We Need Exception Handling?
1. Maintaining Application Flow: Without exception handling, an unexpected error could
terminate the program abruptly. Exception handling ensures that the program can continue
running or terminate gracefully.
2. Informative Feedback: When an exception occurs, it provides valuable information about
the problem, helping developers to debug and users to understand the issue.
3. Resource Management: Exception handling can ensure that resources like database
connections or open files are closed properly even if an error occurs.
4. Enhanced Control: It allows developers to specify how the program should respond to
specific types of errors.
PHP error handling keywords
The following keywords are used for PHP exception handling.
Try: The try block contains the code that may potentially throw an exception. All of the code
within the try block is executed until an exception is potentially thrown.
Throw: The throw keyword is used to signal the occurrence of a PHP exception. The PHP
runtime will then try to find a catch statement to handle the exception.
Catch: This block of code will be called only if an exception occurs within the try code block.
The code within your catch statement must handle the exception that was thrown.
Finally: In PHP 5.5, the finally statement is introduced. The finally block may also be
specified after or instead of catch blocks. Code within the finally block will always be
executed after the try and catch blocks, regardless of whether an exception has been thrown,
and before normal execution resumes. This is useful for scenarios like closing a database
connection regardless if an exception occurred or not.
Syntax:
try
Web Programming (3360713) Page 51 of 66
{
// run your code here
throw new Exception("error message!");
}
catch(Exception $e)
{
//code to handle the exception
}
finally
{
//optional code that always runs
}
Example:
<!DOCTYPE html>
<html>
<body>
<?php
try
{
// if some condition is met or not met ->
throw new Exception("I am the error message!");
// below lines are not executed ->
echo "I am not executed!";
}
catch(Exception $e)
{
echo " Exception caught - ", $e->getMessage();
}
finally
{
echo " I am executed in the end";
}
?>
</body>
</html>
Web Programming (3360713) Page 52 of 66
PHP try catch with multiple exception types
PHP supports using multiple catch blocks within try catch. This allows us to customize our
code based on the type of exception that was thrown.
This is useful for customizing how you display an error message to a user, or if you should
potentially retry something that failed the first time.
try {
// run your code here
}
catch (Exception $e) {
echo $e->getMessage();
}
catch (InvalidArgumentException $e) {
echo $e->getMessage();
}
File Handling in PHP:
To write file:
The PHP fwrite() function is used to write data to a file.
It takes three parameters: a file pointer, a string to be written, and an optional parameter that
specifies the maximum number of bytes to write.
Syntax:
fwrite ( resource $handle , string $string [, int $length ] ) : int|false
Example:
<!DOCTYPE html>
<html>
<body>
<?php
Web Programming (3360713) Page 53 of 66
// Open a file for writing
$file = fopen("example.txt", "w");
// Write some data to the file
fwrite($file, "Hello,PHP world!");
echo "file write successfully...";
// Close the file
fclose($file);
?>
</body>
</html>
Web Programming (3360713) Page 54 of 66
Example-2:
<!DOCTYPE html>
<html>
<body>
<?php
$file = fopen("data.txt", "w");
if ($file) {
$data = "Hello, World!\n";
fwrite($file, $data);
fclose($file);
echo "Data written to the file.";
} else {
echo "Error opening file.";
}
?>
</body>
</html>
Web Programming (3360713) Page 55 of 66
File Read in PHP:
fopen() function in PHP is used to open a file or URL and returns a file pointer resource that can
be used to read, write, or manipulate the file.
'r': read only
'w': write only (truncates the file to zero length or creates a new file)
'a': append-only (opens the file for writing at the end of the file)
'x': exclusive write (creates a new file and opens it for writing only if it doesn't already exist)
'b': binary mode (used in conjunction with the above modes to indicate that the file should
be opened in binary mode)
't': text mode (used in conjunction with the above modes to indicate that the file should be
opened in text mode)
Syntax:
Web Programming (3360713) Page 56 of 66
fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource
$context ]] )
PHP fclose() Function
The PHP fclose() function is used to close an open file pointer or handle in PHP.
It is typically used after a file has been opened using fopen() or a related function.
Syntax:
bool fclose ( resource $handle );
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$file = fopen('example.txt', 'r');
if ($file) {
while (($line = fgets($file)) !== false) {
echo $line;
}
fclose($file);
}
?>
</body>
</html>
Web Programming (3360713) Page 57 of 66
State Management in PHP:
PHP allows us to save certain states of the application either on the server itself, or in the user’s
browser.
PHP provides us with two different techniques to manage states in a web application:
Hidden Field: <input type=” hidden”> define hidden input field
Query String: GET and POST for passing the query string from the browser to Server
Sessions: Server Side State Management
Cookies: Client Side State Management
1. Hidden Field:
Use a hidden field to keep track of this value.
A hidden field behaves the same as a text field, except that the user cannot see it unless he
views the HTML source of the document that contains it.
Example:
Hidden_Field.html File:
<!DOCTYPE html>
<html>
<body>
<h1> First Number</h1>
<form action="Hidden_field1.php" method="post">
<label for= "fn"> First Number </label>
<input type="text" name="fn" value="" id="fn" >
<p> <input type="submit" value="continue →"></p>
</form>
</body>
</html>
Hidden_Field1.php File:
<!DOCTYPE html>
<html>
Web Programming (3360713) Page 58 of 66
<body>
<h1> Second Number</h1>
<form action="Hidden_field2.php" method="post">
<input type="hidden" name="fn" value=" <?php echo $_POST['fn'] ?> " id="fn" >
<label for= "sn"> Second Number </label>
<input type="text" name="sn" value="" id="sn" >
<p> <input type="submit" value="continue →"></p>
</form>
</body>
</html>
Hidden_Field2.php File:
<!DOCTYPE html>
<html>
<body>
<?php
$ans = $_POST['fn'] + $_POST['sn'] ;
?>
<h1> Answer is .....</h1>
<?php
echo "The Answer is $ans";
?>
</form>
</body>
</html>
Web Programming (3360713) Page 59 of 66
Web Programming (3360713) Page 60 of 66
2. Query String / URL rewriting:
The information sent across the web pages.
This information is called a query string.
This query string can be passed from one page to another by appending its address of the page.
Passing more than one query string by inserting the & sign between the query strings.
A query string contains two things: the query string ID and its value.
The query string passed across the web pages is stored in $_REQUEST, $_GET, or $_POST
variable.
Example:
Query_String.html File:
<!DOCTYPE html>
<html>
<title>Login form</title>
</head>
<body>
<form action="Query_String.php" method=”get”>
<table>
<tr>
<td>User name:</td><td> <input type="text" name="username" ></td>
</tr>
<tr>
<td>E-mail: </td><td><input type="text" name="email" ></td>
</tr>
<tr>
<td><input type="submit" name="sub" value="submit"></td>
</tr>
</table>
</form>
</body>
</html>
Web Programming (3360713) Page 61 of 66
Query_String.php File:
<!DOCTYPE html>
<html>
<body>
<?php
echo "<strong>Welcome ".$_GET['username']. "!</strong><br/>";
echo "Please remember this e-mail: ".$_GET['email']. " for later use.";
?>
</body>
</html>
3. Session
Sessions are states that are saved to the server (like a unique ID), or if a user is logged into their
account.
To start a session in PHP, we use the session_start() function. We store session data by using
the $_SESSION superglobal.
How to start a session and store session data :
Syntax:
Web Programming (3360713) Page 62 of 66
// start a session
session_start();
// set a session variable
$_SESSION["session_variable_name"] = session_variable_value;
Example:
<!DOCTYPE html>
<html>
<title>Login form</title>
</head>
<body>
<form action="Session1.php" method=”get”>
<table>
<tr>
<td>User name:</td><td> <input type="text" name="username" ></td>
</tr>
<tr>
<td>E-mail: </td><td><input type="text" name="email" ></td>
</tr>
<tr>
<td><input type="submit" name="sub" value="submit"></td>
</tr>
</table>
</form>
</body>
</html>
Web Programming (3360713) Page 63 of 66
Session1.php File:
<?php
// start a session
session_start();
// set a session variable
$_SESSION["username"] = username;
$_SESSION["emailID"] = email;
?>
<html>
<body>
<a href="session2.php">Sessions page</a>
</body>
</html>
Session2.php File:
<?php
session_start();
echo "Hello " . $_SESSION["username"];
?>
How to destroy a session
We can destroy a whole session completely with the session_destroy() function.
Example:
<?php
session_start();
echo "Hello " . $_SESSION["username"];
// unset username value
session_destroy();
// try to print username to the page
echo $_SESSION["username"];
?>
4. Cookie
Cookies are states that are saved to the user’s system, instead of the server. Unlike a session, a
cookie has a 1024-byte size limit.
Web Programming (3360713) Page 64 of 66
Cookies are not stored on the server, they can be modified and deleted. Cookies are less reliable
and secure than sessions.
Cookies are sent to the web server as header information in every HTTP request.
How to set a cookie
PHP provides us with the setcookie() function to create, or set, a cookie.
Syntax:
setcookie (name, value, expiration, path, domain, secure);
The first argument, name, is mandatory for every cookie. The rest of the arguments are optional
Example:
<?php
// Expires when the browser closes
setcookie("UserID", 007);
// Expires in 1 minute (60 seconds)
setcookie("SelfDestructMsg", "1 minute", time()+60)
// Only available to a specific subdomain over HTTPS
setcookie("Name", "Bond, James", time()+60, "/totally_not_cookies/", "agents.mi6.com", 1);
?>
How to access cookie data:
We access a cookie’s value via the $_COOKIE super global by specifying its name as the
key.
Syntax:
$_COOKIE["cookie_name"];
Example:
<?php
setcookie("Name", "Bond, James", time()+60);
echo "Agent: " . $_COOKIE["Name"];
?>
Web Programming (3360713) Page 65 of 66
How to change cookie data
We can change any argument of the cookie, except the name, by assigning a new value.
When a new name is assigned, it will create a new cookie instead of changing the current
cookie.
Example:
<?php
setcookie("Name", "Hunt, Ethan", time()+5);
echo "Agent: " . $_COOKIE["Name"];
?>
How to delete a cookie:
We delete a cookie by setting its expiration time to anything in the past.
When a cookie is deleted and we try to access it, the interpreter will raise an Undefined index
error.
Example:
<?php
// Current time - 60 minutes
setcookie("Name", "Hunt, Ethan", time()-3600);
echo "Agent: " . $_COOKIE["Name"];
?>
Web Programming (3360713) Page 66 of 66