You are on page 1of 26

Chapter – 4

Creating and validating forms


Marks- 12

Content outline:
4.1 Creating a webpage using GUI components, browser role-GET and POST methods, Server role
4.2 Form controls: textbox, textarea, radio button, check box, list, and buttons
4.3 Working with multiple forms
4.4 Web page validation
4.5 Cookies: use of cookies, attributes of cookies, create cookies, modify cookies, delete cookies
4.6 Sessions: use of session, start session, get session variables, destroy sesions
4.7 Sending E-mail

4.1 Creating a webpage using GUI components, browser role-GET and POST methods, Server
role
Q. How to handle form in PHP?
Ans:

Fig: Process of form handling


• When user fill information while opening an email account, user is actually interacting with
a form.
• Forms are generally used to accept input from user and submit it to the server for
processing.

Notes By- G. R. Jagtap


1
• Form contains HTML tags related to graphical user interface such as textbox, buttons,
checkbox etc.
• Form is created using the tag <form>…</form> and GUI items.
Example:
HTML Code
<html>
<body>
<form action="form1.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>

PHP Code
<?php
echo "Name - ". $_POST["name"];
echo " Email - ". $_POST["email"];
?>

Notes By- G. R. Jagtap


2
Q. Explain Browser role and server role in web development.
Ans:
Browser role:

• HTML form consist of text fields, list, buttons etc for getting request from user.
• When user fills the data on the form and submit it, URL is encoded by the browser and
submitted to server for further processing.

Server role:
• When the browser requests a web page from the server, it sets TCP/IP connection and sends
a request in an HTTP format.
• The server verifies the request came from the browser and gives response.

Notes By- G. R. Jagtap


3
Q. Explain PHP GET and POST variables.
Ans:
HTML tags are used to create form.
Forms are created using <form>…</form> tag.
GUI components are added on forms such as text fields, list, checkbox, buttons etc.
Form submission type can be – GET or POST.
Depending upon the method get() or post() used in html form, $_GET or $_POST variables are
used in PHP script.
Example:
1) Use of get() Method and $_GET variable
HTML Code
<html>
<body>
<h3>Sign-In Form</h3>
<form method = "get" action="login.php">
Enter Username:<input type = "text" name = "uname">
<br>
Enter Password: <input type = "password" name = "upass">
<br>
<input type = "submit" name = "submit" value = "Log-In">
</form>
</body>
</html>

PHP Script
<?php
Notes By- G. R. Jagtap
4
$name = $_GET['uname'];
$pass = $_GET['upass'];
if($name=="admin" && $pass=="123")
echo "Login Successful ";
else
echo "Login Fail";
?>

In above screen, user input is displayed in address bar of the browser. This is because of get()
method.

2) Use of post() Method and $_POST variable


HTML Code
<html>
<body>
<h3>Sign-In Form</h3>
<form method = "post" action="login.php">
Enter Username:<input type = "text" name = "uname">
<br>
Enter Password: <input type = "password" name = "upass">
<br>
<input type = "submit" name = "submit" value = "Log-In">
</form>
</body>
</html>

Notes By- G. R. Jagtap


5
PHP Script
<?php
$name = $_POST['uname'];
$pass = $_POST['upass'];
if($name=="admin" && $pass=="123")
echo "Login Successful ";
else
echo "Login Fail";
?>

Q. Differentiate between GET and POST.


Ans:
Sr.No GET POST
1 GET transfers the information POST transfers the information through
through http head location & displays document body.
the data on URL address.
2 GET is unsecured. POST is highly secured.
3 GET transfers limited amount of POST transfers huge amount of
data. data.
4 GET can't upload the file. POST can upload the files.
5 The GET method is restricted to send The POST method does not have
upto 1024 characters only. any restriction on data size to be
sent.

Notes By- G. R. Jagtap


6
6 GET can't be used to send binary The POST method can be used to send
data, like images or word documents, ASCII as well as binary data
to the server.

