You are on page 1of 80

Program Title:- Computer Engineering

Sem/Year:- 6th (I Scheme)


Course Title:- Web Based Application development with PHP
Course Abbreviation:- WBP Course Code:- 22619
Level of understanding the subject :- Easy & Medium

Prerequis Knowledge about Web Page Designing and Proficiency in programming


ites language and analytical skills.
Learning Students will get the knowledge of web based
Objective Knowledge
application development.
(What
Students will understand the process of Server
will my Understanding
installation and use of Scripting language.
students
Students will perform various operation on
KNOW Application
Arrays and Graphics.
by the
end of the Students will learn to analyse programming
Analysis
subject?) constructs and apply appropriate one.

Student will be able to design form and validate


Evaluation
controls.
Student will be able to create database and
Create
perform database operations.
Teaching
Scheme

Teaching
Theory Practical
Scheme
Credit
(L+T+P) Paper ESE PA TOTAL ESE PA TOTAL
L T P
hrs. Max Min Max Min Max Min Max Min Max Min Max Min

3 - 2 5 3 70 28 30* 0 100 40 25@ 10 25 10 50 20

Rationale :- To inculcate web based application development skills in students using


server side scripting.
Competency: Develop simple web based application using PHP Language.

Course Outcomes:
a. Develop Program using Control Statements.
b. Perform operations based on arrays and graphics.
c. Develop Program by applying various object oriented concepts.
d. Use form controls with validation to collect user’s input.
e. Perform database operations in PHP
Index
S.N. Description TH No. of
Understanding Marks Hrs Pr
Level
Units 70 48 16
1. Expressions & Control Statements in PHP Easy 12 06 3
2. Arrays, Functions & Graphics Medium 16 10 4
3. Apply Object Oriented Concepts in PHP Medium 16 12 2
1 4. Creating & Validating Forms Medium 12 12 5
5. Database Operations Medium 14 08 2
2 Assignments 5
50
3 Practice questions-Unit Tests
Questions
5Q-2M ,5Q-4M

4 List of Micro-project 10 ----- -----

5 Question papers & Models answer solution 4 ----- -----


Unit IV: Creating and Validating Forms
LO. Learning Outcomes/Unit Outcomes
No.

4a Use the relevant form control to get


user’s input.

4b Design web page using multiple forms


for the given problem.
4c
Apply given validation rules on the form.

4d
Set/modify/delete cookies using cookies attributes.

4e
Manage the given session using session variables.
Form:
A web Page containing GUI controls to read Input
and perform task.
Form:

Use- will create an html form which will act as a container to


hold other controls.

Syntax :
<form action=“name of file" method=“get or
post">

Action – will have path and will run when submit type
button is clicked

Method- can be “get” or “post”


When to use GET?
● Information sent from a form with the GET method is visible to everyone
● values are displayed in the URL
● GET also has limits on the amount of information to send. The limitation is about 2000
characters.
● GET may be used for sending non-sensitive data.
● Note: GET should NEVER be used for sending passwords or other sensitive information!

When to use POST?


● Information sent from a form with the POST method is invisible to others (all names/values
are embedded within the body of the HTTP request)
● and has no limits on the amount of information to send.
● Moreover POST supports advanced functionality such as support for multi-part binary input
while uploading files to server.
Text Box: User Input Control-

Use- To read Input from user as a text format.


A single line editor.
Syntax :

Label:<input type="text" name=“name for


textbox">

Example:
Name: <input type="text" name=“studname">
TextArea: User Input Control-
Use- To read Input from user as a text format.
A Multiline editor.
It Can be used for Address field, Story, Conclusion field, etc

Textarea having rows and columns means No.of rows to be visible on screen and
column means how many characters in one line to be visible on the screen
Syntax :

Label:<textarea name=“name for textarea“


rows=“no.of rows" cols=“no.of columns">

Example:
Address: <textarea name=“localadd“
rows="4" cols="50" >
Button: Push-Button- Trigger to perform any action

Types-

1. Submit - on clicking on this it will jump to specified path


in the action attribute of <form>
2. Reset - will clear data entered in the fields

<input type="submit" value ="Register">

<input type="reset" value ="Clear">


