0% found this document useful (0 votes)
16 views55 pages

WBP Lab Manual

The document outlines the vision and mission of a Computer Engineering program, emphasizing technical skill development, ethical practices, and industrial exposure. It details the course on Web Based Application Development with PHP, including educational objectives, program outcomes, and specific outcomes related to software and hardware usage. Additionally, it provides practical exercises and theoretical backgrounds for PHP programming, including installation, syntax, and control structures.

Uploaded by

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

WBP Lab Manual

The document outlines the vision and mission of a Computer Engineering program, emphasizing technical skill development, ethical practices, and industrial exposure. It details the course on Web Based Application Development with PHP, including educational objectives, program outcomes, and specific outcomes related to software and hardware usage. Additionally, it provides practical exercises and theoretical backgrounds for PHP programming, including installation, syntax, and control structures.

Uploaded by

Aditya Makwana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Program: Computer Engineering (NBA Accredited)

Course: Web Based Application Development with PHP (22619)


Semester: VI

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.

Program Vision and Mission


Vision
To empower students with domain knowledge of Computer Engineering and interpersonal skills to
cater to the industrial and societal needs.

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

Program Educational Objectives

Provide socially responsible, environment friendly solutions to Computer engineering related broad-
based problems adapting professional ethics.

Adapt state-of-the-art Computer engineering broad-based technologies to work in multidisciplinary


work environments.

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

Program Outcomes (POs)


Basic knowledge: Apply knowledge of basic mathematics, science and basic engineering to
solve the problems related to application of computers and communication services in
1
storing, manipulating and transmitting data, often in the context of a business or other
enterprise.
Discipline knowledge: Apply Information Technology knowledge to solve broad-based
2 Information Technology related problems.
Experiments and practice: Plan to perform experiments, practices and to use the results to
3 solve Information Technology related problems.
Engineering Tools: Apply appropriate Information Technology related techniques/tools with
4 an understanding of the limitations.
The engineer and society: Assess societal, health, safety and legal issues and the consequent
5 responsibilities relevant to practice in the field of Information technology.
Environment and sustainability: Apply Information Technology related engineering
6 solutions for sustainable development practices in environmental contexts.
Ethics: Apply ethical principles for commitment to professional ethics, responsibilities and
7 norms of practice in the field of Information Technology.
Individual and team work: Function effectively as a leader and team member in
8 diverse/multidisciplinary teams.
9 Communication: Communicate effectively in oral and written form. .
Life-long learning: Engage in independent and life-long learning along with the technological
10 changes in the IT and allied industry.

Program Specific Outcomes (PSOs)

1 Computer Software and Hardware Usage: Use state-of-the-art technologies for


operation and application of computer software and hardware.

2 Computer Engineering Maintenance: Maintain computer engineering related software


and hardware systems.

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

a) Install and configure PHP, web server, MYSQL


b) Write a program to print “welcome to PHP”
c) Write a program using expression and operators.

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’;
?>

Program Code: Write a program to print “welcome to PHP”

<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 ".

How to Run a PHP File in XAMPP

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

Program Code: Write a program using expression and operators.

<?php
// simple assign operator
$a=20;
echo "a=$a <br/>";

//add then assign operator


$a+=10;
echo "a=a+10 :$a <br/>";

// subtract then assign operator


$a-=10;
echo "a=a-10 :$a <br/>";

// multiply then assign operator


$a*=10;
echo "a=a*10 :$a <br/>";

// Divide then assign(quotient) operator


$a/=10;
echo "a=a/10 :$a <br/>";

// Divide then assign(remainder) operator


$a%=2;
echo "a=a%2 :$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:

• generate dynamic page content


• create, open, read, write, delete, and close files on the server
• collect form data
• send and receive cookies
• add, delete, modify data in your database
• used to control user-access
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI

• can encrypt data

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 runs on different platforms (Windows, Linux, Unix, Mac OS X, etc.)


• PHP is compatible with almost all servers used today (Apache, IIS, etc.)
• PHP supports a wide range of databases.
• PHP is easy to learn and runs efficiently on the server side.

Practical related questions:


1. Sate difference between echo() and print().
2. State the difference between $ and $$ in PHP.
3. State the use of spaceship operator.
4. What are string operators available in PHP?
5. What is the use of var_dump() in php?
6. Analyze the difference between programming language and scripting language/

Exercise: Execute the following script and attach the output:

<?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;
}

Program Code: Write a program for whether number is positive or not.

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

Program Code: Write a program to demonstrate the use of Switch statement.

<?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.

Practical related questions:


1. How we use if..else and elseif statement in PHP?
2. Difference between if…else and switch statement.

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