4.2 Form controls: textbox, text area, radio button, check box, list, and buttons.
a. Textbox / Text field
HTML Code
<html>
<body>
<h3>Form</h3>
<form method = "post" action = "add.php">
Enter Number1:<input type = "text" name = "num1"> <br>
Enter Number2: <input type = "text" name = "num2"> <br>
<input type = "submit" name = "submit" value = "Addition">
</form>
</body>
</html>

PHP Script
<?php
$num1 = $_POST['num1'];
$num2 = $_POST["num2"];
echo "Addition is ".($num1+$num2);
?>

Notes By- G. R. Jagtap


7
b. Text area
HTML Code
<html>
<body>
<form method = "post" action = "add.php">
Enter Address:<textarea name="addr" rows="5" cols="30"></textarea><br>
<input type = "submit" name = "submit" value = "Submit">
</form>
</body>
</html>

PHP Script
<?php
$addr = $_POST['addr'];
echo "Address is ".$addr;

Notes By- G. R. Jagtap


8
?>

c. Radio button
HTML Code
<html>
<body>
<form method = "post" action = "add.php">
Select Color:<input type="radio" name="color" value="Red">RED</br>
<input type="radio" name="color" value="Pink">PINK</br>
<input type="radio" name="color" value="Green">GREEN</br><br>
<input type = "submit" name = "submit" value = "Submit">
</form>
</body>
</html>

PHP Script
<?php
$c = $_POST['color'];
echo "Selected Color is ".$c;

Notes By- G. R. Jagtap


9
?>

d. Check box
HTML Code
<html>
<body>
<form method = "post" action = "add.php">
Select Color:<input type="checkbox" name="c1" value="Red">RED
<input type="checkbox" name="c2" value="Pink">PINK
<input type="checkbox" name="c3" value="Green">GREEN</br>
<br>
<input type = "submit" name = "submit" value = "Submit">
</form>
</body>
</html>

PHP Script
<?php
$c1 = $_POST['c1'];
$c2 = $_POST['c2'];

Notes By- G. R. Jagtap


10
$c3 = $_POST['c3'];
echo "Selected Color is ".$c1." ".$c2." ".$c3;
?>

e. List box
HTML Code
<html>
<body>
<form method="get" action="list.php">
Programming Languages Known: <br>
<select name="lang">
<option value="C">C</option>
<option value="C++">C++</option>
<option value="Java">Java</option>
<option value="PHP">PHP</option>
<option value="Python">Python</option>
</select><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Notes By- G. R. Jagtap


11
PHP Script
<?php
if(isset($_GET['lang']))
echo "Language Selected is- ".$_GET['lang'];
else
echo "No languages selected";
?>

f. Buttons
HTML Code
<html>
<body>
<form method="get" action="btn.php">
<input type="submit" name="btnSubmit" value="Save">
<input type="submit" name="btnDisc" value="Discard">
</form>
</body>
</html>

Notes By- G. R. Jagtap


12
PHP Script
<?php
if(isset($_GET['btnSubmit']))
echo "Save Button is clicked";
else
echo "Discard Button is clicked";
?>

4.3 Working with multiple forms


HTML Code
<html>
<head>
<title>Multiple Forms</title>
</head>
<body>
<form name="frm1" method="post" action="Ass1.php">
Enter Name:<input type="text" name="uname">
<input type="submit" name="button1" value="Save Name">
</form>
<form name="frm2" method="post" action="Ass2.php">
Enter Mobile Number:<input type="text" name="umob">

Notes By- G. R. Jagtap


13
<input type="submit" name="button2" value="Save Number">
</form>
</body>
</html>

PHP Script
Ass1.php
<?php
if(!empty($_POST['button1']))
echo "Name is - ".$_POST['uname'];
?>
Output when “Save Name” button is clicked.

Notes By- G. R. Jagtap