Syntax :
<input type=“submit“ value=“caption to be
displayed on button">

<input type=“reset“ value=“caption to be


displayed on button">

<input type="submit" value ="Register">

<input type="reset" value ="Clear">


Giving Choice to User:

Check Box Radio Button

Single Selection allowed


Multiple Selection allowed
RadioButton: Single Selection

Syntax:

<input type="radio" name=“groupname“ value=“value1”> Label1<br>


<input type="radio" name=“groupname" value=“value2”> Label2<br>

Example:

<input type="radio" name="contact" value="email"> Email<br>


<input type="radio" name="contact" value="phone"> Phone<br>
f1.html

<html>
<body>
<form action="f2.php" method="POST">
Select Contact Option:<br>
<input type="radio" name="contact" value="email"> Email<br>
<input type="radio" name="contact" value="phone"> Phone<br>
<input type="submit" name="ok" value="Okay">
<input type="reset" name="reset" value="Clear">
</form>
</body>
</html>
f2.php Name of radiobutton
<?php
$c= $_POST['contact'];
$b= $_POST['ok'];
if(isset($b))
Name of button(name attribute
{ value of submit button)
if ($c=="email")
echo "You will get E-mail!";
else
echo "You will get Call!";
}
else
echo "Click Okay Button";
echo "<br>Thank You";
?>
Checkbox: Multiple Selection

Syntax:

<input type=“checkbox" name=“name[]“ value=“value1”> Label1<br>


<input type=“checkbox" name=“name[]" value=“value2”> Label2<br>

Example:

<input type="checkbox" name=“lang[]" value=“e”> English<br>


<input type="checkbox" name=“lang[]" value=“m”> Marathi<br>
<input type="checkbox" name=“lang[]" value=“h”> Hindi<br>
f1.html

<html>
<body>
<form action="f2.php" method="POST">
<input type="checkbox" name="lang[]"
value="C/C++">C/C++<br/>
<input type="checkbox" name="lang[]" value="Java">Java<br/>
<input type="checkbox" name="lang[]" value="PHP">PHP<br/>
<input type="submit" name="ok" value="Okay">
<input type="reset" name="reset" value="Clear">
</form>
</body>
</html>
f2.php
<?php
$b= $_POST['ok'];
if(isset($b))
{
if(!empty($_POST['lang']))
{ foreach($_POST['lang'] as $i)
{ echo $i."</br>";
}
}
else
echo "Select Language,please";
}
echo "<br>Thank You";
?>
Giving Choice to User: multiple options to show

Choice control/combo box/


drop down list

Allows single selection


f1.html
<html>
<body>
<form action="f2.php" method="POST">
Choose any fruit
<select name="fruits">
<option value="Mango">Mango</option>
<option value="Grape">Grape</option>
<option value="Apple">Apple</option>
<option value="Orange">Orange</option>
</select><br><br>
<input type="submit" name="ok" value="Okay">
<input type="reset" name="reset" value="Clear">
</form>
</body>
</html>
f2.php
<?php
$b= $_POST['ok'];

if(isset($b))
{
echo " You have selected : ";
echo $_POST["fruits"];
}
echo "<br>Thank You";

?>
Giving Choice to User: multiple options to show

List control/Scrolling list

Allows single or multiple selection


f1.html Single Selection list
<html>
<body>
<form action="f2.php" method="POST">
Choose any fruit
<select name="fruits" size="4">
<option value="Mango">Mango</option>
<option value="Grape">Grape</option>
<option value="Apple">Apple</option>
<option value="Orange">Orange</option>
</select><br><br>

<input type="submit" name="ok" value="Okay">


<input type="reset" name="reset" value="Clear">
</form>
</body>
</html>
f2.php
<?php
$b= $_POST['ok'];

if(isset($b))
{
echo " You have selected : ";
echo $_POST["fruits"];
}
echo "<br>Thank You";

?>
f1.html Multiple Selection list
<html>
<body>
<form action="f2.php" method="POST">
Choose any fruit
<select name="fruits[]" size="4“ multiple>
<option value="Mango">Mango</option>
<option value="Grape">Grape</option>
<option value="Apple">Apple</option>
<option value="Orange">Orange</option>
</select><br><br>

