0% found this document useful (0 votes)
44 views106 pages

IWD Lab Manual

The document is a laboratory manual for a Diploma in Computer Engineering course on Web Development, detailing the curriculum, course outcomes, and practical assessments. It outlines the expected program outcomes, course outcomes, assessment rubrics, and a list of practical exercises related to PHP and web development. Additionally, it includes instructions for setting up a local web server using XAMPP and various PHP programming tasks.

Uploaded by

Tarun Ahir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views106 pages

IWD Lab Manual

The document is a laboratory manual for a Diploma in Computer Engineering course on Web Development, detailing the curriculum, course outcomes, and practical assessments. It outlines the expected program outcomes, course outcomes, assessment rubrics, and a list of practical exercises related to PHP and web development. Additionally, it includes instructions for setting up a local web server using XAMPP and various PHP programming tasks.

Uploaded by

Tarun Ahir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Diploma Engineering

Laboratory Manual
Introduction to Web Development
(DI04007011)
[Computer Engineering ,Semester IV]
Enrolment No
Name
Branch
Academic Term
Institute

Directorate Of Technical Education Gandhinagar


- Gujarat
Government Polytechnic, Ahmedabad

Certificate

This is to certify that Mr./Ms…………………………………………………..


Enrollment No. ………….…………….…….…….……. of Diploma in Computer Engineering
of………………………………………………………………………. (DI04007011)has
satisfactorily completed the term work in course…………………..for the academic
year:………………Term: Odd/Even prescribed in the GTU curriculum.

Place:…………………..

Date:…………………..

Signature of Course Faculty Head of the Department


DTE’s Mission:
 To provide globally competitive technical education;
 Remove geographical imbalances and inconsistencies;
 Develop student friendly resources with a special focus on girls’ education and support to
weaker sections;
 Develop programs relevant to industry and create a vibrant pool of technical professionals.
Institute’s Vision:

Institute’s Mission:

Department’s Vision:

Department’s Mission:
PROGRAMME OUTCOMES (POs)
Following programme outcomes are expected to be achieved through the practical of the course:

1. Basic and Discipline specific knowledge


2. Problem analysis
3. Design/development of solutions
4. Engineering Tools, Experimentation and Testing
5. Engineering practices for society, sustainability and environment
6. Project Management
7. Life-long learning

COURSE OUTCOMES (COs)

CONo CourseOutcomes
CO1 Apply basic PHP syntax and structures to create simple web pages.
CO2 Use PHP functions, arrays, and strings to write efficient code.
CO3 Handle and validate user inputs using forms in PHP.
CO4 Manage user data across multiple pages using sessions and cookies in PHP.
CO5 Connect PHP with the MySQLi Database and perform common database operations.
ASSESSMENT RUBRICS
% of
Criteria Rubrics
point
Excellent (10-8 marks): Completed programs/scripts correctly as per
the requirements.

C1: Adequate (7-6 marks): Completed programs/scripts correctly with


Program approx. 70% requirements.
50 %
Completeness/ Poor (5-4 marks): Completed programs/scripts correctly with 70% -
Correctness 50% requirements.
Unsatisfactory (0-3 marks): Completed programs/ scripts correctly
with less than 50% requirements.
Excellent (10-8 marks):The code is clean, well-organized and very
easy to understand.

Adequate (7-6 marks):The code is fairly easy to read and understand.


C2:
25 %
Readability Poor (5-4 marks):The code is readable only by someone who knows
what it is supposed to be doing.
Unsatisfactory (0-3 marks):The code is poorly organized and very
difficult to understand.
Excellent (10-8 marks):
 Coding standards are followed in complete code while naming
variables/functions/ classes, explaining the purpose of variables/
functions/classes.
 The Complete code is well-documented with comments explaining
the code.
Adequate (7-6 marks):
 Coding standards are followed in most of the code while naming
C3: variables/functions/ classes, explaining the purpose of variables/
Coding functions/classes.
25 %
Standards/  Most of the code is documented with comments explaining the
Documentation code.
Poor (5-4 marks):
 Coding standards are followed in very little code while naming
variables/functions/ classes, explaining the purpose of variables/
functions/classes.
 Very little code is documented with comments explaining the code.
Unsatisfactory (0-3 marks):
 Coding standards are not followed properly.
 Proper comments are not written explaining the code.
Total Marks for Practical = 0.5 * (Marks of C1) + 0.25 * (Marks of C2) + 0.25 * (Marks of C3)
RUBRICS CRITERIA BASED MARKS
Pr. C1 C2 C3 Total Marks
Faculty Sign
No. Marks Marks Marks (50% C1) + (25%C2) + (25%C3)
1

10

11

12

13

COURSE OUTCOME BASED MARKS DISTRIBUTION

Practical List CO Covered Total Marks Marks obtained


Practical–1 to 3 CO1 30
Practical–4 to 6 CO2 30
Practical–7 to 9 CO3 30
Practical–10 & 11 CO4 20
Practical–12 & 13 CO5 20
Index
Name: ___________________________________ EnrollNo. __________________________

Term: __________ Division: ________ Batch:____________

Sr. Date Marks(1


Experiment/Practical Outcome Page Sign
No Perform 0)
Environment Setup & Introduction
i. Install and configure a local web server using
XAMPP/WAMP/LAMP. 1
ii. Create a web page using PHP that displays a
welcome message.
2 Variables, Constants & Operators
i. Develop simple PHP web applications using 9
variables, constants, and operators.
3 Control & Looping Structures
i. Develop PHP web applications using control
structures. 18
ii. Develop PHP web applications using looping
structures.
4 Functions
i. Develop PHP web applications using user 27
defined functions.
5 Arrays
i. Develop PHP web applications that
demonstrate the use of indexed, associative
arrays, and multidimensional arrays.
ii. Develop PHP web applications to process data 33
stored in arrays.
iii. Develop PHP web applications to
demonstrate array functions.
6 Strings
i. Develop PHP web applications to demonstrate 43
string functions.
7 Forms & Input Data
i. Develop a PHP web application to display a
user registration form and show data filled out by
the user after submission. 46
ii. Update the above web application to validate
user data.
8 Images & Files
i. Develop a simple PHP web application to
collect user feedback and store the feedback in
atext file. 53
ii. Develop a PHP web application to upload an
image file into the server and display a
thumbnail of the uploaded image.
9 Subscription & Email
i. Develop a simple PHP web application for
61
newsletter subscription and send a confirmation
email. (Plain & HTML email)
Sessions, Cookies, Exception Handling
i. Develop a PHP web application to demonstrate
10 the use of Session in PHP. 65
ii. Develop a PHP web application to
demonstrate the use of Cookies in PHP.
Exception Handling
11 i. Develop a PHP web application to demonstrate 70
the use of Exception handling in PHP.
Database Operations
i. Perform database operations
usingphpMyAdmin (Create/delete database &
12 tables and run SQL queries). 74
ii. Develop a simple Blog web application that
allows users to create, read, update, and delete
blogs (CRUD operations).
Mini Web Applications
i. Develop a simple MVC web application using
PHP for Contact Management with add, search,
update, and delete operations (CRUD operations
with prevention of SQL Injection).
13 ii. Develop a simple To-Do List web application 84
using PHP with the help of AI code generation
tools such as GitHub Copilot, ChatGPT, Gemini,
etc.
iii. Develop a simple Inventory Management
web application and host it on a web server.
Introduction to Web Development (DI04007011) [Link](617)

