0% found this document useful (0 votes)
64 views

Chapter 4 Creating and Validating Forms

The document discusses various form controls and validation techniques in web development including GET and POST methods, form controls like text boxes, radio buttons, checkboxes, lists and hidden fields. It also covers working with multiple forms and submit buttons, and client-side versus server-side validation.

Uploaded by

small.things1212
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views

Chapter 4 Creating and Validating Forms

The document discusses various form controls and validation techniques in web development including GET and POST methods, form controls like text boxes, radio buttons, checkboxes, lists and hidden fields. It also covers working with multiple forms and submit buttons, and client-side versus server-side validation.

Uploaded by

small.things1212
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Chapter 4:

Creating and Validating Forms


GET and POST Methods
GET Request POST Request
Parameters remain in browser history Parameters are not saved in browser
because they are part of the URL history
GET is Less Secure compared to POST POST is a little safer than GET
This request can be cached. This request are never cached.
This request can be bookmarked. This request can not be bookmarked.
GET method should not be used when POST method used when sending
sending passwords or other sensitive passwords or other sensitive information.
information.
Only limited amount of information is send Large amount of information is send using
using GET request. (2048 characters ) POST request.
It is more efficient It is less efficient
$_GET is an array of variables passed to the current
script via the URL parameters.
$_POST is an array of variables passed to the current
script via the HTTP POST method.
Example
<form action="/action_page.php" method="get">
or:
Example
<form action="/action_page.php" method="post">
Server Role
The responsibility of web server can be
illustrated by enlisting following functionalities.
●The primary responsibility of web server is to

respond to the requests made by the web clients.


●It is responsible to HTTP connections.

●Web server manages permissions and access for

certain resources.
●It is responsible for encrypting and compressing

data.
● Web server manages multiple domains and URLs.

● It is handles database connection, cookies, state

and uploading of files.


Form Controls
• The HTML form is defined using the <form> element.
• HTML allows us to place these form components(text, text area,
checkbox and so on) on the web page and send the desired
information to the destination.
• The form has an attribute action which gets executed when user
clicks a button on the form.
• Various attribute of form are-

Attribute Description
action It specifies the URL where the form should be submitted
method It specifies the HTTP methods such as GET,POST
name This attribute denotes the name of the form.
target It specifies the target of the address in the action attribute
The target attribute specifies a name or a keyword that indicates
where to display the response that is received after submitting the
form.
The target attribute defines a name of, or keyword for, a browsing
context (e.g. tab, window, or inline frame).
Value Description

_blank The response is displayed in a new window or tab

_self The response is displayed in the same frame (this is


default)
_parent The response is displayed in the parent frame

_top The response is displayed in the full body of the window

framename The response is displayed in a named iframe


Text Box :
• Text is typically required to place one line text.
• The text field can be set using

<input type=“text” size=“30” name=“username” value=“ “>

• Some other parameters or attributes can be


▪ maxlength – that allows us to enter the text of some maximum
length.
▪ name - indicates name of the text field.
▪ align – denotes the alignment of the text in the text field. The
alignment can be left, right, bottom and top.
Example :
• Create a form in some HTML file as follows-
• Input.html
<form action="hello.php" method="post">
Name:<input type ="text" name="user"/>
<input type ="submit" value="submit"/>
</form>

• Now the hello.php program can be as follws-


<?php
$name=$_POST["user"];
echo "Hello";
echo "\n",$name;
?>
Text Area :
• Text area is used for multiple line text.
• Syntax:

<textarea name=name_of_component rows=“no_of_rows”


cols=“no_of_cols”> </textarea>
Example:
• Input.html
<form action="hello.php" method=“get">
Enter your feedback<br/>
<textarea name=“feedback” rows=“5” cols=“50”></textarea>
<br/>
<input type ="submit" value="submit"/>
</form>

• Now the hello.php program can be as follws-


