PHP Lab Manual Format
PHP Lab Manual Format
Laboratory Manual
Web Development using PHP
4341604
DTE’s Vision:
● 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.
DTE’s Mission:
Institute’s Vision:
Institute’s Mission:
Department’s Vision:
Department’s Mission:
Web Development using PHP (4341604)
Certificate
has satisfactorily completed the term work in course “Web Development using PHP
(4341604)” for the academic year: ……………………….… Term: Even prescribed in the GTU
curriculum.
Place: ………………………….
Date: ………………………….
Preface
The primary aim of any laboratory/Practical/field work is enhancement of
required skills as well as creative ability amongst students to solve real time problems by
developing relevant competencies in psychomotor domain. Keeping in view, GTU has
designed competency focused outcome-based curriculum -2021 (COGC-2021) for
Diploma engineering programmes. In this more time is allotted to practical work than
theory. It shows importance of enhancement of skills amongst students and it pays
attention to utilize every second of time allotted for practical amongst Students,
Instructors and Lecturers to achieve relevant outcomes by performing rather than writing
practice in study type. It is essential for effective implementation of competency focused
outcome- based Green curriculum-2021. Every practical has been keenly designed to
serve as a tool to develop & enhance relevant industry needed competency in each and
every student. These psychomotor skills are very difficult to develop through traditional
chalk and board content delivery method in the classroom. Accordingly, this lab manual
has been designed to focus on the industry defined relevant outcomes, rather than old
practice of conducting practical to prove concept and theory.
By using this lab manual, students can read procedure one day in advance to actual
performance day of practical experiment which generates interest and also, they can have
idea of judgement of magnitude prior to performance. This in turn enhances
predetermined outcomes amongst students. Each and every Experiment /Practical in this
manual begins by competency, industry relevant skills, course outcomes as well as
practical outcomes which serve as a key role for doing the practical. The students will also
have a clear idea of safety and necessary precautions to be taken while performing
experiment.
This manual also provides guidelines to lecturers to facilitate student-centered lab
activities for each practical/experiment by arranging and managing necessary resources
in order that the students follow the procedures with required safety and necessary
precautions to achieve outcomes. It also gives an idea that how students will be assessed
by providing Rubrics.
Website design is a broad term that encompasses a wide variety of tasks, all involved in
the formation of web pages. There are essentially two types of web design approaches,
which are dynamic and static design. PHP, which stands for "PHP: Hypertext Pre-
processor" is a widely-used Open Source general-purpose scripting language that is
especially suited for web development and can be embedded into HTML. Its syntax draws
upon C, Java, and Perl, and is easy to learn. The main goal of the language is to allow web
developers to write dynamically generated web pages quickly, but you can do much more
with PHP.
Although we try our level best to design this lab manual, but always there are chances of
improvement. We welcome any suggestions for improvement.
3 | Page
Web Development using PHP (4341604)
4 | Page
Web Development using PHP (4341604)
5 | Page
Web Development using PHP (4341604)
5. Arrays
a. Write PHP Script for addition and
multiplication of two 2x2 matrices.
b. Write a PHP Script to count the number of - - - -
elements in an array without using built-in
function (use numeric and associative
arrays).
6. User defined Functions
a. Write a PHP script to call by reference and
call by value.
b. Write a PHP Script for performing function
- - - -
that takes arguments with default argument
and returns value.
c. Write a PHP Script to show the use of
variable length argument.
7. Built-In functions
a. Write PHP script to demonstrate use of
various strings handling function.
b. Write a PHP script to Demonstrate
Include() and require() function.
- - - -
c. Write PHP script to demonstrate Array
functions.
d. Write PHP script to demonstrate use of
fopen(), fread(), fwrite() and fclose() File
functions.
8. Form Handling
a. Create student registration form using text
box, check box, radio button, select, submit
button. And display user inserted value in - - - -
new PHP page using GET or POST Method.
b. Write a PHP script to explain the concept of
$_REQUEST.
9. Email and Validation
a. Write PHP script to validate form including
name, email using appropriate functions.
- - - -
b. Write PHP script for sending plain text
email, HTML email and attachments with
email.
10. Session and Cookies
a. Write a PHP script to demonstrate creating,
deleting, updating, retrieving and passing
- - - -
variable cookie data.
b. Write PHP script to demonstrate passing
information using Session.
6 | Page
Web Development using PHP (4341604)
7 | Page
Web Development using PHP (4341604)
8 | Page
Web Development using PHP (4341604)
9 | Page
Web Development using PHP (4341604)
10 | Page
Web Development using PHP (4341604)
12. Database
a. Write a PHP script to connect with database
server from your webpage.
b. Create a database with student table and
write a PHP script to insert a record in
student table.
c. Write a program to read student records
from student table and display all these
information in table format on output
screen.
d. Write a PHP script to delete and update a
specific record from table.
e. Write a PHP script simple login system that
allows user to add a new username if user
doesn’t exist in the database, also create a
forgot password link, to redirect user to set
up his new password on authentication.
11 | Page
Web Development using PHP (4341604)
Date: _________________
A. Objective:
PHP is a popular scripting language, which is used to develop various web applications.
PHP environment for executing PHP program using WAMP or XAMPP server. This will
help you to write, debug and run the PHP program.
E. Practical Outcome(PrO)
Students will be able install/configure development environment and also write a PHP
script to display Welcome message.
12 | Page
Web Development using PHP (4341604)
G. Prerequisite Theory:
What is PHP?
- PHP was created by Rasmus Lerdorf in 1994 but appeared in the market in 1995.
- PHP stands for Hypertext Pre-processor.
- PHP is a server scripting language.
- PHP scripts are executed on the server.
- PHP is a widely used open-source scripting language, so PHP is free to download
and use.
- PHP is a powerful tool for making dynamic and interactive Web pages.
- PHP is an interpreted language.
- PHP can be embedded into HTML.
- PHP is an object-oriented language.
- PHP is simple and easy to learn language.
13 | Page
Web Development using PHP (4341604)
Environment Setup:
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 Cross platform, Apache, MariaDB, PHP and
Perl. Apache is cross platform web server, MariaDB is the most widely used database
developed by MySQL, PHP is a backend scripting language and Perl is a programming
used for web development. X denotes Cross-platform, which means that it can work on
different platforms such as Windows, Linux, and macOS.
Install XAMPP server on Windows 7 or above.
1. Open the XAMPP website. Go to https://www.apachefriends.org/index.html in
your computer's web browser.
14 | Page
Web Development using PHP (4341604)
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 installation. 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’.
15 | Page
Web Development using PHP (4341604)
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’.
16 | Page
Web Development using PHP (4341604)
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.
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 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
17 | Page
Web Development using PHP (4341604)
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.
18 | Page
Web Development using PHP (4341604)
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 your 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, like
WordPress or other content management systems. Alternatively, you can reach the
dashboard through localhost/dashboard/.
17. You can use the Admin button of your database module to open phpMyAdmin.
Here, you can manage the databases of your web projects that you’re testing on
your XAMPP. Alternatively, you can reach the administration section of your
MySQL database via localhost/phpmyadmin/
19 | Page
Web Development using PHP (4341604)
20. Now open a web browser and load your PHP page via localhost/test/test.php. If
your browser window displays the words ‘Hello World’, then you’ve successfully
installed and configured your XAMPP.
20 | Page
Web Development using PHP (4341604)
H. Resources/Equipment Required
Sr. Instrument/Equipment/
Specification Quantity
No. Components/Trainer kit
Hardware: Computer Computer (i3-i5 preferable), RAM minimum
1
System 2 GB and onwards
2 Operating System Windows/ Linux/ MAC
As Per
3 Software XAMPP server (PHP, Web server, Database) Batch
Size
Notepad, Notepad++, Sublime Text or
4 Text Editor
similar
NA
J. Source code:
K. Input-Output:
21 | Page
Web Development using PHP (4341604)
M. References / Suggestions
1. https://www.w3schools.com/php/default.asp
2. https://www.tutorialspoint.com/php/
3. https://tutorialehtml.com/en/php-tutorial-introduction/
4. www.tizag.com/phpT/
5. https://books.goalkicker.com/PHPBook/
6. https://spoken-tutorial.org/tutorial-
search/?search_foss=PHP+and+MySQL&search_language=English
7. https://codecourse.com/watch/php-basics
8. https://onlinecourses.swayam2.ac.in/aic20_sp32/preview
N. Assessment-Rubrics
Faculty
Marks Obtained Date
Signature
Program Implementation Student’s engagement
Correctness and Presentation in practical activities Total
(4) Methodology (3) (3) (10)
R1 R2 R3
22 | Page
Web Development using PHP (4341604)
Date: _________________
Practical No.2: Variables, Constant and Operators
a. Write a PHP script to demonstrate use of global, local, static
variables and constant.
b. Write a PHP script to demonstrate arithmetic operators,
comparison operator, and logical operator.
c. Write a PHP program to swap two numbers with and without using
third variable.
A. Objective:
23 | Page
Web Development using PHP (4341604)
E. Practical Outcome(PRo)
Students will be able to write a PHP script for different scopes of variable and constant.
Students will be able to write a PHP script for different kind of operators.
G. Prerequisite Theory:
Variable in PHP
Variables in a program are used to store some values, so they are the containers for
storing information. These information can be numeric values, characters, character
strings, or memory addresses.
In PHP, a variable does not need to be declared before adding a value to it. PHP
automatically converts the variable to the correct data type, depending on its value, so
it is called loosely typed variables. After declaring a variable it can be reused
throughout the code. Below rules should be followed if you are dealing with variable in
PHP.
Any variables declared in PHP must begin with a dollar sign ($), followed by
the variable name.
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, a-z, 0-9, and _ ).
Variable names are case-sensitive ($avg and $AVG are two different variables).
The assignment operator (=) used to assign value to a variable.
PHP has a total of eight data types which we use to construct our variables −
Integers − are whole numbers, without a decimal point, like 25, 9876.
Doubles − are floating-point numbers, like 3.14 or 49.19876.
24 | Page
Web Development using PHP (4341604)
Example-1
<?php
// Declaring variables
$txt = "Hello World";
$num = 5;
Scope of Variable
Variable can be declared anywhere in the script in PHP. According to where the
variable can be used/accessed in the script it is divided into three scopes:
Local
Global
Static
Local Scope
The variables declared within a function are called local variables to that function and
have their scope only in that particular function. In simple words, it cannot be accessed
outside that function. Any declaration of a variable outside the function with the same
name as that of the one within the function is a completely different variable.
25 | Page
Web Development using PHP (4341604)
<?php
function test()
{
$a = 10; // local scope
echo "Variable a inside function is: $a <br/>";
}
test();
Global Scope
In PHP, A variable declared outside a function has a global scope and can only be accessed
outside a function.
<?php
$a = 10; // global scope
function test()
{
echo "Variable a inside function is: $a <br/>";
}
test();
To get access within a function we need to use the “global” keyword before the
variable to refer to the global variable.
26 | Page
Web Development using PHP (4341604)
<?php
$a = 10; // global scope
function test()
{
global $a;
echo "Variable a inside function is: $a <br/>";
}
test();
<?php
$a = 10; // global scope
function test()
{
global $a;
echo "Variable a inside function is:”. $GLOBALS['a'] .”<br/>";
}
test();
27 | Page
Web Development using PHP (4341604)
Static Variable
It is the characteristic of PHP to delete the variable, once it completes its execution and
the memory is freed. But sometimes we need to store the variables even after the
completion of function execution. To do this we use the static keywords and the
variables are then called static variables.
<?php
function test()
{
static $a = 10
echo $a .”<br/>”;
$a++;
}
test();
test();
test();
?>
O/P:
10
11
12
Constant
Constants are opposite to variables in terms of that once they are defined they cannot
be changed or undefined. A constant is an identifier (name) for a simple value. The
value cannot be changed during the script. A valid constant name starts with a letter or
underscore (no $ sign before the constant name).
To create a constant, define() function is used.
Syntax:
define(name, value, case-insensitive)
Here,
name: Specifies the name of the constant
value: Specifies the value of the constant
case-insensitive: Specifies whether the constant name should be case-insensitive.
Default is false
28 | Page
Web Development using PHP (4341604)
<?php
// case-sensitive constant
define("TEST", "This is constant.");
echo TEST ."<br/>";
// case-insensitive constant
define("TEST", " This is constant.", true);
echo test;
?>
O/P:
This is constant.
This is constant.
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
variable $a.
PHP operators can be categorized into following types:
Arithmetic Operators:
29 | Page
Web Development using PHP (4341604)
Assignment Operators:
Bitwise Operators:
Comparison Operators:
30 | Page
Web Development using PHP (4341604)
equal to $b
$a <> $b Returns TRUE if $a is not
<> Not equal
equal to $b
$a === $b Returns TRUE if $a and $b are
=== Identical
equal and of same data type
$a !== $b Returns TRUE if $a and $b are
!== Not identical not equal or of different data
type
$a < $b Returns TRUE if $a is less
< Less than
than $b
$a > $b Returns TRUE if $a is greater
> Greater than
than $b
$a <= $b Returns TRUE if $a is less
<= Less than or equal to
than or equal to $b
$a >= $b Returns TRUE if $a is greater
>= Greater than or equal to
than or equal to $b
$a <=> $b Return -1 if $a is less than $b
Return 0 if $a is equal $b
<=> Spaceship
Return 1 if $a is greater than
$b
Logical Operators:
31 | Page
Web Development using PHP (4341604)
String Operators:
H. Resources/Equipment Required
Sr. Instrument/Equipment/
Specification Quantity
No. Components/Trainer kit
Computer (i3-i5 preferable), RAM
1 Hardware: Computer System
minimum 2 GB and onwards
2 Operating System Windows/ Linux/ MAC
As Per
XAMPP server (PHP, Web server, Batch
3 Software
Database) Size
Notepad, Notepad++, Sublime Text or
4 Text Editor
similar
NA
J. Source code:
A) Write a PHP script to demonstrate use of global, local, static variables and constant.
32 | Page
Web Development using PHP (4341604)
A) Input-Output:
33 | Page
Web Development using PHP (4341604)
34 | Page
Web Development using PHP (4341604)
B) Input-Output:
C) Write a PHP program to swap two numbers with and without using third variable.
35 | Page
Web Development using PHP (4341604)
C) Input-Output:
36 | Page
Web Development using PHP (4341604)
L. References / Suggestions
1) https://www.w3schools.com/php/default.asp
2) https://www.tutorialspoint.com/php/
3) https://tutorialehtml.com/en/php-tutorial-introduction/
4) www.tizag.com/phpT/
5) https://books.goalkicker.com/PHPBook/
6) https://spoken-tutorial.org/tutorial-
search/?search_foss=PHP+and+MySQL&search_language=English
7) https://codecourse.com/watch/php-basics
8) https://onlinecourses.swayam2.ac.in/aic20_sp32/preview
M. Assessment-Rubrics
Faculty
Marks Obtained Date
Signature
Program Implementation Student’s engagement
Correctness and Presentation in practical activities Total
(4) Methodology (3) (3) (10)
R1 R2 R3
37 | Page
Web Development using PHP (4341604)
Date: _________________
Practical No.3: Conditional Statements
a. Write a PHP script to check the given number is odd or even.
b. Write a PHP script to print student’s grade based on marks of 5
subjects.
c. Create a PHP script to show the month of a year using switch
statement.
A. Objective:
Conditional statements are performed on different computations or actions depending
on whether Boolean condition evaluates to true or false. Students will be able to use
various forms of if statements and switch…case statement to check the condition.
38 | Page
Web Development using PHP (4341604)
E. Practical Outcome(PRo)
Students will be able to write a PHP script for different conditional structures.
G. Prerequisite Theory:
Conditional statements are used to perform different actions based on different
conditions. PHP also allows you to write code that perform different actions based on
the results of a logical or comparative test conditions at run time.
There are several statements in PHP that you can use to make decisions:
The if statement
The if...else statement
The if...elseif....else statement
The switch...case statement
The 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.
Syntax:
if(condition) {
Block of code // statements to execute if condition is true
}
39 | Page
Web Development using PHP (4341604)
Syntax:
if(condition) {
Block of code // statements to execute if condition is true
}
else {
Block of code // statements to execute if condition is false
}
Syntax:
if(condition) {
Block of code // statements to execute if condition is true
}
elseif(condition) {
Block of code // statements to execute if condition is true
}
else {
Block of code // statements to execute if all conditions are //false
}
Syntax:
switch(n) {
case value1:
code to be executed if n== value1;
break;
case value2:
code to be executed if n== value2;
break;
......
default:
code to be executed if n != any case;
}
40 | Page
Web Development using PHP (4341604)
H. Resources/Equipment Required
Sr. Instrument/Equipment/
Specification Quantity
No. Components/Trainer kit
Computer (i3-i5 preferable), RAM
1 Hardware: Computer System
minimum 2 GB and onwards
2 Operating System Windows/ Linux/ MAC
As Per
XAMPP server (PHP, Web server, Batch
3 Software
Database) Size
Notepad, Notepad++, Sublime Text or
4 Text Editor
similar
J. Source code:
A) Write a PHP script to check the given number is odd or even.
41 | Page
Web Development using PHP (4341604)
A) Input-Output:
42 | Page
Web Development using PHP (4341604)
B) Input-Output:
C) Create a PHP script to show the month of a year using switch statement.
43 | Page
Web Development using PHP (4341604)
C) Input-Output:
44 | Page
Web Development using PHP (4341604)
L. References / Suggestions
1) https://www.w3schools.com/php/default.asp
2) https://www.tutorialspoint.com/php/
3) https://tutorialehtml.com/en/php-tutorial-introduction/
4) www.tizag.com/phpT/
5) https://books.goalkicker.com/PHPBook/
6) https://spoken-tutorial.org/tutorial-
search/?search_foss=PHP+and+MySQL&search_language=English
7) https://codecourse.com/watch/php-basics
8) https://onlinecourses.swayam2.ac.in/aic20_sp32/preview
M. Assessment-Rubrics
Faculty
Marks Obtained Date
Signature
Program Implementation Student’s engagement
Correctness and Presentation in practical activities Total
(4) Methodology (3) (3) (10)
R1 R2 R3
45 | Page
Web Development using PHP (4341604)
Date: _________________
Practical No.4: Looping Structures
a. Write PHP Script to print Fibonacci series in html tabular format.
b. Write a PHP script to print below number triangle.
A. Objective:
Looping structure is used in programming to repeat a specific block of code until
certain condition is true. Students will be able to use while, do-while and for loop to
replace the repetition of statements. Foreach loop is used for iteration within array.
46 | Page
Web Development using PHP (4341604)
E. Practical Outcome(PRo)
Students will be able to write a PHP script for different looping structures.
G. Prerequisite Theory:
Loops are used to execute the same block of code again and again, as long as a certain
condition is met. The basic idea behind a loop is to automate the repetitive tasks within
a program to save the time and effort. PHP supports four different types of loops.
while
do…while
for
foreach
while loop:
while loop executes a block of code as long as the specified condition is true.
Syntax:
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
Syntax:
do {
Block of code // statements to execute till condition is true.
// Executed once before checking condition.
} while(condition);
47 | Page
Web Development using PHP (4341604)
for loop:
for loop executes a block of code a specified number of times.
Syntax:
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.
Syntax:
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.
Syntax:
while(condition1) {
Block of code // statements to execute till condition1 is true
if(condition2) {
break; // exit while loop is condition2 is true
}
}
continue statement:
continue statement is used to halt the current iteration of a loop and start next
iteration of loop. It does not terminate the loop.
Syntax:
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
}
48 | Page
Web Development using PHP (4341604)
H. Resources/Equipment Required
Sr. Instrument/Equipment/
Specification Quantity
No. Components/Trainer kit
Computer (i3-i5 preferable), RAM
1 Hardware: Computer System
minimum 2 GB and onwards
2 Operating System Windows/ Linux/ MAC
As Per
XAMPP server (PHP, Web server, Batch
3 Software
Database) Size
Notepad, Notepad++, Sublime Text or
4 Text Editor
similar
J. Source code:
A) Write PHP Script to print Fibonacci series in html tabular format.
49 | Page
Web Development using PHP (4341604)
A) Input-Output:
50 | Page
Web Development using PHP (4341604)
B) Input-Output:
51 | Page
Web Development using PHP (4341604)
C) Input-Output:
Options:
1. A and B 3. A and C
2. A, B, and C 4. A, B, C, and D
Options:
1. 12345 3. Error
2. 01234 4. Infinite loop
52 | Page
Web Development using PHP (4341604)
Options:
1. 12345 3. 23456
2. 01234 4. Error
L. References / Suggestions
1) https://www.w3schools.com/php/default.asp
2) https://www.guru99.com/php-tutorials.html
3) https://www.tutorialspoint.com/php/
4) https://tutorialehtml.com/en/php-tutorial-introduction/
5) www.tizag.com/phpT/
6) https://books.goalkicker.com/PHPBook/
7) https://spoken-tutorial.org/tutorial-
search/?search_foss=PHP+and+MySQL&search_language=English
8) https://codecourse.com/watch/php-basics
9) https://onlinecourses.swayam2.ac.in/aic20_sp32/preview
M. Assessment-Rubrics
Faculty
Marks Obtained Date
Signature
Program Implementation Student’s engagement
Correctness and Presentation in practical activities Total
(4) Methodology (3) (3) (10)
R1 R2 R3
53 | Page
Web Development using PHP (4341604)
Date: _________________
Practical No.5: Arrays
a. Write PHP Script for addition and multiplication of two 2x2
matrices.
b. Write a PHP Script to count the number of elements in an array
without using built-in function (use numeric and associative
arrays).
A. Objective:
Array in PHP is a type of data structure that allows us to store multiple elements of
similar data types under a single variable thereby saving us the effort of creating a
different variable for every data. Students will be able to use indexed array, associative
array and multidimensional array.
54 | Page
Web Development using PHP (4341604)
E. Practical Outcome(PRo)
Students will be able to write PHP script using array data structures.
G. Prerequisite Theory:
PHP In PHP, an array is a variable that can hold multiple values of different data types.
Arrays are incredibly useful when you need to work with multiple values of the same
type, or when you need to store related data together.
There are two types of arrays in PHP: indexed arrays and associative arrays.
Indexed Arrays
An indexed array is an array where each value is assigned a numeric index, starting
from zero. Here's an example of how to create an indexed array in PHP:
$dept = array(“IT”,“CE”,“ME”,“EE”);
In this example, the $dept array contains five elements, each with a numeric index.
You can access the values of an indexed array by referring to their index:
echo $dept[0]; // Output: IT
echo $dept[1]; // Output: CE
echo $dept[2]; // Output: ME
Associative Arrays
An associative array is an array where each value is assigned a string key. Here's an
example of how to create an associative array in PHP:
55 | Page
Web Development using PHP (4341604)
$person = array(
"name" => "Sachin",
"age" => 30,
"location" => "Ahmedabad"
);
In this example, the $person array contains three elements, each with a string
key. You can access the values of an associative array by referring to their key:
echo $person["name"]; // Output: Sachin
echo $person["age"]; // Output: 30
echo $person["location"]; // Output: Ahmedabad
Multidimensional Arrays
A multidimensional array is an array where each element can also be an array. Here's
an example of how to create a multidimensional array in PHP:
$students = array(
array("name" => "Sachin", "age" => 30),
array("name" => "Saurav", "age" => 31),
array("name" => "Rahul", "age" => 29)
);
So, arrays are an essential and important part of PHP, and they allow developers to
store and manipulate multiple values in a single variable. Indexed arrays are useful for
working with numeric data, while associative arrays are useful for working with non-
numeric data. Multidimensional arrays are useful for storing complex data structures.
56 | Page
Web Development using PHP (4341604)
H. Resources/Equipment Required
Sr. Instrument/Equipment/
Specification Quantity
No. Components/Trainer kit
Computer (i3-i5 preferable), RAM
1 Hardware: Computer System
minimum 2 GB and onwards
2 Operating System Windows/ Linux/ MAC
As Per
XAMPP server (PHP, Web server, Batch
3 Software
Database) Size
Notepad, Notepad++, Sublime Text or
4 Text Editor
similar
J. Source code:
A) Write PHP Script for addition and multiplication of two 2x2 matrices.
57 | Page
Web Development using PHP (4341604)
A) Input/Output:
58 | Page
Web Development using PHP (4341604)
B) Write a PHP Script to count the number of elements in an array without using built-
in function (use numeric and associative arrays).
59 | Page
Web Development using PHP (4341604)
B) Input/Output:
L. References / Suggestions
1) https://www.w3schools.com/php/default.asp
2) https://www.guru99.com/ php-tutorials.html
3) https://www.tutorialspoint.com/php/
4) https://tutorialehtml.com/en/php-tutorial-introduction/
5) www.tizag.com/phpT/
6) https://books.goalkicker.com/PHPBook/
7) https://spoken-tutorial.org/tutorial-
search/?search_foss=PHP+and+MySQL&search_language=English
8) https://codecourse.com/watch/php-basics
9) https://onlinecourses.swayam2.ac.in/aic20_sp32/preview
60 | Page
Web Development using PHP (4341604)
M. Assessment-Rubrics
Faculty
Marks Obtained Date
Signature
Program Implementation Student’s engagement
Correctness and Presentation in practical activities Total
(4) Methodology (3) (3) (10)
R1 R2 R3
61 | Page
Web Development using PHP (4341604)
Date: _________________
Practical No.6: User defined Functions
a. Write a PHP script to call by reference and call by value.
b. Write a PHP Script for performing function that takes arguments
with default argument and returns value.
c. Write a PHP Script to show the use of variable length argument.
A. Objective:
A function is a block of reusable code that is used to perform a specific task. Functions
enhances the readability of a program, Reduce duplication of the code, reduces the
complexity of a program. User-defined functions help to decompose a large program
into small segments which makes program easy to understand, maintain and debug.
This practical will help student to practice writing PHP scripts using user defined
functions.
62 | Page
Web Development using PHP (4341604)
E. Practical Outcome(PRo)
Students will be able to create user defined functions for different tasks.
G. Prerequisite Theory:
User defined functions
User-defined functions can be used to group code into reusable blocks and make the
code more modular and easier to maintain.
Syntax:
Here,
- function: This is the keyword that tells PHP that you are defining a
function.
- function_name: This is the name of the function.
- (arg1, arg2, ..., argN): These are the arguments that the function accepts.
Arguments are optional, and you can define as many or as few as you
need.
- code to be executed: This is the code that the function executes when it
is called.
63 | Page
Web Development using PHP (4341604)
<?php
function test()
{
echo "Welcome Students.";
}
test();
?>
O/P:
Welcome Students.
sum(10,20);
?>
O/P:
Sum of the two numbers is: 30
O/P:
Returned value from function is: 30
64 | Page
Web Development using PHP (4341604)
O/P:
Sum of the two numbers is: 15
Sum of the two numbers is: 30
func_num_args()
It returns the total number of arguments provided in the function call operation.
65 | Page
Web Development using PHP (4341604)
<?php
function sum()
{
echo func_num_args();
}
sum(10,20,30,40);
?>
O/P: 4
func_get_args()
It creates and returns an array which contains values of arguments provided in the
function call operation.
<?php
function dept()
{
$arr = func_get_args();
Print_r($arr);
}
dept(“IT”, “CE”, “ME”);
?>
O/P: Array ( [0] => “IT” [1] => “CE” [2] => “ME” )
func_get_arg(int position)
It returns the value of specified argument provided in the function call operation. Here
‘position’ is the position index of specified argument.
<?php
function dept()
{
echo func_get_arg(2);
}
dept(“IT”, “CE”, “ME”);
?>
O/P: ME
66 | Page
Web Development using PHP (4341604)
<?php
function incr($val)
{
$val = $val + 1;
echo $val . "<br/>";
}
$a = 1;
incr($a);
echo $a;
?>
O/P: 2
1
<?php
function incr(&$val)
{
$val = $val + 1;
echo $val . "<br/>";
}
$a = 1;
incr($a);
echo $a;
?>
O/P: 2
2
67 | Page
Web Development using PHP (4341604)
H. Resources/Equipment Required
Sr. Instrument/Equipment/
Specification Quantity
No. Components/Trainer kit
Computer (i3-i5 preferable), RAM
1 Hardware: Computer System
minimum 2 GB and onwards
2 Operating System Windows/ Linux/ MAC
As Per
XAMPP server (PHP, Web server, Batch
3 Software
Database) Size
Notepad, Notepad++, Sublime Text or
4 Text Editor
similar
J. Source code:
A) Write a PHP script to call by reference and call by value.
68 | Page
Web Development using PHP (4341604)
A) Input/Output:
69 | Page
Web Development using PHP (4341604)
B) Write a PHP Script for performing function that takes arguments with default
argument and returns value.
B) Input/Output:
70 | Page
Web Development using PHP (4341604)
71 | Page
Web Development using PHP (4341604)
C) Input/Output:
2) Which type of function call is used in line 8 in the following PHP code?
<?php
function calc($price, $tax)
{
$total = $price + $tax;
}
$pricetag = 15;
$taxtag = 3;
calc($pricetag, $taxtag);
?>
a) Call By Value
b) Call By Reference
c) Default Argument Value
d) Type Hinting
72 | Page
Web Development using PHP (4341604)
K. References / Suggestions
1) https://www.w3schools.com/php/default.asp
2) https://www.guru99.com/php-tutorials.html
3) https://www.tutorialspoint.com/php/
4) https://tutorialehtml.com/en/php-tutorial-introduction/
5) www.tizag.com/phpT/
6) https://books.goalkicker.com/PHPBook/
7) https://spoken-tutorial.org/tutorial-
search/?search_foss=PHP+and+MySQL&search_language=English
8) https://codecourse.com/watch/php-basics
9) https://onlinecourses.swayam2.ac.in/aic20_sp32/preview
73 | Page
Web Development using PHP (4341604)
L. Assessment-Rubrics
Faculty
Marks Obtained Date
Signature
Program Implementation Student’s engagement
Correctness and Presentation in practical activities Total
(4) Methodology (3) (3) (10)
R1 R2 R3
74 | Page
Web Development using PHP (4341604)
Date: _________________
Practical No.7: Built-In functions
a. Write PHP script to demonstrate the use of various strings handling
function.
b. Write a PHP script to demonstrate the use of Include() and
require() function.
c. Write PHP script to demonstrate the use of Array functions.
d. Write PHP script to demonstrate the use of fopen(), fread(), fwrite()
and fclose() file functions.
A. Objective:
Built-in functions are predefined functions in PHP that exist in the PHP library. These
PHP inbuilt functions make PHP a very efficient and productive scripting language. The
built in functions of PHP classified into many categories. Students will be able to learn
various built-in functions like string functions, array functions, file functions etc.
75 | Page
Web Development using PHP (4341604)
E. Practical Outcome(PRo)
Students will be able to use different built-in functions of string, file and array.
G. Prerequisite Theory:
PHP String Functions
echo
Use: To output/display one or more strings or variables to the screen.
Note: The echo() function is not actually a function, so you are not
required to use parentheses with it. However, if you want to pass more
than one parameter to echo(), using parentheses will generate an error.
Syntax: echo(strings)
Example: <?php
echo "Hello world";
?>
Output: Hello world
print
Use: To output/display one or more strings or variables to the screen.
Note: The print() function is not actually a function, so you are not
required to use parentheses with it.
Syntax: print(strings)
Example: <?php
print "Hello world";
?>
Output: Hello world
strlen()
Use: To find the length of strings.
Return: The length of a string.
Syntax: strlen(String)
76 | Page
Web Development using PHP (4341604)
Example: <?php
echo strlen("Hello world");
?>
Output: 11
str_word_count()
Use: To count the words of strings.
Return: The number of words in the string.
Syntax: str_word_count(String)
Example: <?php
echo str_word_count("Hello world");
?>
Output: 2
strrev()
Use: To reverse the given strings.
Return: The reversed string.
Syntax: strrev(String)
Example: <?php
echo strrev("Hello world");
?>
Output: dlrow olleH
str_replace()
Use: To replace some of the characters in a string with some other.
Return: The string with replacements.
Syntax: str_replace(search, replace, string)
Here;
Search: Required. This will be the string to search for replacing.
Replace: Required. This will replace the searched string.
String: Required. This will the string which we have to search and
replace.
Example: <?php
echo str_replace("Hello","Hi","Hello world");
?>
Output: Hi world
strstr()
Use: To display the part of the string from the first search occurrence.
Note: This function is case-sensitive. For a case-insensitive search, use
stristr() function.
Return: The rest of the string.
Syntax: strstr(string,search,before_search)
77 | Page
Web Development using PHP (4341604)
Here;
String: Required. This will be the string to search.
Search: Required. Specifies the string to search for. If this is a number, it
will search for the character matching the ASCII value of the number.
Before_search: Optional. A boolean value whose default is "false". If set to
"true", it returns the part of the string before the first occurrence of the
search parameter.
Example: <?php
echo strstr("Hello world","world") . "<br/>";
echo strstr("Hello world","world",true);
?>
Output: world
Hello
substr()
Use: To extract the string.
Return: The a part of the string.
Syntax: substr(string,start,length)
Here;
String: Required. This will be the string to return a part of.
Start: Required. Specifies where to start in the string
- A positive number - Start at a specified position in the string
- A negative number - Start at a specified position from the end of the
string
- 0 - Start at the first character in string
Length: Optional. Specifies the length of the returned string.
- A positive number - The length to be returned from the start
- Negative number - The length to be returned from the end
- If the length parameter is 0, NULL, or FALSE - returns empty string
Example: <?php
echo substr("Hello world",7) ."<br/>";
echo substr("Hello world",-7) ."<br/>";
echo substr("Hello world",7,2) ."<br/>";
echo substr("Hello world",1,-7) ."<br/>";
echo substr("Hello world",-7,-1);
?>
Output: orld
o world
or
ell
o worl
strtolower()
78 | Page
Web Development using PHP (4341604)
strtoupper()
Use: To extract the string.
Return: String in upper case.
Syntax: strtoupper(string)
Example: <?php
echo strtoupper("Hello World");
?>
Output: HELLO WORLD
ucwords()
Use: To convert the first character of each word in a string to uppercase.
Return: String with first character of each word in uppercase.
Syntax: ucwords(string, delimiters)
Here;
String: Required. This will be the string to convert.
Delimiters: Optional. Word separator character.
Example: <?php
echo ucwords("hello world") ."<br/>";
echo ucwords("hello-world", "-");
?>
Output: Hello World
Hello-World
strpos()
Use: To find the position of the first occurrence of a string inside another
string.
Note: The strpos() function is case-sensitive.
Return: The position of the first occurrence of a string inside another string, or
FALSE if the string is not found. (String positions start at 0).
Syntax: strpos(string, find, start)
Here;
String: Required. This will be the string to search.
Find: Required. This will be the string to find.
Start: Optional. Specifies where to begin the search. (If start is a negative
number, it counts from the end of the string.)
79 | Page
Web Development using PHP (4341604)
Example: <?php
echo ucwords("hello world") ."<br/>";
echo ucwords("hello-world", "-");
?>
Output: Hello World
Hello-World
ltrim()
Use: To remove whitespace and other predefined characters from left side of
a string.
Return: String after removing of space/characters.
Syntax: ltrim(string, charlist)
Here;
String: Required. This will be the string to check.
Charlist: Optional. This will be characters to remove from the string.
Example: <?php
echo ltrim("Hello world","Held");
?>
Output: o world
rtrim()
Use: To remove whitespace and other predefined characters from right side
of a string.
Return: String after removing of space/characters.
Syntax: rtrim(string, charlist)
Here;
String: Required. This will be the string to check.
Charlist: Optional. This will be characters to remove from the string.
Example: <?php
echo rtrim("Hello world","Held");
?>
Output: Hello wor
trim()
Use: To remove whitespace and other predefined characters from both sides
of a string.
Return: String after removing of space/characters.
Syntax: trim(string, charlist)
Here;
String: Required. This will be the string to check.
Charlist: Optional. This will be characters to remove from the string.
Example: <?php
80 | Page
Web Development using PHP (4341604)
implode()
Use: To convert the array to strings. It takes an array and converts those
array to strings by using any separator.
Return: String from elements of an array.
Syntax: implode(separator, array)
Here;
Separator: Optional. This will be the separator to put between the array
elements. Default is "" (an empty string).
Array: Required. This will be an array.
Example: <?php
$arr = array('Hello','World');
echo implode(" ",$arr) ."<br/>";
echo implode("-",$arr);
?>
Output: Hello World
Hello-World
explode()
Use: To break a string into an array.
Return: An array of strings.
Syntax: explode(separator, string, limit)
Here;
Separator: Required. This will be the for where to break the string.
String: Required. This will be string to split.
Limit: This will be the number of array elements to return.
limit can be, >0 - Returns an array with a maximum of limit element(s)
<0 - Returns an array except for the last -limit element(s)
0 - Returns an array with one element
Example: <?php
$str = "Welcome to the PHP world.";
print_r (explode(" ",$str));
echo "<br/>";
print_r (explode(" ",$str,0));
echo "<br/>";
print_r (explode(" ",$str,3));
echo "<br/>";
print_r (explode(" ",$str,-1));
?>
81 | Page
Web Development using PHP (4341604)
Output: Array ( [0] => Welcome [1] => to [2] => the [3] => PHP [4] => world. )
Array ( [0] => Welcome to the PHP world. )
Array ( [0] => Welcome [1] => to [2] => the PHP world. )
Array ( [0] => Welcome [1] => to [2] => the [3] => PHP )
Syntax:
include 'filename';
or
require 'filename';
Let’s assume that we have a file named ‘two.php’ and we want to include it in our page
named ‘one.php’.
two.php:
<?php
echo "<p>Thank you for visiting our website.</p>";
?>
one.php:
<html>
<body>
</body>
</html>
Output:
82 | Page
Web Development using PHP (4341604)
Same way you can use require() function and test it.
Here;
Search: Required. This will be the what to search for.
Array: Required. This will be array to search.
Type: Optional. If this is set to TRUE, it searches for the search-string and
specific type in the array.
Example: <?php
$dept = array("IT", "CE", "ME", 16);
if (in_array("16", $dept, TRUE)) {
echo "Match found<br>";
}
else {
echo "Match not found<br>";
}
if (in_array("IT",$dept)) {
echo "Match found<br>";
}
else {
echo "Match not found<br>";
}
?>
Output: Match not found
Match found
in_array()
Use: To merge one or more arrays into one array.
Return: Merged array.
Syntax: array_merge(array1, array2, …., arrayN)
Example: <?php
$a1=array("IT","CE");
$a2=array("ME","EE");
print_r(array_merge($a1,$a2));
?>
Output: Array ( [0] => IT [1] => CE [2] => ME [3] => EE )
array_push()
Use: To insert one or more elements to the end of an array.
83 | Page
Web Development using PHP (4341604)
array_pop()
Use: To delete the last element of an array.
Return: The new array after deletion.
Syntax: array_pop(array)
Example: <?php
$a=array("IT","CE","ME");
array_pop($a);
print_r($a);
?>
Output: Array ( [0] => IT [1] => CE )
array_replace()
Use: To replace the values of the first array with the values from following
arrays.
Return: The replaced array, or NULL if an error occurs.
Syntax: array_replace(array1, array2, …)
Example: <?php
$a1=array("IT","CE");
$a1=array("EE","ME");
print_r(array_replace($a1,$a2));
?>
Output: Array ( [0] => EE [1] => ME )
array_reverse()
Use: To reverse the specified arrays.
Return: The reversed array.
Syntax: array_reverse(array)
Example: <?php
$a=array("IT","CE");
print_r(array_reverse($a));
?>
Output: Array ( [0] => CE [1] => IT )
array_search()
Use: To search an array for a value.
Return: The key of a value if it is found in the array, and FALSE otherwise.
84 | Page
Web Development using PHP (4341604)
Here;
Value: Required. This will be the value to search for.
Array: Required. This will be array to search.
Strict: Optional. If this parameter is set to TRUE, then this function will
search for identical elements in the array. Default is FALSE.
Example: <?php
$a=array("a"=>"IT","b"=>"CE");
echo array_search("IT",$a);
?>
Output: a
count()
Use: To count of elements in an array.
Return: The number of elements in an array.
Syntax: count(array, mode)
Here;
Array: Required. This will be an array.
Mode: Optional. It will be 0 or 1. Default is 0 and it does not count all
elements of multidimensional arrays. If it is 1 then it counts the array
recursively (counts all the elements of multidimensional arrays).
Example: <?php
$a=array("IT","CE");
echo (count($a));
?>
Output: 2
85 | Page
Web Development using PHP (4341604)
list()
Use: To assign values to a list of variables in one operation.
Return: The assigned array.
Syntax: list(var1, var2, var3, …)
Example: <?php
$arr = array("IT","CE");
list($a, $b) = $arr;
echo "Our departments are $a and $b.";
?>
Output: Our departments are IT and CE.
sort()
Use: To sort an indexed array in ascending order.
Return: TRUE on success. FALSE on failure
Syntax: sort(array)
Example: <?php
$arr=array("IT","CE","ME","EE");
sort($arr);
$alen=count($arr);
for($x=0;$x<$alen;$x++)
{
echo $arr[$x] . "<br/>”;
}
?>
Output: CE
EE
IT
ME
86 | Page
Web Development using PHP (4341604)
Here;
Array: Required. This will be file or URL to open.
Mode: Required. This will be the type of access you require to the file.
Modes can be r, r+, w, w+, a, a+, x, x+, c, c+.
fclose()
Use: To close a file.
Return: TRUE on success, FALSE on failure.
Syntax: fclose(filepointer)
fread()
Use: To read from an open file.
Return: A file pointer resource on success, FALSE and an error on failure.
Syntax: fread(file, length)
Here;
File: Required. This will be file to read from.
Length: Required. This will be the maximum number of bytes to read.
Example: <?php
$file = fopen("test.txt","r");
fread($file,"5");
fclose($file);
?>
fwrite()
Use: To write to an open file.
Return: The number of bytes written, FALSE on failure.
Syntax: fwrite(file, string, length)
Here;
File: Required. This will be file to write to.
string: Required. This will be string to write in file.
Length: Optional. This will be maximum number of bytes to write.
Example: <?php
$file = fopen("test.txt","w");
fwrite($file,"Hello World")
fclose($file);
?>
Output: 11
87 | Page
Web Development using PHP (4341604)
88 | Page
Web Development using PHP (4341604)
H. Resources/Equipment Required
Sr. Instrument/Equipment/
Specification Quantity
No. Components/Trainer kit
Computer (i3-i5 preferable), RAM
1 Hardware: Computer System
minimum 2 GB and onwards
2 Operating System Windows/ Linux/ MAC
XAMPP server (PHP, Web server, As Per
3 Software Batch Size
Database)
Notepad, Notepad++, Sublime Text or
4 Text Editor
similar
J. Source code:
A) Write PHP script to demonstrate the use of various strings handling function.
89 | Page
Web Development using PHP (4341604)
B) Input/Output:
90 | Page
Web Development using PHP (4341604)
C) Write a PHP script to demonstrate the use of Include() and require() function.
D) Input/Output:
91 | Page
Web Development using PHP (4341604)
F) Input/Output:
92 | Page
Web Development using PHP (4341604)
G) Write PHP script to demonstrate the use of fopen(), fread(), fwrite() and fclose() file
functions.
H) Input/Output:
93 | Page
Web Development using PHP (4341604)
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
2. __________ function is used for replacing the whole string with an alternate string.
3. A function that capitalizes the first letter of each word in a string, is a _________.
5. ___________ function is used to get the value of the previous element in an array.
<?php
$a=array("a"=>"IT","b"=>array("CE"));
echo (count($a,1));
?>
L. References / Suggestions
1) https://www.w3schools.com/php/default.asp
2) https://www.guru99.com/php-tutorials.html
3) https://www.tutorialspoint.com/php/
4) https://tutorialehtml.com/en/php-tutorial-introduction/
5) www.tizag.com/phpT/
6) https://books.goalkicker.com/PHPBook/
7) https://spoken-tutorial.org/tutorial-
search/?search_foss=PHP+and+MySQL&search_language=English
8) https://codecourse.com/watch/php-basics
9) https://onlinecourses.swayam2.ac.in/aic20_sp32/preview
94 | Page
Web Development using PHP (4341604)
M. Assessment-Rubrics
Faculty
Marks Obtained Date
Signature
Program Implementation Student’s engagement
Correctness and Presentation in practical activities Total
(4) Methodology (3) (3) (10)
R1 R2 R3
95 | Page
Web Development using PHP (4341604)
Date: _________________
Practical No.8: Form Handling
a. Create student registration form using text box, check box, radio
button, select, submit button. And display user inserted value in
new PHP page using GET or POST Method.
b. Write a PHP script to explain the concept of $_REQUEST.
A. Objective:
Forms are important component of the web application that allows to collect
information from the users. Forms are used for various tasks such as login,
registration, contact us, and application specific information collection. This practical
will help students to design a form and to collect data entered in form input by users
using PHP.
96 | Page
Web Development using PHP (4341604)
CO3: Design and develop a Web site using form controls for presenting web-based
content.
E. Practical Outcome(PRo)
Students will be able to use a form and to collect data entered in form input by users
using PHP.
G. Prerequisite Theory:
From Tag
It is used to design form which contains various input controls that allows user to
input information.
Input Element
It allows you to place various controls in the form to accept input from user.
97 | Page
Web Development using PHP (4341604)
Textbox Syntax:-
<input type=“text” name=“Text Name” value=“Default value”>
Hidden field Syntax:-
<input type=“hidden” name=“field Name” value=“Default value”>
Password Syntax:-
<input type=“password” name=“psw Name” value=“Default value”>
TextArea Syntax:-
<textarea name =“Text name” rows=“rowsize” cols=“columnsize”>
checkbox Syntax:-
<input type=“checkbox” name=“checkBoxName” value=“Default value”
checked> TextToDisplay </input>
radio Button Syntax:-
<input type=“radio” name=“radioname” value=“Default value”
checked> TextToDisplay </input>
List box Syntax:-
<select name=“List name” size=“value”>
<option>Value1</option>
<option>Value1</option>
</select>
Submit Button Syntax:-
<input type=“submit” >
Image Button Syntax:-
<input type=“image” SRC=“URL”>
Syntax:
$VariableName = $_GET[“fieldname”];
98 | Page
Web Development using PHP (4341604)
Disadvantages:-
Information trying to pass to destination file is visible in URL so it is Insecure.
Transfer limited amount of Information.
GET can't be used to send binary data, like images or word documents, to the
server.
The GET method is restricted to send up to 1024 characters only.
Submit form using POST method:
The POST method transfers information via HTTP headers.
It will transfer Information between pages through FORM body.
The POST method does not have any restriction on data size to be sent.
The POST method can be used to send ASCII as well as binary data.
The data sent by POST method goes through HTTP header so security depends on
HTTP protocol. By using Secure HTTP you can make sure that your information is
secure.
The PHP provides $_POST associative array to access all the sent information using
POST method
Information is transferred through FORM body, not visible to everyone. Hence
secure method.
It allows you to transfer larger amount of data.
Syntax:
$VariableName = $_POST[“fieldname”];
Syntax:
$VariableName = $_REQUEST[“fieldname”];
99 | Page
Web Development using PHP (4341604)
H. Resources/Equipment Required
Sr. Instrument/Equipment/
Specification Quantity
No. Components/Trainer kit
Computer (i3-i5 preferable), RAM
1 Hardware: Computer System
minimum 2 GB and onwards
2 Operating System Windows/ Linux/ MAC
XAMPP server (PHP, Web server, As Per
3 Software Batch Size
Database)
Notepad, Notepad++, Sublime Text or
4 Text Editor
similar
NA
J. Source code:
A) Create student registration form using text box, check box, radio button, select,
submit button. And display user inserted value in new PHP page using GET or POST
Method.
100 | Page
Web Development using PHP (4341604)
A) Input/Output:
101 | Page
Web Development using PHP (4341604)
102 | Page
Web Development using PHP (4341604)
B) Input/Output:
1. ____________ variable is used to collect form data sent with both the GET and POST
methods.
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
________________________________________________________________________________________________
5. For password input in form, you should use ____________ attribute and ___________ value
of <input> tag.
103 | Page
Web Development using PHP (4341604)
L. References / Suggestions
1) https://www.w3schools.com/php/default.asp
2) https://www.guru99.com/php-tutorials.html
3) https://www.tutorialspoint.com/php/
4) https://tutorialehtml.com/en/php-tutorial-introduction/
5) www.tizag.com/phpT/
6) https://books.goalkicker.com/PHPBook/
7) https://spoken-tutorial.org/tutorial-
search/?search_foss=PHP+and+MySQL&search_language=English
8) https://codecourse.com/watch/php-basics
9) https://onlinecourses.swayam2.ac.in/aic20_sp32/preview
M. Assessment-Rubrics
Faculty
Marks Obtained Date
Signature
Program Implementation Student’s engagement
Correctness and Presentation in practical activities Total
(4) Methodology (3) (3) (10)
R1 R2 R3
104 | Page
Web Development using PHP (4341604)
Date: _________________
Practical No.9: Email and Validation
a. Write PHP script to validate form including name, email using
appropriate functions.
b. Write PHP script for sending plain text email, HTML email and
attachments with email.
A. Objective:
Forms validation and sending email are important if we talk about input of form. By
practical students will be able to learn from validation and sending email details from
form.
105 | Page
Web Development using PHP (4341604)
E. Practical Outcome(PRo)
Students will be able to perform validation and to email data entered in form by users
using PHP.
G. Prerequisite Theory:
Form Validation
Form validation in PHP is the process of verifying that the data submitted by a user
through a web form is valid, complete, and meets the required format. An HTML form
contains various input fields such as text box, checkbox, radio buttons, submit button,
and checklist, etc. These input fields need to be validated, which ensures that the user
has entered information in all the required fields and also validates that the
information provided by the user is valid and correct.
PHP validates the data at the server-side, which is submitted by HTML form. You need
to validate a few things:
Empty String
The code below checks that the field is not empty. If the user leaves the required field
empty, it will show an error message. Put these lines of code to validate the required
field.
if (empty ($_POST["name"])) {
$errMsg = "Error! Kindly Enter the Name.";
echo $errMsg;
} else {
$name = $_POST["name"];
}
Validate String
The code below checks that the field will contain only alphabets and whitespace, for
example - name. If the name field does not receive valid input from the user, then it
will show an error message:
106 | Page
Web Development using PHP (4341604)
Validate Numbers
The below code validates that the field will only contain a numeric value. For example -
Mobile no. If the Mobile no field does not receive numeric data from the user, the code
will display an error message:
Validate Email
A valid email must contain @ and . symbols. PHP provides various methods to validate
the email address. Here, we will use regular expressions to validate the email address.
The below code validates the email address provided by the user through HTML form.
If the field does not contain a valid email address, then the code will display an error
message:
107 | Page
Web Development using PHP (4341604)
Validate URL
The below code validates the URL of website provided by the user via HTML form. If
the field does not contain a valid URL, the code will display an error message, i.e., "URL
is not valid".
$websiteURL = $_POST["website"];
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-
a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "URL is not valid";
echo $websiteErr;
} else {
echo "Website URL is: " .$websiteURL;
}
Input length
The input length validation restricts the user to provide the value between the
specified range, for Example - Mobile Number. A valid mobile number must have 10
digits. The given code will help you to apply the length validation on user input:
Syntax:
mail(to, subject, message, headers, parameters);
Here,
To: Required. Specifies receiver or receivers of the mail.
Subject: Required. Specifies the subject of the email.
Message: Required. Defines the message to be sent.
Headers: Optional. Specifies additional headers, like From, Cc, and Bcc.
Parameters: Optional. Specifies an additional parameter to the sendmail program
108 | Page
Web Development using PHP (4341604)
<?php
$to = "receiver@example.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: sender@example.com" . "\r\n" .
"CC: somebodyelse@example.com";
mail($to,$subject,$txt,$headers);
?>
<?php
$to = "receiver@example.com";
$subject = "This is subject";
$message = "<h1>This is HTML Email</h1> \r\n";
$message .= "<h1>This is HTML Heading.</h1>";
109 | Page
Web Development using PHP (4341604)
H. Resources/Equipment Required
Sr. Instrument/Equipment/
Specification Quantity
No. Components/Trainer kit
Computer (i3-i5 preferable), RAM
1 Hardware: Computer System
minimum 2 GB and onwards
2 Operating System Windows/ Linux/ MAC
XAMPP server (PHP, Web server, As Per
3 Software Batch Size
Database)
Notepad, Notepad++, Sublime Text or
4 Text Editor
similar
NA
J. Source code:
A) Write PHP script to validate form including name, email using appropriate functions.
110 | Page
Web Development using PHP (4341604)
B) Input/Output:
111 | Page
Web Development using PHP (4341604)
C) Write PHP script for sending plain text email, HTML email and attachments with
email.
112 | Page
Web Development using PHP (4341604)
D) Input/Output:
113 | Page
Web Development using PHP (4341604)
L. References / Suggestions
1) https://www.w3schools.com/php/default.asp
2) https://www.guru99.com/php-tutorials.html
3) https://www.tutorialspoint.com/php/
4) https://tutorialehtml.com/en/php-tutorial-introduction/
5) www.tizag.com/phpT/
6) https://books.goalkicker.com/PHPBook/
7) https://spoken-tutorial.org/tutorial-
search/?search_foss=PHP+and+MySQL&search_language=English
8) https://codecourse.com/watch/php-basics
9) https://onlinecourses.swayam2.ac.in/aic20_sp32/preview
M. Assessment-Rubrics
Faculty
Marks Obtained Date
Signature
Program Implementation Student’s engagement
Correctness and Presentation in practical activities Total
(4) Methodology (3) (3) (10)
R1 R2 R3
114 | Page
Web Development using PHP (4341604)
Date: _________________
Practical No.10: Session and Cookies
a. Write a PHP script to demonstrate creating, deleting, updating,
retrieving and passing data with Cookie.
b. Write PHP script to demonstrate passing information using
Session.
A. Objective:
A cookie is often used to identify a user. It is a small file that the server stores on the
user's computer. Each time the same computer requests a page with a same browser, it
will send the cookie too A session is a way to store information which is to be used
across multiple pages. In this practical student will learn how to create cookie, modify
it and delete it. Also, they will learn how to start a session, fetch session variables and
destroy a session.
115 | Page
Web Development using PHP (4341604)
CO4: Debug the Programs by applying state management concepts and error handling
techniques of PHP.
E. Practical Outcome(PRo)
Students will be able to create, store, fetch, delete cookies and session.
G. Prerequisite Theory:
Cookies:
Cookies are small files that are stored on the client's computer by the web server.
Cookies are used to store small amounts of data that can be accessed by the web server
when the client requests a page from the website. Cookies are commonly used to store
user preferences, shopping cart items, login credentials, and other user-specific
information.
To set a cookie in PHP, you can use the setcookie() function.
Syntax:
setcookie(Name, value, Expire Time)
To retrieve a cookie value in PHP, you can use the $_COOKIE superglobal array. The
$_COOKIE array contains all of the cookies that have been set by the web server.
Syntax:
$variable_name = $_COOKIE['cookie_name'];
To delete a cookie create a cookie using setcookie() function without specifying any
Expire Time or give past time as an expiry time.
Syntax:
setcookie (‘Cookie_Name’, "") /OR/ setcookie ("name","",time()-60)
116 | Page
Web Development using PHP (4341604)
Example:
<?php
setcookie("user", "IT");
?>
<html>
<body>
<?php
if(!isset($_COOKIE["user"])) {
echo "Sorry, cookie is not found!";
} else {
echo "<br/>Cookie Value: " . $_COOKIE["user"];
}
?>
</body>
</html>
Session
Session is a way to store data on the server side that is associated with a specific user
or client. Sessions are used to maintain stateful information across multiple requests
from the same client. To start a session in PHP, you need to call the session_start()
function at the beginning of your script. This function creates a new session or
resumes an existing session if one exists.
Syntax:
session_start();
Once the session has been started, you can store data in the session by setting values in
the $_SESSION superglobal array.
Syntax:
$_SESSION['session_name'] = 'value';
To retrieve data from the session, you can simply access the $_SESSION superglobal
array.
Syntax:
$variable_name = $_SESSION['session_name'];
You can destroy a session and all of its associated data by calling the session_destroy()
function. This function will remove all session.
To unset specific session variables without destroying the entire session, you can use
the unset() function.
117 | Page
Web Development using PHP (4341604)
Syntax:
session_destroy();
unset($_SESSION['session_name']);
Example: session1.php
<?php
session_start();
?>
<html>
<body>
<?php
$_SESSION["user"] = "IT";
echo "Session information are set successfully.<br/>";
?>
<a href="session2.php">Visit session2.php</a>
</body>
</html>
session2.php
<?php
session_start();
?>
<html>
<body>
<?php
echo "User is: ".$_SESSION["user"];
?>
</body>
</html>
H. Resources/Equipment Required
Sr. Instrument/Equipment/
Specification Quantity
No. Components/Trainer kit
Computer (i3-i5 preferable), RAM
1 Hardware: Computer System
minimum 2 GB and onwards
2 Operating System Windows/ Linux/ MAC
XAMPP server (PHP, Web server, As Per
3 Software Batch Size
Database)
Notepad, Notepad++, Sublime Text or
4 Text Editor
similar
118 | Page
Web Development using PHP (4341604)
NA
J. Source code:
119 | Page
Web Development using PHP (4341604)
A) Input/Output:
120 | Page
Web Development using PHP (4341604)
121 | Page
Web Development using PHP (4341604)
C) Input/Output:
122 | Page
Web Development using PHP (4341604)
L. References / Suggestions
1) https://www.w3schools.com/php/default.asp
2) https://www.guru99.com/php-tutorials.html
3) https://www.tutorialspoint.com/php/
4) https://tutorialehtml.com/en/php-tutorial-introduction/
5) www.tizag.com/phpT/
6) https://books.goalkicker.com/PHPBook/
7) https://spoken-tutorial.org/tutorial-
search/?search_foss=PHP+and+MySQL&search_language=English
8) https://codecourse.com/watch/php-basics
9) https://onlinecourses.swayam2.ac.in/aic20_sp32/preview
M. Assessment-Rubrics
Faculty
Marks Obtained Date
Signature
Program Implementation Student’s engagement
Correctness and Presentation in practical activities Total
(4) Methodology (3) (3) (10)
R1 R2 R3
123 | Page
Web Development using PHP (4341604)
Date: _________________
Practical No.11: Error Handling
a. Write a PHP script to demonstrate Error Handling.
b. Write a PHP script to demonstrate Use of Try and Catch Error
Handling.
A. Objective:
When creating scripts and web applications, error handling is an important part. If
your code lacks error checking code, your program may look very unprofessional and
you may be open to security risks. Students will be able to learn handling of error in
PHP.
CO4: Debug the Programs by applying state management concepts and error handling
techniques of PHP.
124 | Page
Web Development using PHP (4341604)
E. Practical Outcome(PRo)
G. Prerequisite Theory:
<?php
if(file_exists("myfile.txt"))
{
$file = fopen("myfile.txt", "r");
}
else
{
die("Error: The file does not exist.");
}?>
125 | Page
Web Development using PHP (4341604)
two parameters (error level and error message) but can accept up to five parameters
(optionally: file, line-number, and the error context) –
Syntax:
Custom_Function_Name (Type, Message, Filename, Line Number, Context)
Syntax:
try
{ //code to be executed
throw new Exception(“Error Message”);
}
Catch (ExceptionType1 $ob1)
{// Exception Handling code for Exception Type 1 }
H. Resources/Equipment Required
Sr. Instrument/Equipment/
Specification Quantity
No. Components/Trainer kit
Computer (i3-i5 preferable), RAM
1 Hardware: Computer System
minimum 2 GB and onwards
2 Operating System Windows/ Linux/ MAC
XAMPP server (PHP, Web server, As Per
3 Software Batch Size
Database)
Notepad, Notepad++, Sublime Text or
4 Text Editor
similar
126 | Page
Web Development using PHP (4341604)
NA
J. Source code:
127 | Page
Web Development using PHP (4341604)
B) Input/Output:
C) Write a PHP script to demonstrate Use of Try and Catch Error Handling
128 | Page
Web Development using PHP (4341604)
D) Input/Output:
L. References / Suggestions
1) https://www.w3schools.com/php/default.asp
2) https://www.guru99.com/php-tutorials.html
3) https://www.tutorialspoint.com/php/
4) https://tutorialehtml.com/en/php-tutorial-introduction/
5) www.tizag.com/phpT/
6) https://books.goalkicker.com/PHPBook/
7) https://spoken-tutorial.org/tutorial-
search/?search_foss=PHP+and+MySQL&search_language=English
8) https://codecourse.com/watch/php-basics
9) https://onlinecourses.swayam2.ac.in/aic20_sp32/preview
M. Assessment-Rubrics
Faculty
Marks Obtained Date
Signature
Program Implementation Student’s engagement
Correctness and Presentation in practical activities Total
(4) Methodology (3) (3) (10)
R1 R2 R3
129 | Page
Web Development using PHP (4341604)
Date: _________________
Practical No.12: Error Handling
a. Write a Write a PHP script to connect with database server from
your webpage.
b. Create a database with student table and write a PHP script to
insert a record in student table.
c. Write a program to read student records from student table and
display all these information in table format on output screen.
d. Write a PHP script to delete and update a specific record from
table.
e. Write a PHP script simple login system that allows user to add a
new username if user doesn’t exist in the database, also create a
forgot password link, to redirect user to set up his new password
on authentication.
A. Objective:
When we are talking about creating dynamic website, database plays an very
important role. Students will be able to understand database in phpMyAdmin and can
use various database operations.
130 | Page
Web Development using PHP (4341604)
CO5: Create dynamic web pages using PHP and MySQL database.
E. Practical Outcome(PRo)
Students will be able to use database and perform various database operations using
SQL statements.
G. Prerequisite Theory:
Database
Create Database from PhpMyAdmin
131 | Page
Web Development using PHP (4341604)
132 | Page
Web Development using PHP (4341604)
mysqli_connect()
mysqli_connect() is a function used to establish a connection to a MySQL database.
133 | Page
Web Development using PHP (4341604)
Syntax:
mysqli_connect(servername, username, password, dbname);
Here,
servername: specifies the name of the MySQL server host.
username: specifies the username to connect to the MySQL server.
password: specifies the password to connect to the MySQL server.
dbname: specifies the name of the database to connect to.
mysqli_query()
mysqli_query() is a function used in PHP to execute a MySQL query on a database.
Syntax:
mysqli_query(connection, query);
Here,
connection: specifies the MySQL connection to use for the query.
query: specifies the SQL query to be executed.
mysqli_fetch_row()
mysqli_fetch_row() function fetches one row from a result-set and returns it as an
enumerated array. It returns an array of strings that corresponds to the fetched row.
Syntax:
mysqli_fetch_row(result);
Here,
Result: Required. Specifies a result set identifier returned by mysqli_query().
mysqli_fetch_array()
mysqli_fetch_array() function fetches a result row as an associative array, a numeric
array, or both. It returns an array of strings that corresponds to the fetched row.
Syntax:
mysqli_fetch_array(result,resulttype);
Here,
Result: Required. Specifies a result set identifier returned by mysqli_query().
Resulttype: Optional. Specifies what type of array should be produced. Can be one
of the following values: MYSQLI_ASSOC, MYSQLI_NUM, MYSQLI_BOTH (default)
134 | Page
Web Development using PHP (4341604)
mysqli_error()
mysqli_error() function returns the last error description for the most recent function
call, if any.
Syntax:
mysqli_error(connection)
Here,
Connection: Required. Specifies the MySQL connection to use
mysqli_close()
mysqli_close() function closes a previously opened database connection.
Syntax:
mysqli_close(connection)
Here,
Connection: Required. Specifies the MySQL connection to use
Example: (Insert)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password,
$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
135 | Page
Web Development using PHP (4341604)
H. Resources/Equipment Required
Sr. Instrument/Equipment/
Specification Quantity
No. Components/Trainer kit
Computer (i3-i5 preferable), RAM
1 Hardware: Computer System
minimum 2 GB and onwards
2 Operating System Windows/ Linux/ MAC
XAMPP server (PHP, Web server, As Per
3 Software Batch Size
Database)
Notepad, Notepad++, Sublime Text or
4 Text Editor
similar
NA
J. Source code:
A) Write a PHP script to connect with database server from your webpage.
136 | Page
Web Development using PHP (4341604)
A) Input/Output:
B) Create a database with student table and write a PHP script to insert a record in
student table.
137 | Page
Web Development using PHP (4341604)
C) Input/Output:
138 | Page
Web Development using PHP (4341604)
D) Write a program to read student records from student table and display all these
information in table format on output screen.
139 | Page
Web Development using PHP (4341604)
E) Input/Output:
140 | Page
Web Development using PHP (4341604)
F) Write a PHP script to delete and update a specific record from table.
141 | Page
Web Development using PHP (4341604)
G) Input/Output:
142 | Page
Web Development using PHP (4341604)
H) Write a PHP script simple login system that allows user to add a new username if user
doesn’t exist in the database, also create a forgot password link, to redirect user to set
up his new password on authentication.
143 | Page
Web Development using PHP (4341604)
144 | Page
Web Development using PHP (4341604)
I) Input/Output:
145 | Page
Web Development using PHP (4341604)
L. References / Suggestions
1) https://www.w3schools.com/php/default.asp
2) https://www.guru99.com/php-tutorials.html
3) https://www.tutorialspoint.com/php/
4) https://tutorialehtml.com/en/php-tutorial-introduction/
5) www.tizag.com/phpT/
6) https://books.goalkicker.com/PHPBook/
7) https://spoken-tutorial.org/tutorial-
search/?search_foss=PHP+and+MySQL&search_language=English
8) https://codecourse.com/watch/php-basics
9) https://onlinecourses.swayam2.ac.in/aic20_sp32/preview
M. Assessment-Rubrics
Faculty
Marks Obtained Date
Signature
Program Implementation Student’s engagement
Correctness and Presentation in practical activities Total
(4) Methodology (3) (3) (10)
R1 R2 R3
146 | Page