<input type="submit" name="ok" value="Okay">


<input type="reset" name="reset" value="Clear">
</form>
</body>
</html>
f2.php
<?php
$b= $_POST['ok'];
$values = $_POST['fruits'];
if(isset($b))
{
echo " You have selected : "; Use Ctrl + mouse click to select items
foreach ($values as $a)
{
echo $a."<br>";
}
}
echo "<br>Thank You";
?>
Creating Form
Creating Home Screen (html- file)

<html>
<body>
<b>Student Registration</b><br><br><br><br>
<form action="f2.php" method="post">
Name: <input type="text" name="n"><br><br>
E-mail: <input type="text" name="e"><br><br>
<input type="submit" value ="Register">
<input type="reset" value ="Clear">
</form>
</body>
</html>

Save file as “f1.html” in C:\xampp\htdocs\


Save file as “f1.html” in C:\xampp\htdocs\

- To display expected Output ,we have to read data from two textboxes and display
on screen. For this reading and display task ,we have to write PHP Script.
- Write that script in new Notepad file and name should be the same as we have
given in “action” attribute of <form> tag.

<form action="f2.php" method="post">


To read field of HTML file in PHP Script-
<form action="f2.php" method="post">
<form action="f2.php" method=“get">

Use GET or POST according the type mentioned in “method” attribute of <form> tag

$_GET[“name of field”];

OR

$_POST[“name of field”];

Name: <input type="text" name="n"><br><br>


“f2.php”, Save file in C:\xampp\htdocs\

<html>

<body>

Welcome <?php echo $_POST["n"]; ?><br>

Your email address is: <?php echo $_POST["e"]; ?>

</body>

</html>
Start XAMPP Control Panel,Open Browser,Start
Localhost. And type name of html file
Type data in Html File

Click on Register Button


<form action="f2.php" method="post">
Validate Button is clicked or not