Practical No. 1:Environment


Environment Setup & Introduction
Prerequisite Theory:
XAMPP is one of the most popular software pack to set up web application
development environment for PHP with all required software components. XAMPP is
an Open Source AMP stack which stands for forCross
Cross platform, Apache, MariaDB, PHP
and Perl. Apache is cross platform web server, MariaDB is the most widely used
databasee developed by MySQL, PHP is a backend scripting language and Perl is a
programming used for web development. X denotes Cross-platform,
platform, which means that
it can work on different platforms such as Windows, Linux, and macOS.
XAMPP allows a local host or server to test its website and clients on computers and
laptops before releasing them to the main server. It provides a suitable environment for
testing and verifying the functioning working of projects based on Apache, Perl,
MySQL database, and PHP on the host's system. It also includes administrative tools
such as phpMyAdmin, Filezilla FTP Server, Mercury mail server and JSP Tomcat
server.

Procedure:
Below steps describes installation of XAMPP on Windows operating system. Steps are
similar for Linux and Mac
ac operating systems.
i. Install XAMPP
1. Open the XAMPP website. Go to [Link] in
your computer's web browser.

Download latest XAMPP for Windows operating system.


2. Once the XAMPP setup has been downloaded, you can start the installation by
double clicking on the .exe file.
3. An active antivirus program can interfere with the installation process, so it is best
to temporarily disable any antivirus software until all XAMPP components
compo have
been successfully installed.
Introduction to Web Development (DI04007011) [Link](617)

4. Because User Account Control (UAC) restricts writing access to the C: drive and
can interfere with the XAMPP installation, it is recommended that this be disabled
for the duration of the installation.

5. After that the start screen of the XAMPP setup wizard should appear
automatically. Click on ‘Next’ to configure the installation settings.

6. Under ‘Select Components’, you have the option to exclude individual


components of the XAMPP software bundle from the installa
installation.
tion. But for a full
local test server, we recommend you install using the standard setup and all
available components. After making your choice, click ‘Next’.
Introduction to Web Development (DI04007011) [Link](617)

7. In this next step, you have the chance to choose where you’d like the XAMPP
software packet to be installed. If you opt for the standard setup, then a folder with
the name xampp will be created under C:\ for you. After you’ve chosen a location,
click ‘Next’.

8. Select the language in the next dialog box.

9. On Ready to Install screen click on “Next”.

10. Once all the preferences have been decided, click to start the installation. The
setup wizard will unpack and install the selected components and save them to the
designated directory. This process may take few minutes.
Introduction to Web Development (DI04007011) [Link](617)

11. Your Firewall may interrupt the installation process to block the some components
of the XAMPP. Use the corresponding check box to enable communication
between the Apache server and your private network or work network. Remember
that making your XAMPP server available for public network networks isn’t
recommended.
12. Once all the components are unpacked and installed, you can close the setup
wizard by clicking on ‘Finish’. Click to tick the corresponding check box and
open the XAMPP Control Panel once the installation process is finished.

13. XAMPP Control Panel provides controls for the individual components of your
xampp test server. The control panel user interface allows you to start or stop
individual modules: Apache, MySQL, FileZilla, Mercury and Tomcat. The
XAMPP Control Panel also offers you various other buttons, including:
Config: allows you to configure the XAMPP as well as the individual components
Netstat: shows all running processes on the local computer
Shell: opens a UNIX shell
Explorer: opens the XAMPP folder in Windows Explorer
Services: shows all services currently running in the background
Help: offers links to user forums
Quit: closes the XAMPP Control Panel
Introduction to Web Development (DI04007011) [Link](617)

14. Individual modules can be started or stopped on the XAMPP Control Panel
through the corresponding buttons under ‘Actions’. You can see which modules
have been started because their names are highlighted green under the ‘Module’
title.

If a module can’t be started as a result of an error, you’ll be informed of this


straight away in red font. A detailed error report can help you
you identify the cause of
the issue.
15. You have an ‘Admin’ option located on the Control Panel for every module in
your XAMPP.
16. Click on the Admin button of your Apache server to go to the web address of your
web server. The Control Panel will now start in you
yourr standard browser, and you’ll
be led to the dashboard of your XAMPP’s local host. The dashboard features
numerous links to websites for useful information as well as the open source
project BitNami, which offers you many different applications for your XAMPP,
XA
like WordPress or other content management systems. Alternatively, you can
reach the dashboard through localhost/dashboard/.
Introduction to Web Development (DI04007011) [Link](617)

17. You can use the Admin button of your database module to open phpMyAdmin.
Here, you can manage the databases of your web proj
projects
ects that you’re testing on
your XAMPP. Alternatively, you can reach the administration section of your
MySQL database via localhost/phpmyadmin/

ii. Testing XAMPP installation


To check whether your test server is installed and configured correctly, you have the
option to create a PHP test page, store them on your XAMPP’s local host, and retrieve
them via the web browser.
18. Open the XAMPP directory through the ‘Explorer’ button in the Control Panel
and choose the folder htdocs (C:\xampp\htdocs for standard installations). This
directory should store all the web pages that you want to test on your XAMPP
server. The htdocs folder should already contain data to help configuration of the
web server. But you should store your own projects in a new folder
folder (for example
‘test’ folder).
19. You can create a new PHP file with below code in your editor and storing it as
[Link] in your ‘test’ folder (C:\xampp\htdocs\test):
Introduction to Web Development (DI04007011) [Link](617)

20. Now open a web browser and load your PHP page via localhost/test/[Link]. If
your browser
owser window displays the words ‘Hello World’, then you’ve successfully
installed and configured your XAMPP.

Source Code &Output:


i. Install and configure a local web server using XAMPP/WAMP/LAMP.
Snapshot of XAMPP Control Panel after installation
installation.
Output:
Introduction to Web Development (DI04007011) [Link](617)

ii. Create a web page using PHP that displays a welcome message.
Source Code:

Output:

SIGN OF FACULTY:

8
Introduction to Web Development (DI04007011) G. P., Ahmedabad (617)

Practical No. 2:Variables, Constants & Operators


Prerequisite Theory:
Variables:
A variable is a named area of storage, where you can store a value.
 In PHP, variables are represented by a dollar sign ($) followed by the name of
the variable.
 Variable namesare case-sensitive. For example,$var and $Var are two different
variables.
 A valid variable name starts with a letter or underscore, followed by any number
of letters, numbers, or underscores.
 A PHP variable name cannot contain spaces.
 For example,$enrollmentno, $subject_name, $_itemid are valid variable names
and $12var, $student name, part_id are invalid variable names.
 PHP is loosely-typed language, so it doesn’t need to specify data type of