14
Ass2.php
<?php
if(!empty($_POST['button2']))
echo "Mobile Number - ".$_POST['umob'];
?>
Output when “Save Number” button is clicked.

Q. Design a form to perform addition and subtraction operation on two numbers.


Ans:
HTML Code
<html>
<body>
<form name="frm1" method="post" action="Arith.php">
Enter Number1:<input type="text" name="num1">
Enter Number2:<input type="text" name="num2">
<input type="submit" name="button1" value="Add">
<input type="submit" name="button2" value="Subtract">
</form>
</body>
</html>

Notes By- G. R. Jagtap


15
PHP Script
<?php
if(!empty($_POST['button1']))
echo "Addition is - ".($_POST['num1']+$_POST['num2']);
else
echo "Subtraction is - ".($_POST['num1']-$_POST['num2']);
?>

Q. Explain self-processing form: PHP_Self.


Ans:
• PHP_SELF is a variable that returns the current script being executed.
• This variable returns the name and path of the current file.
• $_SERVER[“PHP_SELF”] sends the submitted form data to the page itself.
• Syntax:

Notes By- G. R. Jagtap


16
<form method=”post” action=”<?php echo $_SERVER[“PHP_SELF”];?>”>
• Code
<html>
<body>
<form method="post" action="<?php echo $_SERVER[“PHP_SELF”];?>">
Enter Name:<input type="text" name="name">
<input type="submit" name="submit" value="Submit">
</form>
<?php
if(isset($_POST['submit']))
{
echo "Hello ".$_POST['name'];
}
?>
</body>
</html>

4.4 Web page validation


Q. Explain web page validation with suitable example.
Ans:
Validation means check the input submitted by the user.
There are two types of validation.
1. Client side validation: validation is performed on the client machine web browser. It is done using
java script.
2. Server side validation: after submitted data by the user, the data is sent to server and validation
checks are performed at server machine. It is done using PHP.
Example:
HTML Code

Notes By- G. R. Jagtap


17
<html>
<body>
<h3>Registration Form</h3>
<p>* - required field.</p>
<form method = "post" action = "formvalidate.php">
Name:<input type = "text" name = "name">*<br>
E-mail: <input type = "text" name = "email">*<br>
Contact Number:<input type = "text" name = "cnum"><br>
<input type = "submit" name = "submit" value = "Submit">
</form>
</body>
</html>

Notes By- G. R. Jagtap


18
PHP Script
<?php
// define variables and set to empty values
$nameErr = $emailErr = "";
$name1 = $_POST["name"];
$email1 = $_POST["email"];
$cnum1 = $_POST["cnum"];

if (empty($name1)) {
$nameErr = "Name is required";
}
if (empty($email1)) {
$emailErr = "Email is required";
}
echo $nameErr." ".$emailErr;
echo "<h4>Your given values are as:</h4>";
echo "Name is -".$name1;
echo "<br>";
echo "Email is -".$email1;
echo "<br>";
echo "Contact number is -".$cnum1;
echo "<br>";
?>

Notes By- G. R. Jagtap


19
4.5 Cookies: use of cookies, attributes of cookies, create cookies, modify cookies, delete cookies
- Cookies are the small text files which are used to store the session data.
- This data of user is used to track the different operations performed by the user.
- PHP provided setcookie() function to set a cookie. This function requires upto six arguments and
should be called before <html> tag. For each cookie this function has to be called separately.
- Syntax:
setcookie(name, value, expire, path, domain, security);
Here is the detail of all the arguments −
• Name − This sets the name of the cookie and is stored in an environment variable called
HTTP_COOKIE_VARS. This variable is used while accessing cookies.
• Value − This sets the value of the named variable and is the content that you actually want to
store.
• Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After
this time cookie will become inaccessible. If this parameter is not set then cookie will
automatically expire when the Web Browser is closed.
• Path − This specifies the directories for which the cookie is valid. A single forward slash
character permits the cookie to be valid for all directories.
• Domain − This can be used to specify the domain name in very large domains and must
contain at least two periods to be valid. All cookies are only valid for the host and domain
which created them.
• Security − This can be set to 1 to specify that the cookie should only be sent by secure
transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.
- Example to create cookie:
<?php
$cookie_name = "user";
$cookie_value = "Ram";
setcookie($cookie_name, $cookie_value, time() + 3000, "/");
?>