3. Why break and continue statement used in php?


4. Write a code to find out whether the year is leap year or not.

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
}

Program Code: Write a program in PHP to calculate Square Root of a number.


<?php
function my_sqrt($n)
{
$x = $n;
$y = 1;
while($x > $y)
{
$x = ($x + $y)/2;
$y = $n/$x;
}
return $x;
}
print_r(my_sqrt(16)."<br/>");
print_r(my_sqrt(144)."<br/>");
?>

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

Practical related questions:


1. Write PHP program to print Fibonacci series.
2. Write a PHP program to print prime number up to n.
3. Difference between for and for-each loop.
4. Difference between while and do-while loop.

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.

1*1=1 1*2=2 1*3=3 1*4=4 1*5=5


2*1=2 2*2=4 2*3=6 2*4=8 2 * 5 = 10
3*1=3 3*2=6 3*3=9 3 * 4 = 12 3 * 5 = 15
4*1=4 4*2=8 4 * 3 = 12 4 * 4 = 16 4 * 5 = 20
5*1=5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25
6*1=6 6 * 2 = 12 6 * 3 = 18 6 * 4 = 24 6 * 5 = 30
7*1=7 7 * 2 = 14 7 * 3 = 21 7 * 4 = 28 7 * 5 = 35
8*1=8 8 * 2 = 16 8 * 3 = 24 8 * 4 = 32 8 * 5 = 40
9*1=9 9 * 2 = 18 9 * 3 = 27 9 * 4 = 36 9 * 5 = 45
10 * 1 = 10 10 * 2 = 20 10 * 3 = 30 10 * 4 = 40 10 * 5 = 50

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:

1. Indexed or Numeric Arrays


− An array with a numeric index where values are stored linearly.
− Numeric arrays use number as access keys.
− An access key is a reference to a memory slot in an array variable.
− The access key is used whenever we want to read or assign a new value an array element.

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.

Program Code: Associative array


<html>
<head>
<title>
array
</title>
</head>
<body>
<h1> Creating an array </h1>
<?php
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI

$course = array(1 => "Computer Engg.",


5 => "Information Tech.",
3 => "Electronics and Telecomm.");
echo $course [5];
?>
</body>
</html>
Output :
Creating an array
Information Tech.

Program Code: Multidimensional Array


<?php
// Defining a multidimensional array
$person = array(
array(
"name" => "Yogita K",
"mob" => "5689741523",
"email" => "[email protected]",
),
array(
"name" => "Manisha P.",
"mob" => "2584369721",
"email" => "[email protected]",
),
array(
"name" => "Vijay Patil",
"mob" => "9875147536",
"email" => "[email protected]",
)
);

// 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

manisha P's email-id is: [email protected]


Vijay Patil's mobile no: 9875147536

Practical related questions:


1. Write a PHP script that inserts a new item in an array in any position.
2. State the use of array_slice().
3. State the use of array_merge().
4. What is implode and explode?

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

2. Write a simple PHP program to demonstrate use of various built in 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

− The string variables can contain alphanumeric characters.


− PHP string functions are used to manipulate string values.

Theoretical Background:

Function Description Syntax Example