variables. It automatically analyse assigned value and defined data type of
variable.
 Assignment Operator (=) is used to assign the value to a [Link] example,
$subject_name = “Introduction to Web Development”;
PHP has total eight different data types which can be used to define variables:
 Integers − whole numbers, without a decimal point. E.g. – 415, 8341.
 Doubles − floating-point numbers. E.g. – 12.5, 3.14.
 Booleans − two possible values either TRUE or FALSE.
 NULL − special type that only has one value: NULL.
 Strings − sequences of characters. E.g. - 'Introduction to Web Development'.
 Arrays − named and indexed collections of other values.
 Objects − instances of programmer-defined classes
 Resources − special variables that hold references to resources external to PHP.
(such as database connections).
Constants:
Constants are like variables, except that once they are defined, they cannot be changed
or undefined.A valid constant name starts with a letter or underscore, but NO $ sign
before the constant name.

Unlike variables, constants are automatically [Link] can be made using the
define() function or const keyword.

Syntax: define(name, value, case-insensitive);


case-insensitive is optional. Its default value is false.
e.g. define(PI, 3.14);

Syntax: const name = value;


e.g. const PI = 3.14;

9
Introduction to Web Development (DI04007011) G. P., Ahmedabad (617)

Operators:
Operator is a symbol used to perform operations on operands (variables or values).For
example:
$a = $b + 10;
Above code uses arithmetic operator (+) to add 10 to variable $b and assign it to $a.
PHP operators can be categorized into following types:
Arithmetic Operators:
Operator Name Example Description
+ Addition $a + $b Sum of two operands
- Subtraction $a - $b Difference of two operands
* Multiplication $a * $b Multiply tow operands
/ Division $a / $b Quotient of operands
% Modulo $a % $b Reminder of operands
++ Increment $a++ Same as $a = $a + 1
-- Decrement $a-- Same as $a = $a - 1

Assignment Operators:
Operator Name Example Description
$a = $b Value of right operand is assigned to
= Assign
left operand
+= Add then assign $a += $b Same as $a = $a + $b
-= Subtract then assign $a -= $b Same as $a = $a - $b
*= Multiply then assign $a *= $b Same as $a = $a * $b
Divide then assign $a /= $b
/= Same as $a = $a / $b
(Quotient)
Divide then assign $a %= $b
%= Same as $a = $a % $b
(Reminder)

Bitwise Operators:
Operator Name Example Description
$a & $b Bitwise AND operation between $a
& Bitwise AND
and $b
$a | $b Bitwise OR operation between $a and
| Bitwise OR
$b
$a ^ $b Bitwise XOR operation between $a
^ Bitwise XOR
and $b
~ Bitwise NOT ~ $a Bitwise NOT operation on $a
<< Left shift $a << $b Left shift bits of $a by $b steps
>> Right shift $a >> $b Right shift bits of $a by $b steps

10
Introduction to Web Development (DI04007011) G. P., Ahmedabad (617)

Comparison Operators:
Operator Name Example Description
== Equal $a == $b Returns TRUE if $a is equal to $b
!= Not equal $a != $b Returns TRUE if $a is not equal to $b
<> Not equal $a <> $b Returns TRUE if $a is not equal to $b
$a === $b Returns TRUE if $a and $b are equal
=== Identical
and of same data type
$a !== $b Returns TRUE if $a and $b are not
!== Not identical
equal or of different data type
< Less than $a < $b Returns TRUE if $a is less than $b
> Greater than $a > $b Returns TRUE if $a is greater than $b
$a <= $b Returns TRUE if $a is less than or
<= Less than or equal to
equal to $b
Greater than or equal $a >= $b Returns TRUE if $a is greater than or
>=
to equal to $b
$a <=> $b Return -1 if $a is less than $b
<=> Spaceship Return 0 if $a is equal $b
Return 1 if $a is greater than $b

Logical Operators:
Operator Name Example Description
$a and $b Returns TRUE if both $a and $b are
and Logical AND
true
$a or $b Returns TRUE if either $a or $b is
or Logical OR
true
$a xor $b Returns TRUE if either $a or $b is
xor Logical XOR
true, but not both are TRUE
! Logical NOT !$a Returns TRUE if $a is FALSE
$a && $b Returns TRUE if both $a and $b are
&& Logical AND
true
$a || $b Returns TRUE if either $a or $b is
|| Logical OR
true

String Operators:
Operator Name Example Description
. Concatenation $a . $b Concatenate both $a and $b
Concatenation and $a .= $b
.= Same as $a = $a . $b
assign

Expressions

11
Introduction to Web Development (DI04007011) G. P., Ahmedabad (617)

In PHP, anything that has a value is an expression, so most of the statements you write
in PHP scrips are expression. For Example:

$a = $b; // $b is an expression
$a = $b * $c; // $b * $c is an expression
$a = sum($b, $c); // sum($b, $c) is an expression
$b++; // $b++ is an expression

Source code and Output:


i. Develop simple PHP web applications using variables, constants, and operators.
1. Write a script to implement a simple calculator for mathematical operations.
Source Code:

12
Introduction to Web Development (DI04007011) G. P., Ahmedabad (617)

Output:

2. Write a script to make use of constants in PHP.


Source Code:

13
Introduction to Web Development (DI04007011) G. P., Ahmedabad (617)

Output:

3. A company has following payment scheme for their staff:


• Net Salary = Gross Salary – Deduction
• Gross Salary = Basic pay + DA + HRA + Medical
• Deduction = Insurance + PF
where, DA (Dearness Allowance) = 50% of Basic pay
HRA (House Rent Allowance) = 10% of Basic pay
Medical = 4% of Basic pay
Insurance = 7% of Gross salary
PF (Provident Fund) = 5% of Gross salary
Write a script to take the basic salary of an employee as input and calculate the net payment
to any employee.
Source Code:

14
Introduction to Web Development (DI04007011) G. P., Ahmedabad (617)

Output:

4. Write script for logical, comparison and bitwise operators.


Source Code:

15
Introduction to Web Development (DI04007011) G. P., Ahmedabad (617)

16
Introduction to Web Development (DI04007011) G. P., Ahmedabad (617)

Output:

SIGN OF FACULTY:

17
Practical No. 3:Control & Looping Structures
Prerequisite Theory:
Control Structures (Decision Making Statements):
Controls statements are used to control are used to control the flow of execution of
program based on certain conditions. In PHP, there are following decision making
statements:
 if statement
 if...else statement
 if...elseif...else statement
 switch statement

if statement:
if statement allow us to run a block of code if certain condition is true. If condition is
false it will not execute block of code.

if(condition) {
Block of code // statements to execute if condition is
// true
}

if...elsestatement:
if...else executes a block of code if certain condition is true and another block of code if
condition is false.

if(condition) {
Block of code // statements to execute if
// condition is true
}
else {
Block of code // statements to execute if
// condition is false
}

if...elseif...else statement:
It is similar to multiple if...else statements. It executes different blocks of code
based on different conditions.