if(isset($_POST[“name of button"]))
{
//code
}
Empty String
f1.html
<html>
<body>
<form action="f2.php" method="POST">
Enter Your Name Please:
<input type="text" name=“un">
<br><br>
<input type="submit" name=“register" value="Submit">
</form>
f2.php
<?php
$n= $_POST[‘un'];
$b= $_POST[‘register'];

if ($b){
if (!empty($n))
{
echo 'The name you entered is ' . $n;
}
else {
echo ‘Please enter a name into this form field.';
}
}
?>
If Name entered and Submit
If Submit button is clicked button is clicked
without entering Name in textbox
Validate Name Field
f1.html
<html>
<body>
<form action="f2.php" method="POST">
Enter Your Name Please:
<input type="text" name=“un">
<br><br>
<input type="submit" name=“register" value="Submit">
</form>
f2.php

<?php
$n= $_POST[‘un'];
$b= $_POST[‘register'];
if ($b){
if (!empty($n))
{
if (!preg_match("/^[a-zA-Z-' ]*$/",$n))
echo "Only letters and white space allowed";
else
echo 'The name you entered is ' . $n;
}
else
echo ‘Please enter a name into this form field.';
}
?>
Validate Number Field
f1.html
<html>
<body>
<form action="f2.php" method="POST">
Contact Number:
<input type="text" name=“mob">
<br><br>
<input type="submit" name=“register" value="Submit">
</form>
f2.php
<?php
$n= $_POST['mob'];
$b= $_POST['register'];
if ($b)
{
if (!empty($n))
{
if (!preg_match ("/^[0-9]*$/", $n) )
echo "Only Numbers are allowed";
else
echo 'Contact Number : ' . $n;
}
else
echo "Please enter valid Mobile Number";
}
?>
Validate Number Field for length

f1.html
<html>
<body>
<form action="f2.php" method="POST">
Contact Number:
<input type="text" name=“mob">
<br><br>
<input type="submit" name=“register" value="Submit">
</form>
f2.php
<?php
$n= $_POST['mob'];
$l=strlen($n);
$b= $_POST['register'];
if ($b)
{
if (!empty($n))
{
if (!preg_match ("/^[0-9]*$/", $n) ) //for numbers
echo "Only Numbers are allowed";
else if(($l<10)||($l>10))
echo "Error:Mobile Number should be 10 digits";
else
echo 'Contact Number : ' . $n;
}
else
echo "Please enter valid Mobile Number";
}
?>
Validate E-mail ID Field
f1.html
<html>
<body>
<form action="f2.php" method="POST">
E-mail ID:
<input type="text" name="email">
<br><br>
<input type="submit" name="register" value="Submit">
</form>
f2.php
<?php
$e= $_POST['email'];
$b= $_POST['register'];
if ($b)
{
if (!empty($e))
{
if (!filter_var($e, FILTER_VALIDATE_EMAIL))
echo "Error-Enter valid Email ID";
else
echo 'E-mail ID : ' . $e;
}
else
echo "You have not entered E-mail. Please enter E-mail ID";
}
?>
PHP - Validate URL
The code below shows a way to check if a URL address syntax is valid (this regular expression
also allows dashes in the URL). If the URL address syntax is not valid, then store an error
message:

$website =$_POST["website"];

if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {

echo "Invalid URL";

}
Validate Form Data With PHP

The htmlspecialchars() function converts special characters to HTML entities. This means that it

will replace HTML characters like < and > with &lt; and &gt;.

This prevents attackers from exploiting the code by injecting HTML or Javascript code (Cross-

site Scripting attacks) in forms.

1. Strip unnecessary characters (extra space, tab, newline) from the user input data (with the PHP
trim() function)
2. Remove backslashes (\) from the user input data (with the PHP stripslashes() function)
A single-button form –To Check Number is Even/Odd

<html>
<body>
<form action="f2.php" method="POST">
Number :
<input type="text" name="num">
<br><br>
<input type="submit" name="register" value="Even/Odd">
</form>
f2.php
<?php
$n= $_POST['num'];
$b= $_POST['register'];
if ($b)
{
if (!empty($n))
{
if($n%2==0)
echo "Number : $n is Even";
else
echo "Number : $n is Odd";
}
else
echo "Error: You have not entered Number";
}
?>
Two submit -button form- Create Following Application
<html>
<body>
<form action="f2.php" method="POST">
Number 1:
<input type="text" name="num1"><br><br>
Number 2:
<input type="text" name="num2"><br><br>
<input type="submit" name="cal" value="+">
<input type="submit" name="cal" value="-">
</form>
</body>
</html>
f2.php

<?php
$n1= $_POST['num1'];
$n2= $_POST['num2'];
$b= $_POST['cal'];

if ($b=="+")
echo "Addition : " .$n1+$n2;
else
echo "Subtraction : ".$n1-$n2;

?>
Multiple submit -button form – Arithmetic calculation
<html>
<body>
<form action="f2.php" method="POST">
Number 1:<input type="text" name="num1"><br><br>
Number 2:<input type="text" name="num2"><br><br>
<input type="submit" name="cal" value="+">
<input type="submit" name="cal" value="-">
<input type="submit" name="cal" value="X">
<input type="submit" name="cal" value="/">
</form>
</body>
</html>
<?php
$n1= $_POST['num1'];
$n2= $_POST['num2'];
$b= $_POST['cal'];
switch($b)
{
case '+' :
echo "Addition : " .$n1+$n2;
break;
case '-' :
echo "Subtraction : ".$n1-$n2;
break;
case 'X' :
echo "Multiplication : ".$n1*$n2;
break;
case '-' :
echo "Division : ".$n1/$n2;
break;
default: echo "Select any operation to perform";
break;
}
echo "<br>Thank You";
?>
Designing a web page having multiple forms
f1.html
<html>
<body>

<form name="f1" method="POST" action="f2.php">


RollNo:<input type="text" name="rn">
<input type="submit" name="b1">
</form>
<form name="f2" method="post" action="f2.php">
Enrollment ID:<input type="text" name="eno">
<input type="submit" name="b2">
</form>
</body>
</html>
f2.php

<?php
if(isset($_POST['b1']))
{
echo "Rollno: ",$_POST['rn'];
}
else if(isset($_POST['b2']))
{
echo "Enno: ",$_POST['eno'];
}
?>
PHP Cookie
PHP cookie is a small piece of information which is stored at client browser. It is used to
recognize the user.

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.
PHP cookies have several advantages, including:

1. Improved User Experience: Cookies allow websites to store user-specific


information, such as preferences and login credentials, which can be
used to provide a more personalized user experience.
2. Persistent Data: Cookies allow websites to store data on the user's
device, which can persist even after the user closes the browser or turns
off their device. This makes it possible for websites to remember a user's
preferences and login credentials across multiple visits.
3. Easy Implementation: PHP cookies are easy to implement and can be
used to store a wide variety of data, making them a versatile tool for
website developers.
PHP setcookie() function
PHP setcookie() function is used to set cookie with HTTP response. Once cookie is set, you can
access it by $_COOKIE superglobal variable.

Syntax:

bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path

[, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

Example

1. setcookie("CookieName", "CookieValue");/* defining name and value only*/


2. setcookie("CookieName", "CookieValue", time()+1*60*60);//using expiry in 1 hour(1*60*60
seconds or 3600 seconds)
3. setcookie("CookieName", "CookieValue", time()+1*60*60, "/mypath/", "mydomain.com", 1);
PHP $_COOKIE
PHP $_COOKIE superglobal variable is used to get cookie.

Example

$value=$_COOKIE["CookieName"];//returns cookie value


PHP Cookie Example :File: cookie1.php
<?php
setcookie("user", "priti");
?>
<html>
<body>
<?php
if(!isset($_COOKIE["user"])) { echo "Sorry, cookie is not found!"; }
else { echo "<br/>Cookie Value: " . $_COOKIE["user"]; }
?>
</body>
</html>
Output:

Sorry, cookie is not found!

Firstly cookie is not set. But, if you refresh the page, you will see cookie is set now.

Output:

Cookie Value: priti


PHP Delete Cookie
If you set the expiration date in past, cookie will be deleted.
File: cookie1.php

<?php

setcookie ("CookieName", "", time() - 3600);// set the expiration date to one hour
ago

?>
Creating cookies:
<?php
setcookie("name", "John Watkin", time()+3600, "/","", 0);
setcookie("age", "36", time()+3600, "/", "", 0);
?>
<html>

<head>
<title>Setting Cookies with PHP</title>
</head>

<body>
<?php echo "Set Cookies"?>
</body>

</html>
Accessing cookies:
<html>
<head> <title>Accessing Cookies with PHP</title> </head>
<body>

<?php
echo $_COOKIE["name"]. "<br />";

/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. "<br />";

echo $_COOKIE["age"] . "<br />";

/* is equivalent to */
echo $HTTP_COOKIE_VARS["age"] . "<br />";
?>
</body>
</html>
PHP Session
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.
PHP session_start() function
PHP session_start() function is used to start the session.

It starts a new or resumes existing session.

It returns existing session if session is created already. If session is not available, it creates and
returns new session.

Syntax

bool session_start ( void )

Example

session_start();
PHP $_SESSION
PHP $_SESSION is an associative array that contains all session variables. It is used to
set and get session variable values.

Example: Store information

$_SESSION["user"] = "Sachin";

Example: Get information

echo $_SESSION["user"];
PHP Session Example
File: session1.php File: session2.php
<?php <?php
session_start(); session_start();
?> ?>
<html> <html>
<body> <body>
<?php <?php
$_SESSION["user"] = "Sachin"; echo "User is: ".$_SESSION["user"];
echo "Session information are set successfully.<br/>"; ?>

?> </body>

<a href="session2.php">Visit next page</a> </html>

</body>
</html>
PHP Session Counter Example
File: sessioncounter.php

<?php

session_start();

if (!isset($_SESSION['counter'])) {

$_SESSION['counter'] = 1;

} else {

$_SESSION['counter']++;

echo ("Page Views: ".$_SESSION['counter']);


PHP Destroying Session
PHP session_destroy() function is used to destroy all session variables
completely.
File: session3.php

<?php

session_start();

session_destroy();

?>
PHP mail() function
Syntax
mail(to,subject,message,headers,parameters);
Example:
<?php
$to = "somebody@example.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: webmaster@example.com" . "\r\n" .
"CC: somebodyelse@example.com";
mail($to,$subject,$txt,$headers);
?>
THANK YOU

You might also like