<?php
$data=$_GET[“feedback"];
echo “your feedback is<br>“,$data;
?>
Radio Button:
• This component is also use to indicate the selection from several
choices.
• Using input type=“radio” we can place radio button on the web
page.
• Syntax:
<input type=“radio” name=“name” value=“value”>
• This component allows us to make only one selection at a time.
Example :
• Create a form in some HTML file as follows- Input.html
<form action="info.php" method="get">
Please Select Your Fevorite Fruit:</br>
<input type="radio" name="Fruit" value="Mango">Mango<br/>
<input type="radio" name="Fruit" value="Banana">Banana<br/>
<input type="radio" name="Fruit" value="Grapes">Grapes<br/>

<br/>
<input type="submit" value="Submit"/>
<form>

• Now the info.php program can be as follws-


<?php
$choice=$_GET["Fruit"];
if(($choice!=null))
{
echo("My Fevorite Fruit Is:".$choice);
}
?>
Checkbox :

● The <input type="checkbox"> defines a checkbox.


● The checkbox is shown as a square box that is ticked (checked) when
activated.
● Checkboxes are used to let a user select one or more options of a
limited number of choices.
Example :
<form action="#" method="post">
<h3>Enter your favorite programming language:</h3>
<input type="checkbox" name="check_list[]" value="c/c++">
<label>c/c++</label><br/>
<input type="checkbox" name="check_list[]" value="java">
<label>java</label><br/>
<input type="checkbox" name="check_list[]" value="php">
<label>php </label><br/>
<br/>
<input type="submit" name="submit" value="submit" />
<br/>
</form>

<?php
if(isset($_POST['submit']))
{
echo"<h4> you have selected..</h4>";
if(!empty($_POST['check_list']))
foreach($_POST['check_list'] as $selected)
{
echo "$selected </br>";
}
}
?>
List :
The List box displays all the items at once in a text area

Example :
Create a form in some HTML file as follows- Input.html
<html>
<body>
<div>
<form action="index.php" method="post">
<p><select name="products[]" multiple="multiple">
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
</select></p>
<p><input type="submit" value="hit it!" /></p>
</form>
</div>
</body>
</html>
Now the index.php program can be as follws-

<?php
if (is_array ( $_POST ['products'] )) {
print "<p>Your product choices are:</p>";
foreach ( $_POST ['products'] as $value ) {
print "$value\n";
}
print "</ul>";
}
?>
Combo Box :
The combo box displays only one item at a time
The Combo box is a combination of a text box in which the user
enters an item and a drop-down list from which the user selects an
item.

Example :
Create a form in some HTML file as follows- Input.html

<html>
<body>
<form action="index.php" method="post">
<p><select name="products[]“>
<option>option1</option>
<option>option2</option>
<option>option3</option>
</select>
<p><input type="submit" value="hit it!" /></p>
</body>
</html>
Now the index.php program can be as follws-

<?php
if (is_array ( $_POST ['products'] )) {
print "<p>Your choices is:</p>";
foreach ( $_POST ['products'] as $value ) {
print "$value\n";
}
print "</ul>";
}
?>
Hidden Control

A hidden field lets web developers include data that cannot be seen or modified by
users when a form is submitted.

A hidden field often stores what database record that needs to be updated when the
form is submitted.

Note: While the value is not displayed to the user in the page's content, it is visible (and
can be edited) using any browser's developer tools or "View Source" functionality. Do
not use hidden inputs as a form of security!
Hidden Control
Create a form in some HTML file as follows- Input.html

<html>
<body>
<h1>Define a hidden input field:</h1>
<form action="actionpage.php" method="POSt">
<input type="hidden" name="custId" value="3487">
<input type="submit" value="Submit">
</form>
</body>
</html>

Now the actionpage.php program can be as follws-

<?php
if(isset($_POST["custId"]))
{
echo "Cust ID:".$_POST['custId'];
}
?>
Working with multiple Forms:

<html>
<head>
</head>
<body>
<form name="mailform" method="post" action="ind.php">
<input type="text " name="email" id="email"/>
<input type="submit" name="mail-submit" value="Send Mail"/>
</form>
<form name="mobileform" method="post" action="ind.php">
<input type="text" name="mobileno" id="mobileno"/>
<input type="submit" name="mob-submit" value="Send Contact"/>
</form>
</body>
</html>
<?php
if($_SERVER['REQUEST_METHOD']=="POST")
if(!empty($_POST['mail-submit'])){
echo "Your mail is:".$_POST['email'];
}
else if(!empty($_POST["mob-submit"])){
echo "Your no is:".$_POST['mobileno'];
}
?>
Working with multiple Submit button :
Create a form in some HTML file as follows- Input.html
<html>
<head>
</head>
<body>
<form name="mailform" method="post" action="ind.php">
<input type="text " name="no1" id="no1" />
<input type="text" name="no2" id="no2" />
<input type="submit" name="addno" value="Add" />
<input type="submit" name="subno" value="Sub" />
</form>
</body>
</html>
Now the ind.php program can be as follws-

<?php
if($_SERVER['REQUEST_METHOD']=='POST')
{
if(isset($_POST['addno'])){
echo "Addition:".((int)$_POST['no1']+(int)$_POST['no2']);
}
else if(isset($_POST['subno'])){
echo "Subtraction:".((int)$_POST['no1']-(int)$_POST['no2']);
}
}
?>
Web Page Validation :
Validation means check the input submitted by the user.
There are two types of validation are available in PHP:
Client side validation : Validation is performed on the client machine web browsers.
Server side validation : After submitted the data, the data has sent to a server and
perform validation check in server machine.
Some of validation rules for fields :

Sr.No. Field Validation Rules


1 Name Should required latters and white-spaces
2 Email Should required @ and .
3 Website Should required a valid URL
4 Radio Should required selectable at lest once
5 Check Box Should required checkable at lest once
6 Drop Down menu Should required selectable at lest once
Vali.html

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