18
if(condition) {
Block of code // statements to execute if this
// condition is true
}
elseif(condition) {
Block of code // statements to execute if this
// condition is true
} elseif(condition) {
Block of code // statements to execute if this
// condition is true
} else {
Block of code // statements to execute if all
// conditions are false
}

switch statement:
The switch statement is used to perform different actions based on different conditions.
Use the switch statement to select one of many blocks of code to be executed.

switch(n) {
case value1:
code to be executed if n== value1;
break;
case value2:
code to be executed if n== value2;
break;
case value3:
code to be executed if n== value3;
break;
case value4:
code to be executed if n== value4;
break;
......
default:
code to be executed if n != any case;
}

Looping Structures:
Loops in PHP are used to execute the same block of code a specified number of times.
PHP supports below loop statements:
 while loop
 do...while loop
 for loop
 foreach loop
while loop:

19
while loop executes a block of code as long as the specified condition is true.
while(condition) {
Block of code // statements to execute
// till condition is true
}

do...while loop:
do...while loop executes a block of code once, and then repeats the loop as long as the
specified condition is true
do {
Block of code // statements to execute till
// condition is true. Executed once
// before checking condition.
} while(condition);

for loop:
for loop executes a block of code a specified number of times.

for(init counter; condition; increment/decrement counter) {


Block of code // statements to execute
// till condition is true
}

foreach loop:
foreach loop executes a block of code for each element in an array.

foreach ($array as $val) {


Block of code // statements to execute
// for each element in an array
}

break statement:
break statement is used to terminate the execution of a loop prematurely.

while(condition1) {
Block of code // statements to execute
// till condition1 is true
if(condition2) {
break; // exit while loop is condition2
// is true
}
}

continue statement:
20
continue statement is used to halt the current iteration of a loop and start next iteration
of loop. It does not terminate the loop.
while(condition1) {

if(condition2) {
continue; // if condition2 is true then
// remaining part of the loop will
// not be executed in this
// iteration
}
Block of code // statements to execute
// till condition1 is true
}

Source code and Output:


i. Develop PHP web applications using control structures.
1. Write a script that reads the name of the car and displays the name of the company the
car belongs to as per the below table:
Car Company
Safari, Nexon, Tigor, Tiago Tata
XUV700, XUV300, Bolero Mahindra
i20, Verna, Venue, Creta Hyundai
Swift, Alto, Baleno, Brezza Suzuki

Source Code:

21
Output:

2. Write a script to read the marks of 4 subjects and display the result as per the below
instructions:

22
GTU Mark-
GRADE Range
AA 85 - 100
AB 75 - 84
BB 65 - 74
BC 55 - 64
CC 45 - 54
CD 40 - 44
DD 35 - 39
FF < 35 (FAIL)
 Each of the four subjects is worth 100 marks.
 If a student gets less than 35 marks in any subject, then he/she will be marked as FAIL,
otherwise he/she will be marked as PASS.
The result contains the grades of each individual subject in tabular format as per the
above table.
Source Code:

23
Output:

ii. Develop PHP web applications using looping structures.

3. Write a script to display Fibonacci numbers up to a given number.

24
Source Code:

Output:

4. Write a script to display a multiplication table for the given number.


Source Code:

25
Output:

SIGN OF FACULTY:

26
Practical No. 4: Functions
Prerequisite Theory:
A function is a block of code written in a program to perform some specific task.
Functions take inputs as parameters, executes a block of statements or perform
operations on these parameters and returns the result. There are two types of functions
in PHP:
 Built-in functions: PHP provides large collection of built-in library functions
(more than 1000 functions). Whenever we need, we can just call these built-in
functions as per our requirements.
 User defined functions: PHP allows us to create our own customised functions
called user defined functions. We can create our own packages of code and use
them whenever required.
User defined functions:
User defined functions are defined as below:

function functionname() {
Block of code;
}

Note: A function name must start with a letter or an underscore. Function names are
NOT case-sensitive.
Below code is example of PHP function which prints a message on the browser.

<?php
function writeMessage() {
echo "Welcome to the PHP course..!!";
}

writeMessage (); // function call


?>

Function with arguments:


Data can be passed to functions through arguments. Arguments are specified inside the
parentheses after the function name. There can be any number of arguments separated
by comma.

27
<?php
function printSubjects($code, $subject) {
echo "Subject name for code $code is $subject <br>";
}

printSubjects("4330701","Scripting Language -Python");