<html>
<body>
<?php
echo "Cookie name- " . $cookie_name."<br>";
echo "Value is: " . $_COOKIE[$cookie_name];

Notes By- G. R. Jagtap


20
?>
</body>
</html>

- Example to Check whether cookie is set or not


isset() function is used to check whether cookie is set or not.
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . "<br />";
else
echo "Sorry... Not recognized" . "<br />";
?>
</body>
</html>

- Example to delete cookie:


<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>

Notes By- G. R. Jagtap


21
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>

4.6 Sessions: use of session, start session, get session variables, destroy sessions
- An alternative way to make data accessible across the various pages of an entire website is to use
a PHP Session.
- A session creates a file in a temporary directory on the server where registered session variables
and their values are stored. This data will be available to all pages on the site during that visit.
- The location of the temporary file is determined by a setting in the php.ini file
called session.save_path. Before using any session variable make sure you have setup this path.
- When a PHP script wants to retrieve the value from a session variable, PHP automatically gets
the unique session identifier string from the PHPSESSID cookie and then looks in its temporary
directory for the file bearing that name and a validation can be done by comparing both values.
- A session ends when the user loses the browser or after leaving the site, the server will terminate
the session after a predetermined period of time, commonly 30 minutes duration.
- Starting a PHP Session
- A PHP session is easily started by making a call to the session_start() function.This function first
checks if a session is already started and if none is started then it starts one. It is recommended to
put the call to session_start() at the beginning of the page.
- Session variables are stored in associative array called $_SESSION[]. These variables can be
accessed during lifetime of a session.
- The following example starts a session then register a variable called counter that is incremented
each time the page is visited during the session.
- Make use of isset() function to check if session variable is already set or not.
- Example:
<?php
session_start();
if( isset( $_SESSION['counter'] ) )
{

Notes By- G. R. Jagtap


22
$_SESSION['counter'] += 1;
}
else
{
$_SESSION['counter'] = 1;
}
$msg = "You have visited this page ". $_SESSION['counter'];
$msg .= " in this session.";
?>
<html>
<head>
<title>Setting up a PHP session</title>
</head>
<body>
<?php echo ( $msg ); ?>
</body>
</html>

- Destroying a PHP Session


- A PHP session can be destroyed by session_destroy() function.
- This function does not need any argument and a single call can destroy all the session variables.
- If you want to destroy a single session variable then you can use unset() function to unset a
session variable.
Notes By- G. R. Jagtap
23
- Here is the example to unset a single variable −
<?php
unset($_SESSION['counter']);
?>
OR
<?php
session_destroy();
?>
Examples
1)
<?php
// Start the session
session_start();
?>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>

2)
<?php
session_start();
?>

Notes By- G. R. Jagtap


24
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>

3) Modify session variable


<?php
session_start();
?>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body>
</html>

Notes By- G. R. Jagtap


25
4) Destroy a session
<?php
session_start();
?>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>

4.7 Sending E-mail


The mail() function allows in sending emails directly from a script.
Syntax:
mail(to,sub,msg,headers,parameters);
Parameters
• to − The receiver / receivers of the email
• sub − The subject of the email.
• msg − The message to be sent.
• headers − The additional headers, such as From, Cc, and Bcc.
• parameters − The additional parameter to the sendmail program. This was added in PHP
4.0.5.
Return
The mail() function returns the hash value of the address parameter, or FALSE on failure.
Example
The following is an example to send an email −
<?php
$msg = "This is demo text!";
mail("demo@gmail.com","Mail verification",$msg);
?>

Notes By- G. R. Jagtap


26

You might also like