Name: <input type="text" name="name" id="name" /><br/>
Mobile no. :<input type="text" name="mob" id="mob" /><br/>
Email ID: <input type="text" name="email" id="email" /><br/>
<input type="submit" name="submit" value="Submit" /><br/>
</form>
val.php

<?php
if($_SERVER['REQUEST_METHOD']==='POST')
{
if(!empty($_POST['name']))
{
echo "Name cant be blank<br/>";
}
if(!is_numeric($_POST['mob']))
{
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/>";
}
}
?>
Cookies
• PHP transparently supports HTTP cookies. Cookies are a mechanism for storing data in
remote browser and thus tracking or identifying return users. Cookies are part of the
HTTP header.
• Cookie is created at server side and saved to client browser.
• A cookie is a small file with the maximum size of 4KB that the web server stores on the
client computer.

• You can see Cookies in google chrome by following


Chrome://settings/content/cookies
Create Cookies
• A cookie is created with the setcookie() function.

• Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.

Note: The setcookie() function must appear BEFORE the <html> tag.
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:

cookie.php
<?php
//setcookie(name, value, expire);
setcookie('actor_name', 'joaquin phoenix', time()+30);
setcookie('age', '44', time()+30);
echo "The cookie has been set for 30 seconds";
?>

cookie_view.php
<?php
$actor_name = $_COOKIE['actor_name'];
$actor_age = $_COOKIE['age'];
echo "$actor_name";
echo " $actor_age";
?>
Types of Cookies

There are two types of cookies, they are:


Session Cookie: This type of cookies are temporary and are expire as soon as the
session ends or the browser is closed.
Persistent Cookie: To make a cookie persistent we must provide it with an expiration
time. Then the cookie will only expire after the given expiration time, until then it will be a
valid cookie.
PHP Sessions
• A session is a way to store information (in variables) to be used across multiple pages.
• Unlike a cookie, the information is not stored on the users computer.

What is a PHP Session?


• When you work with an application, you open it, do some changes, and then you close
it. This is much like a Session. The computer knows who you are. It knows when you start
the application and when you end. But on the internet there is one problem: the web
server does not know who you are or what you do, because the HTTP address doesn't
maintain state.
• Session variables solve this problem by storing user information to be used across
multiple pages (e.g. username, favorite color, etc). By default, session variables last until
the user closes the browser.
• So; Session variables hold information about one single user, and are available to all
pages in one application.

Tip: If you need a permanent storage, you may want to store the data in a database.
Start a PHP Session
• A session is started with the session_start() function.
• Session variables are set with the PHP global variable: $_SESSION.
• Now, let's create a new page called "demo_session1.php". In this page, we start a new
PHP session and set some session variables:

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>

</body>
</html>
Get PHP Session Variable Values
• Next, we create another page called "demo_session2.php". From this page, we will
access the session information we set on the first page ("demo_session1.php").
• Notice that session variables are not passed individually to each new page, instead they
are retrieved from the session we open at the beginning of each page (session_start()).
• Also notice that all session variable values are stored in the global $_SESSION variable:
<?php
session_start();
?>
<!DOCTYPE html>
<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>
Modify a PHP Session Variable
• To change a session variable, just overwrite it:

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

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

</body>
</html>
Destroy a PHP Session
• To remove all global session variables and destroy the session,
use session_unset() and session_destroy():

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset();

// destroy the session


session_destroy();
?>

</body>
</html>
Cookies Session

Cookies are client side file that Session are Sever side file that
contain user information contain user information
Cookies are stored in users browser sessions are not

A cookie can keep information in the session is that when you close your
users browser until deleted browser you also lose the session
If you set variables to cookies then If you set variables to session then
your users will not have to login each user activity will be tracked using
time they enter your community browser session and your users will
have to login each time they reopen
the browser
Cookies can only store Strings Store our object in sessions

Save cookie in future reference Session could not. User close their
Email :
The mail() function allows you to send emails directly from a script.

Syntax
mail(to,subject,message,headers,parameters);
Parameter Description

to Required. Specifies the receiver / receivers of the email

subject Required. Specifies the subject of the email. Note: This parameter cannot contain
any newline characters

message Required. Defines the message to be sent. Each line should be separated with a LF
(\n). Lines should not exceed 70 characters.

Windows note: If a full stop is found on the beginning of a line in the message, it
might be removed. To solve this problem, replace the full stop with a double dot:

<?php

$txt = str_replace("\n.", "\n..", $txt);

?>

headers Optional. Specifies additional headers, like From, Cc, and Bcc. The additional
headers should be separated with a CRLF (\r\n).

Note: When sending an email, it must contain a From header. This can be set with
this parameter or in the php.ini file.

parameters Optional. Specifies an additional parameter to the sendmail program (the one
defined in the sendmail_path configuration setting). (i.e. this can be used to set the
<?php
// the message
$msg = "First line of text\nSecond line of text";

// use wordwrap() if lines are longer than 70 characters


$msg = wordwrap($msg,70);

// send email
mail("[email protected]","My subject",$msg);
?>

You might also like