printSubjects("4330702","Relational Database Management
System");
printSubjects("4330703","Basics of Operating System");
printSubjects("4330704","Data Structures and Algorithms");
?>

Arguments are by default passed by value, which means that a copy of the value is
passed to the function, so the original variable that was passed into the function is not
changed when we modify argument in the function. We can pass argument by
reference, where changes made to the argument also change the original variable that
was passed in. The & operator is used to pass variable by reference in argument. Below
example show how to pass argument by reference:

<?php
function incrementVar(&$var) {
$var += 1;
return $var;
}
$a = 5;
$res = incrementVar($a);
echo "Value after increment is $res <br>";
?>

Below example shows how to use default argument:

<?php
function areaofCircle($radius = 10) {
$area = 2 * 3.14 * $radius;
echo "Area of Circle is : $area <br>";
}

areaofCircle();
areaofCircle(20);
?>

Function with returning value:


Function can return a value using return statements:

28
<?php
function sumArray($arr) {
$sum = 0;
for ($i = 0; $i < count($arr); $i++) {
$sum += $arr[$i];
}
return $sum;
}
$a = array(4, 9, 11, 25, 17);
$s = sumArray($a);

echo "Sum of array is: $s <br>";


?>

Source code and Output:


i. Develop PHP web applications using user defined functions.
1. Consider a currency system in which there are notes of 7 denominations, namely Rs. 1,
Rs. 2, Rs. 5, Rs. 10, Rs. 20, Rs. 50 and Rs. 100. Write a function that computes the
smallest number of notes that will combine for a given amount of money.
Source Code:

29
Output:

2. Write scripts using math functions:


• to generate a random number between the given range.
• to display the binary, octal and hexadecimal of a given decimal number.
• to display the sin, cos and tan of the given angle.
Source Code:

30
Output:

3. Write a script to display the current date and time in different formats.
Source Code:

31
Output:

SIGN OF FACULTY:

32
Practical No. 5: Arrays
Prerequisite Theory:
PHP array is a collection of similar data times stored in a single variable. It is basically
an ordered map, which contains values on the basis of keys/indexes. PHP arrays allows
traversing and processing of data items using a single loop. There are three types of
arrays in PHP.
1. Indexed arrays
2. Associative arrays
3. Multi-dimensional arrays

Indexed/Numeric arrays
This type of arrays can store data of any type. They have integer indexes that start at
zero by default. The Indexed array can be created as follow:

$subject_codes = array(4330701, 4330702, 4330703, 4330704);

Or it can be assigned manually as below:

$subject_codes[0] = 4330701;
$subject_codes[1] =4330702;
$subject_codes[2] =4330703;
$subject_codes[3] =4330704;

Below example shows accessing data stored in the array:

$subject_codes = array(4330701, 4330702, 4330703, 4330704);


echo "Subject codes: <br>";
echo $subject_codes[0] . "<br>";
echo $subject_codes[1] . "<br>";
echo $subject_codes[2] . "<br>";
echo $subject_codes[3] . "<br>";

Another way to access all elements in the array using for loops is as below:

$subject_codes = array(4330701, 4330702, 4330703, 4330704);


echo "Subject codes: <br>";
for($i = 0; $i < count($subject_codes); $i++) {
echo $subject_codes[$i] . "<br>";
}

We can access array data using foreach loop as below:

33
$subject_codes = array(4330701, 4330702, 4330703, 4330704);
echo "Subject codes: <br>";
foreach ($subject_codes as $code) {
echo $code . "<br>";
}

Associative arrays
Associative arrays are similar to indexed arrays but instead of integer indexes values
are assigned to user-defined keys of string type. Below example shows how to assign
associative array:
$subjects = array("4330701" => "SLP",
"4330702" => "RDBMS",
"4330703" => "BOS",
"4330704" => "DSA");
Or it can be assigned manually as below:
$subjects["4330701"] = "SLP";
$subjects["4330702"] = "RDBMS";
$subjects["4330703"] = "BOS";
$subjects["4330704"] = "DSA";
Below example shows accessing data stored in the associative array:
$subjects = array("4330701" => "SLP",
"4330702" => "RDBMS",
"4330703" => "BOS",
"4330704" => "DSA");
echo "Subjects: <br>";
echo $subjects["4330701"] . "<br>";
echo $subjects["4330702"] . "<br>";
echo $subjects["4330703"] . "<br>";
echo $subjects["4330704"] . "<br>";

We can access associative array data using foreach loop as below:


$subjects = array("4330701" => "SLP",
"4330702" => "RDBMS",
"4330703" => "BOS",
"4330704" => "DSA");
echo "Subjects: <br>";
foreach ($subjects as $code => $sub) {
echo $code . ": " . $sub . "<br>";
}

Multidimensional arrays
34
A multidimensional array is an array containing one or more arrays. PHP supports
multidimensional array that are two or more levels deep. However, arrays more than
three levels are hard to manage. Below is example of two-dimensional array:
$subjects = array (
array("4330701","SLP",150),
array("4330702","RDBMS",150),
array("4330703","BOS",150),
array("4330704","DSA",150)
);

Below example shows a way to access all elements in the multidimensional array using
for loops is as below:
$subjects = array (
array("4330701","SLP",150),
array("4330702","RDBMS",150),
array("4330703","BOS",150),
array("4330704","DSA",150)
);

for ($row = 0; $row < count($subjects); $row++) {


echo "Subject " . $row . ": <br>";
for ($col = 0; $col < count($subjects[0]); $col++) {
echo $subjects[$row][$col] . "<br>";
}
}

Source code and Output:


i. Develop PHP web applications that demonstrate the use of indexed, associative arrays, and
multidimensional [Link]. Develop PHP web applications to process data stored in arrays.
1. Write a script to calculate the length of a string and count the number of words in the
given string without using string functions (Hint: Use String as Character Array).
Source Code:

35
Output:

2. Write a script to sort a given indexed array.


Source Code:

36
Output:

37
3. Write a script to perform addition of 3 x 3 matrix.
Source Code:

38
Output:

4. Write a script to encode a given message into equivalent Morse code.


Source Code:

39
Output:

40
iii. Develop PHP web applications to demonstrate array functions.

5. Write PHP script to make use of array-related library functions like count, list, in_array,
current,next, previous, end, each, sort, array_merge, array_reverse
Source Code:

41
Output:

SIGN OF FACULTY:

Practical No. 6:Strings


Prerequisite Theory:
PHP handles strings in several flexible ways, ranging from simple quotes to complex
multi-line formats.
PHP String Syntaxes:

42
1. Single Quoted (' ')
The simplest way to specify a string. It does not interpret variables or most escape
sequences (except \' and \\).
$name = 'World'; echo 'Hello $name'; // Outputs: Hello $name
2. Double Quoted (" ")
The most common syntax. It interpolates variables (replaces variable names with their
values) and supports various escape sequences like \n (newline) or \t (tab).
$name = 'World'; echo "Hello $name"; // Outputs: Hello World
3. Heredoc (<<<Label)
Acts like a double-quoted string but is ideal for multi-line text. It preserves formatting
and interpolates variables.
$text = <<<EOD
This is a multi-line
string for $name.
EOD;
4. Nowdoc (<<<'Label')
The "single-quoted" version of Heredoc. It does not interpolate variables. It’s useful for
embedding code or large blocks of raw text.
$text = <<<'EOD'
Variables like $name won't expand here.
EOD;

Operations: Creating, Searching & More


1. Creating & Accessing: Strings are created by assignment. You can access
individual characters using square brackets (zero-indexed).
$str = "Hello"; echo $str[0]; // Outputs: H
2. Searching: Finding the position of a substring.
3. Replacing: Swapping parts of a string with new text.
4. Formatting: Using functions like sprintf() to return a formatted string based on a
template.
5. Encoding & Escaping: Essential for security (e.g., htmlspecialchars() for XSS
protection) and handling different character sets like UTF-8.

String-Related Library Functions

43
Function Description Example
chr($n) Returns a character from an ASCII chr(65) // "A"
value.
ord($s) Returns the ASCII value of the first ord("A") // 65
character.
strtolower() Converts string to lowercase. strtolower("HEY") // "hey"
strtoupper() Converts string to uppercase. strtoupper("hey") // "HEY"
strlen() Returns the length of the string. strlen("abc") // 3
ltrim() / rtrim() Strips whitespace from the left or ltrim(" x") // "x"
right.
trim() Strips whitespace from both ends. trim(" x ") // "x"
substr() Returns a portion of a string. substr("Hello", 1, 2) // "el"
strcmp() Case-sensitive string comparison. strcmp("a", "A") // Non-zero
strcasecmp() Case-insensitive string comparison. strcasecmp("a", "A") // 0
strpos() Finds the position of the first strpos("abc", "b") // 1
occurrence.
stristr() Case-insensitive strstr; finds first stristr("Hello", "e") // "ello"
occurrence.
str_replace() Replaces all occurrences of a search str_replace("a", "b", "aa") //
string. "bb"
strrev() Reverses a string. strrev("abc") // "cba"

Source code and Output:


i. Develop PHP web applications to demonstrate string functions.
1. Write scripts using string functions:
 to check if the given string is lowercase or not.
 to reverse the given string.
 to remove white spaces from the given string.
 to replace the given word from the given string.

Source Code:

44
Output:

SIGN OF FACULTY:

45
Practical No. 7:Forms & Input Data
Prerequisite Theory:
Web forms are one of the most common ways for a user to interact with a
web application. Forms allow users to enter data, which is typically sent to a web server
for processing and storage or used on the client-side to update the interface in some
way immediately.
The HTML of a web form is made up of one or more form controls (also known as
widgets) and some additional elements to help structure the overall form - these are
commonly referred to as HTML forms. Most common controls are single or multi-line
text boxes, dropdown boxes, buttons, checkboxes and radio buttons. There are some
other elements such as date, time, day color, file etc. Form controls can also be
programmed to enforce specific formats or values to be entered (form validation).
Define HTML Form:
The HTML <form> element is used to create an HTML form for user input:

<form>
...
form elements
...
</form>

Define HTML Form Element:


HTML form elements are mostly created using the <input> element.

<formaction="/[Link]" method="get">
<label for="uname">User Name:</label><br>
<input type="text" id="uname" name="uname"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password">
<input type="submit" value="Submit">
</form>

 The <label> tag defines a label for many form elements. The <label> element is
useful for screen-reader users, because the screen-reader will read out loud the
label when the user focus on the input element.
 The <input type="submit"> defines a button for submitting the form data to a
form-handler. The form-handler is typically a file on the server with a script for
processing input data.
 The action attribute defines the action to be performed when the form is
submitted. Usually, the form data is sent to a file on the server when the user
clicks on the submit button.
 The method attribute specifies the HTTP method to be used when submitting the
form data. The form-data can be sent as URL variables (with method="get") or as
HTTP post transaction (with method="post").

46
 The HTML id attribute is used to specify a unique id for an HTML element. You
cannot have more than one element with the same id in an HTML document.
 Each input field must have a name attribute to be submitted. If the name attribute
is omitted, the value of the input field will not be sent at all. It is used by PHP
script to read form data from that input element.
 The type attribute defines type of input element. By default value of the type
attribute is "text". Different types of input elements are as follow:

Element Type Description


<input type="text"> Displays a single-line text input field.
<input type="radio"> Displays a radio button (for selecting one of many choices)
<input type="checkbox"> Displays a checkbox (for selecting choices)
<input type="submit"> Displays a submit button (for submitting the form)
<input type="button"> Displays a clickable button
<input type="reset"> Displays a reset button (for resetting the form)
<input type="search"> Displays a text input field for search field.
<input type="password"> Displays a text input field for password.
<input type="number"> Displays a text input field for numbers.
<input type="tel"> Displays a text input field for telephone.
<input type="url"> Displays a text input field for URL.
<input type="email"> Displays a text input field for email.
<input type="range"> Displays a range slider.
<input type="file"> Displays a file-select field and a "Browse" button for file
uploads
<input type="color"> Displays an input field for color picker.
<input type="datetime-local"> Displays a date and time input field, with no time zone
<input type="date"> Displays an input fields for date
<input type="time"> Displays an input fields for time.
<input type="month"> Displays an input fields for month.
<input type="week"> Displays an input fields for week.
<textarea> … <textarea> Displays a multi-line plain-text input field.

TextBox:
The <input type="text"> provides a single-line input field to input text.

47
<form action="/[Link]" method="get">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
<input type="submit" value="Submit">
</form>

Radio Button:
Radio Button allows user to select only one choice from a limited number of choices.

<form action="/[Link]" method="get">


<input type="radio" id="male" name="gender"value="male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender"
value="female">
<label for="female">Female</label><br>
<input type="radio" id="other" name="gender" value="other">
<label for="other">Other</label>
<input type="submit" value="Submit">
</form>

Check Box:
Check Box allows a user to select zero or more choices from a limited number of
choices.

<form action="/[Link]" method="get">


<input type="checkbox" id="fruit1" name="friut1"
value="Mango">
<label for=" fruit1">Mango</label><br>

<input type="checkbox" id="fruit2" name="friut2"


value="Banana">
<label for=" fruit2">Banana</label><br>

<input type="checkbox" id="fruit3" name="friut3"


value="Grapes">
<label for=" fruit3">Grapes </label><br>
<input type="submit" value="Submit">
</form>

In PHP, validating and sanitizing form data is the most critical step in preventing
security vulnerabilities like Cross-Site Scripting (XSS) and SQL [Link] is a

48
breakdown of the common functions used to ensure data is safe, present, and in the
correct format.

1. Checking Presence & State


These functions help you determine if a user actually submitted a field or left it blank.
isset(): Checks if a variable is declared and is not null. Use this to see if a specific
button or input was sent in the $_POST array.
if (isset($_POST['submit'])) { ... }
empty(): Returns true if a variable is an empty string, 0, false, null, or an empty array.
if (empty($_POST['username'])) { echo "Username is required";
}

2. Cleaning & Sanitizing


Before you check if the data is "right," you often need to clean it of accidental spaces or
malicious code.
trim(): (Note: PHP uses trim(), not strip()). It removes whitespace from the beginning
and end of a string.
$name = trim($_POST['name']);
htmlspecialchars(): Converts special characters (like < and >) into HTML entities
(&lt; and &gt;). This prevents browsers from executing user input as code (XSS
protection).
echo htmlspecialchars("<script>alert(1)</script>"); // Safely
prints the text.

3. Type & Length Validation


These ensure the data matches your requirements (e.g., age must be a number).
is_numeric(): Checks if a variable is a number or a numeric string.
if (!is_numeric($_POST['age'])){ echo "Enter a valid number";
}
strlen(): Returns the number of characters in a string. Great for password or username
length requirements.
if (strlen($_POST['password']) < 8) { echo "Password short!";
}

4. Advanced Validation with filter_var()


The filter_var() function is the "Swiss Army Knife" of PHP validation. It uses built-in
filters to check complex patterns like emails or URLs.
Validating Email:
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){ echo "Invalid
email format"; }
Validating URL:

49
if (!filter_var($url, FILTER_VALIDATE_URL)) { echo "Invalid
URL"; }

Source code and Output:


i. Develop a PHP web application to display a user registration form and show data filled out
by the user after submission.

ii. Update the above web application to validate user data.


Source Code:

50
51
Output:

SIGN OF FACULTY:

Practical No. 8:Images & Files

52
Prerequisite Theory:
PHP provides a robust set of functions for interacting with the server's file [Link]
is a guide on managing directories and handling text files.

1. Working with Directories


Directories are treated like containers that you can open, read, and manipulate.
 mkdir(): Creates a new directory.
mkdir("uploads", 0755); //Creates "uploads" with specific
permissions
 rmdir(): Removes an empty directory.
rmdir("old_data");
 scandir(): Returns an array of files and directories inside a specified path.
$files = scandir("images");
 is_dir(): Checks if the given path is a directory.
if (is_dir("assets")) { echo "It's a folder!"; }

2. Reading Text Files


There are two main ways to read files: the "all-at-once" approach and the "line-by-line"
approach.
 The Quick Way (file_get_contents)
Best for smaller files when you want the entire content in one variable.
$content = file_get_contents("[Link]");
echo $content;
 The Stream Way (fopen + fgets)
Best for large files to save memory by reading one line at a time.
$file = fopen("[Link]", "r"); // "r" stands for read-only
while (!feof($file)) {
echo fgets($file) . "<br>";
}
fclose($file);

3. Writing Text Files


Like reading, you can overwrite a file or append new data to the end.
 The Quick Way (file_put_contents)
By default, this overwrites the file. Use the FILE_APPEND flag to add to the end
instead.
file_put_contents("[Link]", "New content here!");
// To append: file_put_contents("[Link]", " More text",
FILE_APPEND);
 The Stream Way (fopen + fwrite)
Gives you more control over the file pointer.

53
$file = fopen("[Link]", "w");
// "w" creates/overwrites; "a" appends
fwrite($file, "Adding a line of text.");
fclose($file);

4. Common File Modes for fopen()

Mode Description
'r' Read only; starts at the beginning of the file.
Write only; truncates (deletes) file content or creates it
'w'
if it doesn't exist.
Append; opens for writing but preserves existing
'a'
content, adding new data to the end.
'r+' Read and Write; starts at the beginning.

Handling file uploads and downloads involves a combination of HTML forms and
PHP’s server-side filesystem functions.

5. Uploading Files
To upload files, you must use an HTML form with the method="POST" and the
specific attribute enctype="multipart/form-data".
 The HTML Logic
<form action="[Link]" method="POST"
enctype="multipart/form-data">
Select image to upload:
<input type="file" name="myFile">
<button type="submit">Upload</button>
</form>
 The PHP Logic ([Link])
When a file is uploaded, PHP stores it in a temporary location. You must move it to
your desired folder using move_uploaded_file(). Data about the file is stored in the
$_FILES superglobal array.
if (isset($_FILES['myFile'])) {
$file = $_FILES['myFile'];
$fileName = $file['name'];
$fileTmp = $file['tmp_name'];
$dest = "uploads/" . $fileName;
if (move_uploaded_file($fileTmp, $dest)) {
echo "File uploaded successfully!";
} else {
echo "Upload failed.";
}
}

6. Display uploaded file as a thumbnail


To display an uploaded image as a thumbnail, you need to render theuploaded file’s
path within an HTML <img> tag.

54
When the file is moved via move_uploaded_file(), you store the path in a variable and
then echo that path into the src attribute of an image tag.
if (isset($_POST['submit'])) {
$targetDir = "uploads/";
$fileName = basename($_FILES["myImage"]["name"]);
$targetFilePath = $targetDir . $fileName;

if (move_uploaded_file($_FILES["myImage"]["tmp_name"],
$targetFilePath)) {
echo "<h3>Uploaded Thumbnail:</h3>";
echo '<img src="' . $targetFilePath . '"
style="width:150px; height:auto; border:1px solid #ccc;
padding:5px;">';
}
}

Source code and Output:


i. Develop a simple PHP web application to collect user feedback and store the feedback in a
text file.
Source Code:

55
Output:

56
ii. Develop a PHP web application to upload an image file into the server and display a
thumbnail of the uploaded image.
Source Code:

57
58
Output:

59
SIGN OF FACULTY:

60
Practical No. 9:Subscription & Email
Prerequisite Theory:
Emailsare widely used for communication purposes in various web applications, such
as sending verification emails, password reset links, newsletters, and order
confirmations.
PHP primarily uses the built-in mail() function to send and receive emails using
different protocols such as SMTP, IMAP, and POP3. Although for complex tasks like
attachments and high-volume newsletters, professional libraries (like PHPMailer or
Symfony Mailer) are often used.
Here are the basic steps to send an email in PHP.
• Configure the SMTP server settings
• Set up the email headers
• Compose the email message
1. Sending Plain Text Email
This is the simplest form of communication. It sends unformatted text without any
styling.
$to = "user@[Link]";
$subject = "Welcome!";
$message = "Hello, thank you for joining our site.";
$headers = "From: webmaster@[Link]";

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


echo "Email sent successfully.";
}
2. Sending HTML Email
To send formatted text (bold, colors, links), you must change the Content-type in the
email headers to text/[Link]:Always use \r\n (carriage return + newline) to separate
headers.
$to = "user@[Link]";
$subject = "Special Offer";
$message = "
<html>
<head><title>Monthly Special</title></head>
<body>
<h1 style='color:blue;'>Big Sale!</h1>
<p>Check out our <a
href='[Link]
</body>
</html>
";
$headers = "MIME-Version: 1.0". "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "From: sales@[Link]" . "\r\n";

mail($to, $subject, $message, $headers);

61
3. Email with Attachments
Sending attachments with the native mail() function is highly complex because it
requires "Multipart/Mixed" MIME boundaries to separate the text from the file data
(which must be encoded in Base64).
The easier way isusing PHPMailer library, because native PHP code for attachments is
long and prone to errors.
use PHPMailer\PHPMailer\PHPMailer;

$mail = new PHPMailer();


$mail->setFrom('from@[Link]', 'Your Name');
$mail->addAddress('recipient@[Link]');
$mail->Subject = 'File Attachment';
$mail->Body = 'See the attached PDF for details.';

// Adding the attachment


$mail->addAttachment('documents/[Link]');

$mail->send();

Source code and Output:


i. Develop a simple PHP web application for newsletter subscription and send a confirmation
email. (Plain & HTML email)
Source Code:

62
Output:

63
SIGN OF FACULTY:

64
Practical No. 10:Session, Cookies
Prerequisite Theory:
In PHP, sessions and cookies are two mechanisms used to store and manage data
related to a user's interaction with a website or web application.
Session
Sessions are a way of storing information on the server about a user's activity on a
website. When a user visits a website, the server assigns them a unique session ID,
which is stored in a cookie on the user's computer. The server then uses this session ID
to keep track of the user's activity as they move around the website. The session data
can include things like user preferences, shopping cart items, or authentication status.
Sessions can be started using the session_start() function and the session data can be
accessed through the $_SESSION superglobal array.
Cookie
Cookies are small text files that are stored on a user's computer by their web browser.
Cookies are often used to remember user preferences or login information, or to track
user behavior across different pages or sessions. In PHP, cookies can be set using the
setcookie() function. Cookies can have an expiration time, after which they are
automatically deleted, or they can be set to expire when the user closes their browser.
Cookie data can be accessed using the $_COOKIE superglobal array.
Comparison
Both sessions and cookies have their advantages and disadvantages. Sessions are
generally more secure because the data is stored on the server, but they can be slower
and less flexible. Cookies are faster and more flexible, but they can be less secure
because the data is stored on the user's computer. When using cookies, it's important to
make sure that sensitive information, such as passwords or credit card numbers, is not
stored in the cookie.
In summary, sessions and cookies are two important mechanisms used to store and
manage user-related data in PHP. By understanding how to use these mechanisms
correctly, developers can create more secure and user-friendly web applications.
Examples
Using Session
Start the session using the session_start() function.

<?php
session_start();
>

Set a session variable.

65
<?php
$_SESSION[‘username’] = ‘Ashish’;
>

Access the session variable on another page.

<?php
session_start();
echo "Welcome " .$_SESSION[‘username’];
>

Using Cookie
Set a cookie using the setcookie() function.

<?php
$cookie_name "username";
$cookie_value = "Ashish";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>

Access the cookie value.

<?php
if(isset($_COOKIE [$cookie_name])) {
echo "Welcome". $_COOKIE [$cookie_name];
}
?>

Note that when using sessions and cookies, it's important to be careful about what data
is stored and how it's accessed, to prevent security issues. For example, sensitive
information like passwords or credit card numbers should never be stored in a cookie or
session.

Source code and Output:


i. Develop a PHP web application to demonstrate the use of Session in PHP.
Source Code:

66
Output:

67
ii. Develop a PHP web application to demonstrate the use of Cookies in PHP.
Source Code:

68
Output:

SIGN OF FACULTY:

Practical No. 11:Exception Handling


Prerequisite Theory:

69
Exception Handling is a way to change the normal flow of a script when a specified
error (an exception) occurs. This allows you to handle errors gracefully instead of
letting the script crash with a "Fatal Error".
1. The Core Components
try: The block of code where you expect something might go wrong.
throw: Used to trigger an exception. You "throw" an Exception object.
catch: The block of code that executes only if an exception was thrown in the try
block. It "catches" the error object to handle it.
finally: A block that always runs after the try and catch blocks, regardless of whether
an exception was thrown or not. This is perfect for cleanup tasks (like closing a
database connection).
2. Practical Example: Division by Zero
A common programming error is dividing by zero. Here is how you handle it using
exceptions:
function divide($numerator, $denominator) {
if ($denominator == 0) {
// Trigger an exception
throw new Exception("Division by zero error!");
}
return $numerator / $denominator;
}

try {
// Attempting the operation
echo divide(10, 0);
}
catch (Exception $e) {
// Handle the error
echo "Caught exception: " . $e->getMessage() . "\n";
}
finally {
// This always runs
echo "Process complete.";
}
3. Creating Custom Exceptions
You can create your own exception classes by extending the base Exception class. This
is useful for categorizing errors (e.g., DatabaseException, ValidationException).

70
class InvalidEmailException extends Exception {}

function checkEmail($email) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new InvalidEmailException("The email address
is not valid.");
}
}

