WBP Lab Manual
WBP Lab Manual
Institute Vision
Vision
To achieve excellence in imparting technical education so as to meet the professional and societal
needs.
Institute Mission
Mission
• Developing technical skills by imparting knowledge and providing hands on experience.
• Creating an environment that nurtures ethics, leadership and team building.
• Providing industrial exposure for minimizing the gap between academics & industry.
Mission
M1: Developing technical skills by explaining the rationale behind learning.
M2: Developing interpersonal skills to serve the society in the best possible manner.
M3: Creating awareness about the ever-changing professional practices to build industrial adaptability
Provide socially responsible, environment friendly solutions to Computer engineering related broad-
based problems adapting professional ethics.
Solve broad-based problems individually and as a team member communicating effectively in the
world of work.
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Name of Student
Roll No.
Date:
Experiment No: 01
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Resources required:
Hardware Software
Computer System Any database tools such as XAMPP
Practical Significance:
PHP is an acronym for "PHP: Hypertext Preprocessor". PHP is a widely-used, open source
scripting language. PHP scripts are executed on the server.
Theoretical Background:
• A PHP script starts with the <?php and ends with the ?> tag.
• The PHP delimiter <?php and ?> in the following example simply tells the PHP engine to treat
the enclosed code block as PHP code, rather than simple HTML.
• On servers with shorthand support enabled you can start a scripting block with <? and end with
?>.
Syntax:
<?php
echo ‘Hello world’;
?>
<html>
<body>
<?php echo "Welcome to PHP";
?>
</body>
</html>
Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to
distinguish one set of instructions from another.
There are two basic statements to output text with PHP: echo and print. In the example above
we have used the echo statement to output the text “Welcome to PHP ".
The XAMPP (Cross-platform, Apache, MariaDB (Mysql), PHP and Perl) suite of Web
development tools, created by Apache Friends, makes it easy to run PHP (Personal Home
Pages) scripts locally on your computer. Manual installation of a Web server and PHP requires
in-depth configuration knowledge, but installing XAMPP on Windows only requires running
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
an installer package. This package installs not only a Web server and PHP but also MySQL,
FileZilla, Mercury, Perl and Tomcat.
Install XAMPP:
• Go to the Apache Friends website and download XAMPP for Windows. For the easiest install,
download the Basic Package's "self-extracting RAR archive." Wait for the download to finish
and open it to begin installing XAMPP. Click the "Install" button to start the file extraction.
When the Command Prompt screen appears, press the "Enter" key at every question to accept
default settings.
• Start the XAMPP program. When started, XAMPP loads itself into your icon tray. The icon is
orange with a white bone-like shape in its center. Single-click the icon to expand the Control
Panel. Click on the "Start" button next to "Apache" to start your Apache Web server. When
Apache is running, the word "Running" will appear next to it, highlighted in green. Also start
"MySQL" if your PHP scripts depend on a MySQL database to run.
• Place your PHP files in the "htdocs" folder located under the "XAMMP" folder on your C:
drive. The file path is "C:\xampp\htdocs" for your Web server.
• Make sure your PHP files are saved as such; they must have the ".php" file extension. The file
path is " C:\xampp\htdocs\test"
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
• If you create a folder named "test," then use the address "localhost/test" to open them in your
browser.
Operators are symbols used to manipulate data stored in variables. A value operated on by an
operator is referred to as an operand. The combination of operands with an operator to produce
a result is called an expression.
Example: (1+2)
Here integer value 1 and 2 are operands and + is the addition operator, operates on operands to
produce the integer result 3.
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
<?php
// simple assign operator
$a=20;
echo "a=$a <br/>";
?>
Output:
a=20
a=a+10 :30
a=a-10 :20
a=a*10 :200
a=a/10 :20
a=a%2 :0
PHP can:
With PHP you are not limited to output HTML. You can output images, PDF files, and even flash
movies. You can also output any text, such as XHTML and XML.
Why PHP?
<?php <?php
$x = -12; $y = 2;
echo ($x > 0) ? “The number is positive”: “The if (**$y == 4)
number is negative”; {
?> echo $y;
}
?>
<?php <?php
$x = "test"; $a = 10;
$y = "this"; echo ++$a;
$z = "also"; echo $a++;
$x .= $y .= $z ; echo $a;
echo $x; echo ++$a;
echo $y; ?>
?>
Experiment No: 02
Write a PHP program to demonstrate the use of looping structures using
a) while statement
b) Do-while else statement
c) for statement
d) for-each statement
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Resources required:
Hardware Software
Computer System Any database tools such as XAMPP
Practical Significance:
Generally instructions are executed sequentially. In some cases it is necessary to change the
sequence of executions based on certain conditions. For this purpose decision control structure is
required.
Theoretical Background:
a) if statement
The if statement is used to execute a block of code only if the specified condition evaluates to
true.
Syntax:
if(condition)
{
// Code to be executed
}
b) if-else Statement:
If...else statement first checks the condition. If condition is true, then true statement block is
executed. If condition is false, then false statement block is executed.
Syntax:
if (condition)
{
// if TRUE then execute this code
}
else
{
// if FALSE then execute this code
}
c) Nested-if Statement:
Nested if statements mean an if block inside another if block. Nested if else statement used
when we have more than two conditions. It is also called if else if statement.
Syntax:
if(condition1)
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
{
// Code to be executed if condition1 is true
}
elseif(condition2)
{
// Code to be executed if the
condition1 is false and condition2 is true
}
else
{
// Code to be executed if both condition1 and condition2 are false
}
d) Switch Statement
The switch-case statement is an alternative to the if-elseif-else statement, which does
almost the same thing. The switch-case statement tests a variable against a series of values
until it finds a match, and then executes the block of code corresponding to that match. The
switch statement is used to avoid long blocks of if..elseif..else code.
Syntax:
switch(n)
{
case statement1:
//code to be executed if n==statement1;
break;
case statement2:
//code to be executed if n==statement2;
break;
case statement3:
//code to be executed if n==statement3;
break;
case statement4:
//code to be executed if n==statement4;
break;
......
default:
//code to be executed if n != any case;
}
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
<?php
$a=-10;
if ($a > 0)
{
echo "The number is positive";
}
else
{
echo "The number is negative";
}
?>
Output:
The number is negative
<?php
$x=-1;
switch($x) {
case 1:
echo "This is case No 1.";
break;
case 2:
echo "This is case No 2.";
break;
case 3:
echo "This is case No 3.";
break;
case 4:
echo "This is case No 4.";
break;
default:
echo "This is default.";
}
?>
Output:
This is default.
Exercise:
1. Write a PHP code to perform arithmetic operations using switch case.
2. Difference between if…else and ternary operator.
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Experiment No: 03
Write a PHP program to demonstrate the use of looping structures using
a) while statement
b) Do-while else statement
c) for statement
d) for-each statement
Resources required:
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Hardware Software
Computer System Any database tools such as XAMPP
Practical Significance:
A loop causes a section of a program to be repeated a certain number of times. The repetition
continues while the condition set for it remains true. When the condition becomes false, the loop
ends and the control is passed to the statement following the loop. Loop in PHP is used to execute
a statement or a block of statements, multiple times until and unless a specific condition is met.
This helps the user to save both time and effort of writing the same code multiple times.
Theoretical Background:
a) While Statement:
The while statement will execute a block of code if and as long as a test condition is true. The
while is an entry controlled loop statement. i.e., it first checks the condition at the start of the loop
and if its true then it enters the loop and executes the block of statements, and goes on executing it
as long as the condition holds true.
Syntax:
while (if the condition is true)
{
// code is executed
}
b) do-while Statement
This is an exit control loop which means that it first enters the loop, executes the statements, and
then checks the condition. Therefore, a statement is executed at least once on using the do…while
loop. After executing once, the program is executed as long as the condition holds true.
Syntax:
do
{
//code is executed
} while (if condition is true);
c) for Statement:
The for statement is used when you know how many times you want to execute a statement or a
block of statements. That is, the number of iterations is known beforehand. These type of loops are
also known as entry-controlled loops. There are three main parameters to the code, namely the
initialization, the test condition and the counter.
Syntax:
for (initialization expression; test condition; update expression)
{
// code to be executed
}
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
d) For-each statement:
foreach loop is used for array and objects. For every counter of loop, an array element is assigned
and the next counter is shifted to the next element.
Syntax:
foreach (array_element as value)
{
//code to be executed
}
Output:
4
12
Program Code:
Write a program in PHP to display content of array using for-each loop.
<?php
$arr = array (10, 20, 30, 40, 50);
foreach ($arr as $i)
{
echo "$i <br/>";
}
?>
Output:
10
20
30
40
50
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Exercise:
1. Write the output for following script:
<?php <?php
for ($x = 0; $x <= 10; print ++$x) $i = 0;
{ for ($i)
print ++$x; {
} print $i;
?> }
?>
<?php <?php
for ($x = -1; $x < 10;--$x) for ($x = 1; $x < 10;++$x)
{ {
print $x; print "*\t";
} }
?> ?>
2. Create a script to construct the following pattern, using nested for loop.
*
**
***
****
*****
3. Create a script to construct the following pattern, using a nested for loop.
*
**
***
****
*****
*****
****
***
**
*
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
4. Write a PHP script that creates the following table using for loops.
Add cellpadding="3px" and cellspacing="0px" to the table tag.
5. Write a PHP script that creates the following table (use for loops).
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
https://www.w3resource.com/php-exercises/php-for-loop-exercises.php#editorr
Experiment No: 04
Write a PHP program for creating and manipulating:
a) Indexed array
b) Associative array
c) Multidimensional array
Resources required:
Hardware Software
Computer System Any database tools such as XAMPP
Practical Significance:
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
• Arrays in PHP is a type of data structure that allows to store multiple elements of similar data
type under a single variable thereby saving us the effort of creating a different variable for
every data.
• An array in PHP is actually an ordered map. A map is a type that associates values to keys.
• The arrays are helpful to create a list of elements of similar types, which can be accessed using
their index or key.
Theoretical Background:
2. Associative Arrays
− This type of arrays is similar to the indexed arrays but instead of linear storage, every value can be
assigned with a user-defined key of string type.
− An array with a string index where instead of linear storage, each value can be assigned a specific
key.
− Associative array differ from numeric array in the sense that associative arrays use descriptive
names for id keys.
3. Multidimensional Arrays
− These are arrays that contain other nested arrays.
− An array which contains single or multiple arrays within it and can be accessed via multiple
indices.
− We can create one dimensional and two dimensional array using multidimensional arrays.
− The advantage of multidimensional arrays is that they allow us to group related data together.
// Accessing elements
echo "manisha P's email-id is: " . $person[1]["email"], "<br>";
echo "Vijay Patil's mobile no: " . $person[2]["mob"];
?>
Output :
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Exercise:
1. Write a PHP script to sort the following associative array :
array("Sophia"=>"31","Jacob"=>"41","William"=>"39","Ramesh"=>"40") in
a) ascending order sort by value
b) ascending order sort by Key
c) descending order sorting by Value
d) descending order sorting by Key
2. Write a PHP script which displays all the numbers between 200 and 250 that are divisible by
4.
3. Write a PHP script to lower-case and upper-case, all elements in an array.
Experiment No: 05
1. Write a PHP program to
a) Calculate length of string
b) Count the number of words in string- without using string functions
Resources required:
Hardware Software
Computer System Any database tools such as XAMPP
Practical Significance:
− PHP is a string oriented and it comes packed with many string functions.
− A string is a collection of characters. String is one of the data types supported by PHP.
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Theoretical Background:
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Exercise:
1. Write an example to remove HTML tags from a string in php?
Ans: Strip_tags() is function to remove HTML tag in the string
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Experiment No: 06
Write a simple PHP program to demonstrate use of simple function and parameterized function.
Resources required:
Hardware Software
Computer System Any database tools such as XAMPP
Practical Significance:
PHP functions are similar to other programming languages. A function is a piece of code which
takes one more input in the form of parameter and does some processing and returns a value.
Theoretical Background:
- They are built-in functions but PHP gives you option to create your own functions as well.
- A function will be executed by a call to the function. You may call a function from anywhere
within a page.
- There are two parts which should be clear to you
- Creating a PHP Function
- Calling a PHP Function
- It’s very easy to create your own PHP function. Suppose you want to create a PHP function
which will simply write a simple message on your browser when you will call it. Following
example creates a function called writeMessage() and then calls it just after creating it.
- A user-defined function declaration starts with the word function :
Syntax:
function functionName()
{
code to be executed;
}
PHP Functions with Parameters:
PHP gives you option to pass your parameters inside a function. You can pass as many as
parameters you like. These parameters work like variables inside your function. Following example
takes two integer parameters and add them together and then print them.
Program Code:
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Exercise:
1. Write a code to perform addition of 3 numbers using function.
2. Write a PHP program to check whether number is even or odd using function.
3. Write a PHP program to print factorial of number using function.
4. Write PHP program to calculate the sum of digits using function.
5. PHP program to check whether a number is prime or Not using function.
Experiment No: 07
Write a simple PHP program to create PDF document by using graphics concepts.
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Resources required:
Hardware Software
Computer System Any database tools such as XAMPP
Practical Significance:
FPDF is a PHP class which allows to generate PDF files with PHP code. F from FPDF stands for
Free: It is free to use and it does not require any API keys. you may use it for any kind of usage
and modify it to user needs.
Theoretical Background:
- Advantages of FPDF :
• Choice of measure unit, page format and margins
• Allow to set Page header and footer management
• It provides automatic line break, Page break and text justification
• It supports Images in various formats (JPEG, PNG and GIF)
• It allows to setup Colors, Links, TrueType, Type1 and encoding support
• It allows Page compression
- Procedure to create a PDF in PHP:
• Link to download latest version of FPDF class: http://www.fpdf.org/en/download.php
• Download v1.82 and extract and place the folder names as “fpdf182” at
C:\xampp\htdocs\test.
• Open fpdf182 folder and copy all sub-folders and files at C:\xampp\htdocs\test.
• Write the following script on notepad, save and execute.
Program Code:
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
<?php
require('fpdf.php');
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(60,10,'Hello PHP World!',1,1,'C');
$pdf->Output();
?>
Cell ():
Prints a cell (rectangular area) with optional borders, background color and character string.
The upper-left corner of the cell corresponds to the current position. The text can be aligned or
centered. After the call, the current position moves to the right or to the next line. It is possible to put a
link on the text.
If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before
outputting.
Syntax:
Cell(float w [, float h [, string txt [, mixed border [, int ln [, string align [, boolean fill
[, mixed link]]]]]]])
Parameters:
Parameter name Description
W Cell width. If 0, the cell extends up to the right margin.
H Cell height. Default value: 0
Txt String to print. Default value: empty string.
border Indicates if borders must be drawn around the cell. The value can be either a
number:
• 0: no border
1: frame Default value: 0
or
a string containing some or all of the following characters (in any order):
L: left T: top
R: right B: bottom
ln Indicates where the current position should go after the call. Possible
values are:
• 0: to the right
• 1: to the beginning of the next line
• 2: below
Putting 1 is equivalent to putting 0 and calling Ln() just after. Default
value: 0.
• C: center
• R: right align
fill Indicates if the cell background must be painted (true) or transparent (false).
Default value: false.
Exercise:
1. Write a script for setup Header and Footer along with line break and generate a pdf.
2. Write a code based on setFillcolor() and setTextColor() and generate a pdf.
Experiment No: 08
Write a simple PHP program to
a. Inherit members of super class in subclass.
b. Create constructor to initialize object of class by using object oriented concepts.
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Resources required:
Hardware Software
Computer System Any database tools such as XAMPP
Practical Significance:
Inheritance:
Theoretical Background:
Inheritance:
To declare that one class inherits the code from another class, we use the extends keyword.
Syntax :
class Parent
{
// The parent’s class code
}
class Child extends Parent
{
// The child can use the parent's class code
}
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
The child class can make use of all the non-private (public and protected) methods and
properties that it inherits from the parent class. This allows us to write the code only once in the
parent, and then use it in both the parent and the child classes.
class MyClass
{
function __construct()
{
echo “Welcome to PHP constructor. <br / > ”;
}
}
$obj = new MyClass; // Displays “Welcome to PHP constructor.”
Program Code:
a)
<?php
class Shape
{
public $length;
public $width;
public function __construct($length, $width)
{
$this->length = $length;
$this->width = $width;
}
}
class Rect extends Shape
{
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
public $height;
public function __construct($length, $width, $height)
{
$this->length = $length;
$this->width = $width;
$this->height = $height;
}
public function intro()
{
echo "The length is {$this->length}, the width is {$this->width}, and the height is {$this->height} ";
}
}
$r = new Rect(10,20,30);
$r->intro();
?>
Output :
The length is 10, the width is 20, and the height is 30
<?php
class Employee
{
public $name;
public $position;
function __construct($name,$position)
{
// This is initializing the class properties
$this->name=$name;
$this->profile=$position;
}
function show_details()
{
echo $this->name." : ";
echo "Your position is ".$this->profile."<br>";
}
}
b)
<?php
class Employee
{
public $name;
public $position;
function __construct($name,$position)
{
// This is initializing the class properties
$this->name=$name;
$this->profile=$position;
}
function show_details()
{
echo $this->name." : ";
echo "Your position is ".$this->profile."<br>";
}
}
Exercise:
1. How to implement multiple inheritance in PHP?
2. Implement following inheritance:
Class : square
Length, area()
Class : rectangle
Breadth, rectarea()
Class: box
Height, volume()
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Experiment No: 09
Write a simple PHP program on Introspection and Serialization.
Resources required:
Hardware Software
Computer System Any database tools such as XAMPP
Practical Significance:
Introspection
− Introspection in PHP offers the useful ability to examine an object's characteristics, such as its name, parent class
(if any) properties, classes, interfaces and methods.
− PHP offers a large number functions that you can use to accomplish the task.
− In-built functions in PHP Introspection :
Function Description
Program Code:
<?php
class Derived
{
public function details()
{
echo "I am a Derived(super) class for the Child(sub) class. <BR>";
}
}
class sub extends Derived
{
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
public function details()
{
echo "I'm " .get_class($this) , " class.<BR>";
echo "I'm " .get_parent_class($this) , "'s child.<BR>";
}
}
//details of parent class
if (class_exists("Derived"))
{
$der = new Derived();
echo "The class name is: " .get_class($der) . "<BR>";
$der->details();
}
//details of child class
if (class_exists("sub"))
{
$s = new sub();
$s->details();
if (is_subclass_of($s, "Derived"))
{
echo "Yes, " .get_class($s) . " is a subclass of Derived.<BR>";
}
else
{
echo "No, " .get_class($s) . " is not a subclass of Derived.<BR>";
}
}
Output :
The class name is: Derived
I am a Derived (super) class for the Child(sub) class.
I'm sub class.
I'm Derived's child.
Yes, sub is a subclass of Derived.
Serialization
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
− Serialization is a technique used by programmers to preserve their working data in a format that can later be restored
to its previous form.
− Serializing an object means converting it to a byte stream representation that can be stored in a file. Serialization in
PHP is mostly automatic, it requires little extra work from you, beyond calling the serialize () and unserialize( )
functions.
Serialize() :
− The serialize() converts a storable representation of a value.
− The serialize() function accepts a single parameter which is the data we want to serialize and returns a serialized
string.
− A serialize data means a sequence of bits so that it can be stored in a file, a memory buffer or transmitted across a
network connection link. It is useful for storing or passing PHP values around without losing their type and structure.
Syntax :
serialize(value1);
unserialize() : unserialize() can use string to recreate the original variable values i.e. converts actual data from
serialized data.
Syntax :
unserialize(string1);
Program Code:
<?php
$s_data= serialize(array('Welcome', 'to', 'PHP'));
print_r($s_data . "<br>");
$us_data=unserialize($s_data);
print_r($us_data);
?>
Output :
a:3:{i:0;s:7:"Welcome";i:1;s:2:"to";i:2;s:3:"PHP";}
Array ( [0] => Welcome [1] => to [2] => PHP )
Practical related questions:
1. State the use of unserialize().
2. List the Magic Methods with PHP Object Serialization.
Exercise:
1. Declare a class as “Test” with three user defined functions. List name of the class and functions declared in
the class “Test”.
2. Declare an interface “MyInterface’. Write a script for whether interface exits or not.
3. Write a script to based on unserialize().
Experiment No: 10
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Resources required:
Hardware Software
Computer System XAMPP
Knowledge required:
Students should know about the designing forms in HTML along with GET and POST method.
Practical Significance:
HTML Forms are required, when you want to collect some data from the site visitor. For
example, during user registration you would like to collect information such as name, email
address, credit card, etc. A form will take input from the site visitor and then will post it to a back-
end application such as CGI, ASP Script or PHP script etc. The back-end application will perform
required processing on the passed data based on defined business logic inside the application.
Theoretical Background:
GET Method
This is the built in PHP super global array variable that is used to get values submitted via HTTP
GET method. Data in GET method is sent as URL parameters that are usually strings of name and
value pairs separated by ampersands (&). URL with GET data look like this:
http://www.abc.com/dataread.php?name=ram&age=20.
The name and age in the URL are the GET parameters; ram and 20 are the value of those
parameters. More than one parameter=value can be embedded in the URL by concatenating with
ampersands (&).
POST Method
This is the built in PHP super global array variable that is used to get values submitted via HTTP
POST method. Data in POST method is sent to the server in a form of a package in a separate
communication with the processing script. User entered Information is never visible in the URL
query string as it is visible in GET. The POST method can be used to send the much larger
amount of data and text data as well as binary data (uploading a file).
Form Controls
The HTML <form> element defines a form which contains form controls that are used to collect
user input. Example text fields, text area, checkboxes, radio buttons, list, submit buttons and
more.
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Text Field
Text Field is used to take a single line input from the user. Text Field will be included in <form>
element of a web page that will be used to take user input, which will be sent to PHP script
available on the server. Data on the server will be fetched by any one of the super global variable
$_GET and $_POST, after receiving it will be processed and the result will be sent to the user in a
form of response.
Text Area
Text Area is used to take multi line input from the user.
Text Area will be included in <form> element of a web page that will be used to take multi line
input like suggestions, address, feedback from users, which will be sent to PHP script available on
the server.Data on the server will be fetched by any one of the super global variable $_GET and
$_POST, after receiving it will be processed and the result will be sent to user in a form of
response.
Radio Button
Radio Button is used to make the user select single choice from a number of available choices.
Radio Button will be included in <form> element of a web page that will be used single choice
input from the user, which will be sent to PHP script available on the server. Data on the server
will be fetched by any of the super global variable $_GET and $_POST, after receiving it will be
processed and the result will be sent to the user in a form of response.
Check Box
Check Box is used to select one or more options from available options displayed for selection.
Check Box will be displayed as square box which will be activated when ticked (checked). Check
Box will be included in <form> element of a web page that will be used to take user input, which
includes multiple options like hobbies, where user can select one or more hobby form the multiple
hobbies displayed on a web page, which will be sent to PHP script available on the server.Data on
the server will be fetched by any one of the super global variable $_GET and $_POST, after
receiving it will be processed and the result will be sent to the user in a form of response.
Buttons
Button is created using <button> tag. Text and Image can be displayed on the button by placing
the text or image between the opening and closing tags of button. Buttons has to be added with
actions using JavaScript or by associating the button with a form. In we are creating button in
form <input> tag is used to create a button.
Program Code:
checkboxdemo.html
<html>
<head>
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
<title> Text Field Demo</title>
</head>
<body>
<form method="get" action="phpcheckboxdemo.php">
<label>Select your Hobbies:</label>
<input type="checkbox" name="cricket" value="Cricket" checked > Cricket
<input type="checkbox" name="football" value="Football"> Football
<input type="checkbox" name="basketball" value="Basket Ball" > Basket Ball
<input type="submit" value="Submit">
</form>
</body>
</html>
<?php
echo "<p>Your Hobbies are : " . $_GET["cricket "] .",". $_GET["football0"] ."," . $_GET["basketball"] . "
</p>";
?>
Output:
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Exercise:
1. Write a PHP program that demonstrate form element Text box, Radio button, Check box,
Button.
2. Perform arithmetic operations using text filed and buttons and result should be displayed on
same page (Use PHP_SELF).
3. Perform arithmetic operations using text filed and buttons and result should be displayed on
another page.
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Experiment No: 11
Design web page using following form controls.
a) List Box
b) Combo box
c) Hidden field
Resources required:
Hardware Software
Computer System XAMPP
Practical Significance:
HTML Forms are required, when you want to collect some data from the site visitor. For example,
during user registration you would like to collect information such as name, email address, credit
card, etc. A form will take input from the site visitor and then will post it to a back-end application
such as CGI, ASP Script or PHP script etc. The back-end application will perform required
processing on the passed data based on defined business logic inside the application.
Theoretical Background:
List Box
List Box is used to create drop down list of options. HTML <select> tag will be include in
<form>element of a web page that will be used to display dropdown list where user can select
single or multiple options (when multiple attribute is set), which will be send to PHP script
available on server. The <option> tag will be used in <select> tag in order to drop list of options.
Data on the server will be fetched by any one of the super global variable $_GET and $_POST,
after receiving it will be processed and the result will be sent to the user as a response.
Hidden Controls
Hidden Controls are used to store the data in a Web page that user can’t see. Hidden Controls will
be included in <form> element of a web page that will be used to store data that will not be visible
to the user, which will be sent to PHP script available on the server. Data on the server will be
fetched by any one of the superglobal variable $_GET and $_POST, after receiving it will be
processed and the result will be sent to the user in a form of response.
Program Code:
hiddendemo.html
<html>
<head>
<title> Hidden Control Demo</title>
</head>
<body>
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
<form method="post" action="phphiddendemo.php">
<input type="hidden" name="user_id" id="user_id" value="101">
<input type="submit" value="Submit">
</form>
</body>
</html>
phphiddendemo.php
<?php
if(isset($_POST["user_id"])){
echo "<p>User ID : " . $_POST["user_id"] . "</p>";
}
?>
Output:
Exercise:
1. Write a PHP program that demonstrate form elements List Box, Combo Box.
2. Demonstrates Hidden Fields.
Experiment No: 12
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Resources required:
Hardware Software
Computer System XAMPP
Practical Significance:
User may by mistakenly submit the data through form with empty fields or in wrong format. PHP
script must ensure that required fields are complete and submitted data is in valid format. PHP
provides some inbuilt function using these functions that input data can be validated.
Theoretical Background:
− empty() function will ensure that text field is not blank it is with some data, function accepts a
variable as an argument and returns TRUE when the text field is submitted with empty string,
zero, NULL or FALSE value.
− Is_numeric() function will ensure that data entered in a text field is a numeric value, the function
accepts a variable as an argument and returns TRUE when the text field is submitted with numeric
value.
− preg_match() function is specifically used to performed validation for entering text in the text
field, function accepts a “regular expression” argument and a variable as an argument which has
to be in a specific pattern. Typically it is for validating email, IP address and pin code in a form.
− For Example a PHP page formvalidation.php is having three text fields name, mobile number and
email from user, on clicking Submit button a data will be submitted to PHP script validdata.php
on the server, which will perform three different validation on these three text fields, it will check
that name should not be blank, mobile number should be in numeric form and the email is
validated with an email pattern.
Program Code:
formvalidation.php
<html>
<head>
<title> Validating Form Data</title>
</head>
<body>
<form method="post" action="validdata.php">
Name :<input type="text" name="name" id="name" /><br/>
Mobile Number :<input type="text" name="mobileno" id="mobileno" /><br/>
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
validdata.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if(empty($_POST['name']))
{
echo "Name can't be blank<br/>";
}
if(!is_numeric($_POST['mobileno']))
{
echo "Enter valid Mobile Number<br/>";
}
$pattern ='/\b[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}\b/';
if(!preg_match($pattern,$_POST['email']))
{
echo "Enter valid Email ID.<br/>";
}
}
?>
Output:
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Exercise:
1. Write a PHP script to check that emails are valid or not.
Experiment No: 13
Write simple PHP program to
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Resources required:
Hardware Software
Computer System XAMPP
Practical Significance:
PHP cookie is a small piece of information which is stored at client browser. It is used to recognize
the user. PHP session is used to store and pass information from one page to another temporarily
(until user close the website). PHP session technique is widely used in shopping websites where
we need to store and pass cart information e.g. username, product code, product name, product
price etc from one page to another. PHP session creates unique user id for each browser to
recognize the user and avoid conflict between multiple browsers.
Theoretical Background:
Cookies:
Cookie is created at server side and saved to client browser. Each time when client sends request to
the server, cookie is embedded with request. Such way, cookie can be received at the server side.
In short, cookie can be created, sent and received at server end.
A cookie is a small file with the maximum size of 4KB that the web server stores on the client
computer.
A cookie can only be read from the domain that it has been issued from. Cookies are usually set in
an HTTP header but JavaScript can also set a cookie directly on a browser.
Fig. Cookies
There are three steps involved in identifying returning users :
1. Server script sends a set of cookies to the browser. For example : name, age or identification
number etc.
2. Browser stores this information on local machine for future use.
3. When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user.
There are two types of cookies :
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
PHP provides a inbuilt function setcookie(), that can send appropriate HTTP header to create the
cookie on the browser.
Only name argument is must but it is better to pass value, expires and path to avoid any ambiguity.
Syntax : setcookie(name, value, expire, path, domain, secure, HttpOnly);
Attributes of Cookie:
Attribute of Description
cookies
Expires The time when a cookie will get expire. When it reaches to its expiration period cookies is deleted from
browser automatically. If value is set to zero, it will only last till the browser is running its get deleted when
the browser exits.
Path The path where browser to send the cookies back to the server. If the path is specified, it will only send to
specified URL else if it is stored with “/” the cookie will be available for all the URL’s on the server.
Domain The browser will send the cookie only for URLs within this specified domain. By default is the server host
name.
Secure If this field is set, the cookie will only be sent over https connection. By default it is set to false, means it is
okay to send the cookie over an insecure connection.
HttpOnly This field, if present, tells the browser that it should only make the cookie assessable only to scripts that run
on the Web server (that is, via HTTP). Attempts to access the cookie through JavaScript will be rejected.
Session:
Session are used to store important information such as the user id more securely on the server
where malicious users cannot temper with them.
To pass values from one page to another.
Sessions are the alternative to cookies on browsers that do not support cookies.
You want to store global variables in an efficient and more secure way compared to passing them
in the URL
You are developing an application such as a shopping cart that has to temporary store information
with a capacity larger than 4KB.
$_SESSION["username"] = "abc";
?>
A PHP function session_unset() is used to remove all session variables and session_destroy() is
used to destroy session.
Exercise:
1. Write a program that demonstrate use of cookies.
2. Write a PHP program that demonstrate use of session.
Experiment No: 14
Write simple PHP program for sending and receiving plain text messages.
Resources required:
Hardware Software
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Practical Significance:
PHP mail is an inbuilt PHP function which is used to send emails from PHP scripts.
It can also be used to send email, to your newsletter subscribers, password reset links to users who
forget their passwords, activation/confirmation links, registering users and verifying their email
addresses
Theoretical Background:
PHP uses Simple Mail Transmission Protocol (SMTP) to send mail.
Settings of the SMTP mail can be done through “php.ini” file present in the PHP installation
folder.
Any text editor will be used to open and edit “php.ini”file.
Locate [mail function] in the file.
After [mail function]in the file following things will be displayed :
Don’t remove the semi column if you want to work with an SMTP Server like Mercury
; SMTP = localhost;
; smtp_port = 25
Remove the semi colons before SMTP and smtp_port and set the SMTP to your smtp server and
the port to your smtp port. Your settings should look as follows :
SMTP = smtp.example.com
smtp_port = 587
We can get your SMTP settings from your web hosting providers.
PHP Mail
PHP mail is an inbuilt PHP function which is used to send emails from PHP scripts.
It is a cost-effective way of notifying users of important events.
User’s gets contact you via email by providing a contact us form on the website that emails the
provided content.
It can also be used to send email, to your newsletter subscribers, password reset links to users who
forget their passwords, activation/confirmation links, registering users and verifying their email
addresses
Syntax : mail( to, subject, message, headers, parameters );
Parameters Descriptions
Subject Required. Specifies the subject of the email. This parameter cannot contain any newline characters.
Required. Defines the message to be sent. Each line should be separated with a (\n). Lines should not
message
exceed 70 characters.
Headers Optional. Specifies additional headers, like From, Cc, and Bcc.
parameters Optional. Additional parameter to the send mail can be mentioned in this section.
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Program Code:
Exercise:
1. Write simple PHP program for sending and receiving plain text messages through mail ( ).
2. Write a steps to send and receive mail.
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Experiment No: 15
Develop a simple application to
1. Enter data into database
2. Retrieve and present data from database.
Resources required:
Hardware Software
Computer System XAMPP
Practical Significance:
MySQL is used to manage stored data and is an open source Database Management Software
(DBMS) or Relational Database Management System (RDBMS). PHP and MySQL are server side
technologies, both are used on server side so the combination of these is preferred to developed
cloud based application.
Theoretical Background:
PHP 5 and later can work with a MySQL database using:
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
$conn->close();
?>
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Program Code:
<?php
$hn = 'localhost';
$db = 'college';
$un = 'root';
$pw = ' ‘;
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
$query = "SELECT * FROM student";
$result = $conn->query($query);
if (!$result) die($conn->error);
$rows = $result->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$result->data_seek($j);
echo 'Roll No.: ' . $result->fetch_assoc()['rollno'] . '<br/>';
$result->data_seek($j);
echo 'Name: ' . $result->fetch_assoc()['name'] . '<br/>';
$result->data_seek($j);
echo 'Percentage: ' . $result->fetch_assoc()['percent'] . '<br/><br/>';
}
$result->close();
$conn->close();
?>
Exercise:
1. Write a PHP script to enter data in database.
2. Write a PHP script to retrieve and present the data from database.
Experiment No: 16
Develop a simple application to update, delete table data from database.
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Resources required:
Hardware Software
Computer System XAMPP
Practical Significance:
MySQL is used to manage stored data and is an open source Database Management Software
(DBMS) or Relational Database Management System (RDBMS). PHP and MySQL are server side
technologies, both are used on server side so the combination of these is preferred to developed
cloud based application.
Theoretical Background:
PHP 5 and later can work with a MySQL database using:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
Exercise:
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
Sem: VI