str_word_count( ) Count the number of Str_word_count(String) <?php
words in a string echo
str_word_count("Welcome to
PHP world!");
?>
Output: 4
strlen() Returns the Strlen(String) <?php
length of a string echo strlen("Welcome to
PHP");
?>
Output: 14
strrev() Reverses a string Strrev(String) <?php
echo strrev("Information
Technology");
?>
Output: ygolonhceT
noitamrofnI
strpos() Returns the Strops(String, text) <?php
position of the echo strpos("PHP contains for
first occurrence loop, for each and while
of a string inside loop","loop");
another string ?>
(case-sensitive)
Output: 17
str_replace() Replaces some Str_replace(string tobe <?php
characters in a string replaced, text, string) echo
(case-sensitive) str_replace("Clock","Click","Cl
ick and Clock");
?>
Output: Click and Click
ucwords() Convert the first Ucwords(String) <?php
character of each echo ucwords("welcome to php
word to uppercase world");

Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI

Function Description Syntax Example


?>
Output: Welcome To Php
World
strtoupper() Converts a string to Strtoupper(String) <?php
uppercase letters echo strtoupper("information
technology ");
?>
Output: INFORMATION
TECHNOLOGY
strtolower() Converts a string to Strtolower(String) <?php
lowercase letters echo
strtolower("INFORMATION
TECHNOLOGY");
?>
Output: information technology
Str_repeat() Repeating a string Str_repeat(String, <?php
with a specific repeat) echo str_repeat("*",10);
number of times.
?>
Output: **********
strcmp() Compare two strings Strcmp(String1, <?php
(case-sensitive). String2) echo strcmp("Hello
If this function world!","Hello world!");
returns 0, the two ?>
strings are equal. Output: 0
If this function Another example:
returns any negative
or positive numbers, <?php
the two strings are echo strcmp(" world!","Hello
not equal. PHP!");
?>
Output: -40
Substr() substr() function Substr(String, start, <?php
used to display or length) echo substr("Welcome to
extract a string from PHP",11)."<br>";
a particular position. echo substr("Welcome to
PHP",0,7)."<br>";
?>
Output:
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI

Function Description Syntax Example


PHP
Welcome
Str_split() To convert a string str_split(string,length); $str=”PHP”;
to an array Str_split($str);
Output:
Array ( [0] => P [1] => H [2]
=> P )
Str_shuffle() To randomly shuffle str_shuffle ( string $str $str=”PHP”;
all the character of a ) Str_shuffle($str);
string Output: PPH
Trim() Removes white trim(string,charlist) $str=” Welcome “
spaces and Output: Welcome
predefined
characters from a
both the sides of a
string.
Rtrim() Removes the white string rtrim ( string $str $str=”Hello PHP”
spaces from end of [, string Rtrim($str,”PHP”)
the string $character_mask ] ) Output: Hello
Ltrim() Removes the white ltrim(string,charlist); $str=” PHP”
spaces from left side Output: PHP
of the string
Chop() Remove whitespace chop(string,charlist); $str=”Hello PHP”
or other predefined Cho($str,”PHP”);
character from the
Output: Hello
right end of a string.
Chunk_split() Splits a string into chunk_split(string,lengt $str=”Hello PHP”;
smaller parts or h,end) Chunk_split($str,6,”…”);
chunks. Output: Hello… PHP…

Practical related questions:


1. How to find text within a string?
2. How to convert text in lowercase into title case?
3. Write a script to find length of the string “Vidyalankar Polytechnic”?

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

2. Count the number of words in string- without using string functions.


3. Write a simple PHP program to demonstrate use of various built in string functions.
4. Write a script for given string is palindrome or not.

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

/* Defining a PHP Function */


function writeMessage(){
echo "Welcome to PHP world!";
}

/* Calling a PHP Function */


writeMessage();
?>
</body>
</html>
Output :
Welcome to PHP world!
Example :
<?php
function addfunc($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addfunc(50, 20);
?>
This will display following result :
Sum of the two numbers is : 70

Practical related questions:


1. What is anonymous function?
2. Write the difference between built in function & user defined function.
3. What is variable function?

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.

align Allows to center or align the text. Possible values are:


• L or empty string: left align (default value)
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI

• C: center
• R: right align

fill Indicates if the cell background must be painted (true) or transparent (false).
Default value: false.

Practical related questions:


1. What's the difference between include and require?
2. Sate the use of Cell().
3. State the use of AddPage();
4. State the use of setFont().

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:

- Inheritance is a mechanism of extending an existing class by inheriting a class.


- We create a new sub class with all functionality of that existing class, and we can add new
members to the new sub class.
- When we inherit one class from another we say that inherited class is a subclass and the class
who has inherits is called parent class.

Constructor and Destructor:


- A constructor and a destructor are special functions which are automatically called when an
object is created and destroyed.
- Constructors are special member functions for initialize variables on the newly created object
instances from a class.
- When creating a new object, it’s useful to set up certain aspects of the object at the same time.
For example, you might want to set some properties to initial values, fetch some information
from a database to populate the object, or register the object in some way.
- Similarly, when it’s time for an object to disappear, it can be useful to tidy up aspects of the
object, such as closing any related open files and database connections, or unsetting other
related objects.
- An object’s constructor method is called just after the object is created, and its destructor
method is called just before the object is freed from memory.

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.

Constructor and Destructor:


− Normally, when you create a new object based on a class, all that happens is that the object is
brought into existence. (Usually you then assign the object to a variable or pass it to a function.)
By creating a constructor method in your class, however, you can cause other actions to be
triggered when the object is created.
To create a constructor, simply add a method with the special name _ _construct() to your class.
(That ’ s two underscores, followed by the word “ construct, ” followed by parentheses.) PHP
looks for this special method name when the object is created; if it finds it, it calls the method.

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>";
}
}

$employee_obj= new Employee("Prasad Koyande","developer");


$employee_obj->show_details();

$employee2= new Employee("Vijay Patil","Manager");


Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI
$employee2->show_details();
?>
Output :
Prasad Koyande : Your position is developer
Vijay Patil : Your position is Manager
− In the above example, all properties and functions are public hence they can access outside the
class.

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>";
}
}

$employee_obj= new Employee("Prasad Koyande","developer");


$employee_obj->show_details();

$employee2= new Employee("Vijay Patil","Manager");


$employee2->show_details();
?>
Output :
Prasad Koyande : Your position is developer
Vijay Patil : Your position is Manager

Practical related questions:


Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI

1. Define the relationship between a class and an object?


2. What is the purpose of $this & extends?
3. State the use of ‘self’ with suitable example.

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

class_exists() Checks whether a class has been defined.

get_class() Returns the class name of an object.

get_parent_class() Returns the class name of an object’s parent class.

is_subclass_of() Checks whether an object has a given parent class.

get_declared_classes() Returns a list of all declared classes.

get_class_methods() Returns the names of the class’ methods.

get_class_vars() Returns the default properties of a class.

interface_exists() Checks whether the interface is defined.

method_exists() Checks whether an object defines a method.

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

Design web page using following form controls.


e) Text box
f) Radio button
g) Check box
h) Button

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>

New file saved as phpcheckboxdemo.php

<?php
echo "<p>Your Hobbies are : " . $_GET["cricket "] .",". $_GET["football0"] ."," . $_GET["basketball"] . "
</p>";

?>

Output:

Practical related questions:

1.What is the difference between get and post methods?


2. What is the use of isset() function?

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:

Practical related questions:


1. Explain the superglobals in PHP?
2. How does PHP handle forms with multiple selections?
3. How does the form information get from the browser to the server?

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

Develop web page with data validation.

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

Email ID :<input type="text" name="email" id="email" /><br/>


<input type="submit" name="submit_btn" value="Submit" />
</form>
</body>
</html>

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

Practical related questions:


1. How to validate user input in PHP? Explain
2. Why is the need to validate user input?

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

1. Set cookies and read it


2. Demonstrate session management

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

1. Session Based which expire at the end of the session.


2. Persistent cookies which are written on hard disk.

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

Name The unique name is given to a particular cookie.

Value The value of the cookie.

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.

Set Session Variables


<?php
session_start();
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI

$_SESSION["username"] = "abc";
?>
A PHP function session_unset() is used to remove all session variables and session_destroy() is
used to destroy session.

Practical related questions:

1. How to initiate a session in PHP ?


2. How to register a variable in PHP session ?
3. What is the difference between PHP session and Cookie ?
4. What is the difference between session_unregister () and session_unset()?
5. What is the default session time in PHPH?
6. Is it possible to destroy a cookie ()?

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

Computer System XAMPP

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

To Required. Specifies the receiver or receivers email ids.

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:

Practical related questions:


1. How to send mail in PHP?
2. Explain the different parameters of mail function?
3. Explain SMTP protocol?

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:

MySQLi extension (the "i" stands for improved)


PDO (PHP Data Objects)

The CREATE DATABASE statement is used to create a database in MySQL.


<?php
$servername = "localhost";
$username = "username";
$password = "password";

// 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();
?>

Create Table SQL query Example


The CREATE TABLE statement is used to create a table in MySQL.
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP
)";

Insert Data SQL query Example


The INSERT INTO statement is used to add new records to a MySQL table:

INSERT INTO table_name (column1, column2, column3,...)


VALUES (value1, value2, value3,...)
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";

Select Data from database


The SELECT statement is used to select data from one or more tables:

SELECT column_name(s) FROM table_name


or we can use the * character to select ALL columns from a table:

SELECT * FROM table_name


$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);

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();
?>

Practical related questions:


1. Which command would you use to view the available databases or tables?
2. How can you view the structure of a table?
3. How is it possible to know the number of rows returned in the result set?
4. Which function returns the number of affected entries by a query?

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:

MySQLi extension (the "i" stands for improved)


PDO (PHP Data Objects)

Update Data In a MySQL Table Using MySQLi.


The UPDATE statement is used to update existing records in a table:
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Notice the WHERE clause in the UPDA
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";


if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI

$conn->close();
?>

Delete Data From a MySQL Table Using MySQLi


The DELETE statement is used to delete records from a table:
$sql = "DELETE FROM MyGuests WHERE id=3";

Practical related questions:


1. Write use of mysql_fetch_row() and mysql_fetch_array().
2. How do you connect to a MySQL database using mysqli?

Exercise:

1. Write a PHP script to update data in database.


2. Write a PHP script to delete the data from database.

Sem: VI
Program: Computer Engineering (NBA Accredited)
Course: Web Based Application Development with PHP (22619)
Semester: VI

Sem: VI

You might also like