try {
checkEmail("wrong-email");
} catch (InvalidEmailException $e) {
echo "Email Error: " . $e->getMessage();
} catch (Exception $e) {
echo "General Error: " . $e->getMessage();
}
4. Comparison of Error Handling vs. Exceptions

Feature Traditional Error Handling Exception Handling


Cleanly bubbles up to the nearest
Control Hard to manage nested errors.
catch.
Often stops execution
Response Allows for recovery or logging.
immediately.
Separates error logic from
Structure Uses if/else checks everywhere.
business logic.
5. Why use finally?
The finally block is essential for resource management. For example, if you open a
file in the try block and an error occurs, the code that closes the file might be skipped.
Putting the fclose() in the finally block ensures the file is closed even if the script fails.

Source code and Output:


i. Develop a PHP web application to demonstrate the use of Exception handling in PHP.
(Include all the required blocks like try, throw, catch and finally)
Source Code:

71
Output:

72
SIGN OF FACULTY:

73
Practical No. 12:Database Operations
Prerequisite Theory:
MySQL is a popular relational database management system that is commonly used in
web development with PHP. Here are some MySQL functions that can be used in PHP
to interact with MySQL databases:
mysqli_connect() - This function is used to establish a connection to a MySQL
database server.
mysqli_query() - This function is used to execute a MySQL query on a connected
database.
mysqli_fetch_array() - This function is used to fetch the result of a MySQL query as
an array.
mysqli_insert_id() - This function is used to get the auto-generated ID of the last
inserted record in a table.
mysqli_real_escape_string() - This function is used to escape special characters in a
string to prevent SQL injection attacks.
mysqli_num_rows() - This function is used to get the number of rows returned by a
MySQL query.
mysqli_error() - This function is used to get the error message associated with the
last MySQL operation.
mysqli_close() - This function is used to close the connection to a MySQL database
server.
These are just a few examples of the MySQL functions that can be used in PHP. There
are many other functions available for working with MySQL databases in PHP, and
their usage depends on the specific needs of your application.
Example
Assuming we have a MySQL database with a table named "users" that has columns
"id", "username", and "password", we can use PHP to perform various operations on
this table.
1. Connect to the MySQL database:

74
<?php
$host = "localhost"; $username = "db_user";
$password = "db_password";
$dbname = "my_database";

// Create connection
$conn = mysqli_connect($host, $username, $password, $dbname);

// Check connection
if (!$conn) {
die("Connection failed: mysqli_connect_error());
}
echo "Connected successfully";
?>

2. Insert a new user into the "users" table:

<?php
$username = "john_doe";
$password = "my_password";

// Escape special characters in the username and password to


// prevent SQL injection
$username = mysqli_real_escape_string($conn, $username);
$password mysqli_real_escape_string($conn, $password); =

// Create and execute the SQL query to insert a new user


$sql = "INSERT INTO users (username, password) VALUES
('$username', '$password')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
}
else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
?>

3. Retrieve all users from the "users" table:

75
<?php
// Create and execute the SQL query to retrieve all users
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);

// Check if any rows were returned


if (mysqli_num_rows($result) > 0) {
// Output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: ". $row["id"]. " - Username: " .
$row["username"]. "<br>";
}
}
else {
echo "0 results";
}
?>

4. Update the password for a specific user in the "users" table:

<?php
$username "ashish";
$new_password = "new_password";

// Escape special characters in the username and new password to


// prevent SQL injec
$username = mysqli_real_escape_string($conn, $username);
$new_password = mysqli_real_escape_string($conn, $new_password);

// Create and execute the SQL query to update the password for a
// specific user
$sql = "UPDATE users SET password='$new_password' WHERE
username='$username'
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
}
else {
echo "Error updating record: mysqli_error($conn);
}
?>

76
5. Delete a specific user from the "users" table:

<?php
$username "ashish";

// Escape special characters in the username to prevent SQL


// injection
$username = mysqli_real_escape_string($conn, $username);

// Create and execute the SQL query to delete a specific user


$sql = "DELETE FROM users WHERE username='$username'
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
}
else {
echo "Error deleting record: mysqli_error($conn);
}
?>

Source code and Output:


i. Perform database operations using phpMyAdmin (Create/delete database & tables and run
SQL queries). (Assume table as ‘Students’ and columns as ‘enrollno’ (PK), ‘fullname’,
‘gender’, ‘dob’ and ‘mobileno’)
Source Code:

77
78
Output:

79
ii. Develop a simple Blog web application that allows users to create, read, update, and delete
blogs (CRUD operations).
Source Code:

80
81
Output:

82
SIGN OF FACULTY:

Practical No. 13:Mini Web Applications


Source code and Output:
i. Develop a simple MVC web application using PHP for Contact Management with add,
search, update, and delete operations (CRUD operations with prevention of SQL Injection).
Source Code:

83
84
85
Output:

86
87
ii. Develop a simple To-Do List web application using PHP with the help of AI code
generation tools such as GitHub Copilot, ChatGPT, Gemini, etc.
Source Code:

88
89
90
Output:

91
92
iii. Develop a simple Inventory Management web application and host it on a web server.
Source Code:

93
94
95
Output:

96
97
SIGN OF FACULTY:

98

You might also like