Unit-4 Forms Handling, Sessions, Cookies
Unit-4 Forms Handling, Sessions, Cookies
Form:
The <form> tag is used to create an HTML form for user input.
HTML forms are used to collect user input.
Form can contain input element like text fields, checkboxes, radio button, submit
button and more.
Forms are used to pass data to a server.
Syntax:
<form>….</form>
Attributes of form:
Action:
The action attributes specifies where to send the form-data when a form is
submitted.
Syntax:
<form action=“URL”>
o Possible values for URL:
An absolute URL: Points to another web site (like
action=http://www.example.com/example.html)
A relative URL: Points to a file within a web site (like
action="example.php")
Enctype:
The enctype attribute specifies how the form-data should be encoded when
submitting it to the server.
Syntax:<formenctype="vallue">
Note: The enctype attribute can be used only if method="post".
Method:
The method attribute specifies how to send form-data (the form-data is
sent to the page specified in the action attribute).
Syntax:
<form method="get/post">
Value Description
Default. Appends the form data to the URL in name/
Get value pairs:
Post Sends the form-data as an HTTP post transaction.
URL?name=value&name=value
Name:
The name attribute specifies the name of a form.
The name attribute is used to reference elements in a JavaScript, or to
reference form data after a form is submitted.
Syntax:
<form name="text">
o text- Specifies the name of the form
Target:
The target attribute specifies a name or a keyword that indicates where to
display the response that is received after submitting the form.
Syntax:
<form target="_blank |_self |_parent |_top |framename">
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.
Form Controls:
Input Element:
Input elements are used to get input from the user in various formats.
Its properties are specified in the TYPE attribute of the HTML element
<INPUT></INPUT>.
<INPUT> element’s properties:
Type Type of INPUT entry field
Name Variable name passed to application
Value The data associated with the variable name to be
passed to the application.
Checked Button/box checked by default
Size Number of characters in text field.
Maxlength Maximum number of characters accepted.
TextBox
<input type="text"> defines a one-line input field for text input.
Attributes of textbox:
Attribute Description
Name Assigns a name to the given field so that you may
reference it later.
Maxlength Specifies the maximum number of character for an
input field.
Readonly Specifies that an input field is read only (can not be
Prepared By: Prof. Amit Rathod Page No.2
changed).
Required Specifies that an input field is required (must be
filled out).
Size Specifies the width (in characters) of an input field.
Value Specifies the default value for an input field.
Example:
<input type="text" name="username" size="25" maxlength="1O">
Password
<input type="password">defines a password field.
Attributes of password:
Attribute Description
Name Assigns a name to the given field so that you may
reference it later.
Maxlength Specifies the maximum number of character for an
input field.
Required Specifies that an input field is required(must be filled
out).
Size Specifies the width (in characters)of an input field.
Value Specifies the default value for an input field.
Example:
<input type="password" name="pass" size="25" maxlength="1O">
TextArea
The <textarea>tag defines a multi-line text input control.
A Textarea can hold an unlimited number of characters.
Attributes of textarea:
Attribute Description
Name Specifies a name for a textarea.
Cols Specifies the visible width of a textarea.
Maxlength Specifies the maximum number of characters allowed
in the textarea.
Placeholder Specifies a short hint that describes the expected value of
a textarea.
Readonly Specifies that a text area should be read-only.
RadioButtton
<input type="radio"> defines a radio button.
Radio buttons let a user select ONE of a limited number of choices.
Attributes of radio button:
Attribute Description
name Assigns a name to the given field so that you may
reference it later.
value Specifies the default value for an input field.
Specifies whether a radio button should be checked or
checked not.
o True - The radio button is checked
o False - Default. The radio button is not checked
Example:
<input type="radio" name="gender" value="male" checked>Male
<input type="radio" name="gender" value="female">Female
Checkbox
<input type="checkbox"> defines a checkbox.
Checkboxes allow for multiple items to be selected for a certain group of
choices.
Attributes of checkbox:
Attribute Description
Name Assigns a name to the given field so that you may
reference it later.
Value Specifies the default value for an input field.
Specifies whether a checkbox should be checked or not.
Checked o True -The checkbox is checked
o False - Default. The checkbox is not checked
Example:
<input type="checkbox" name="language" value="java" checked>Java
Prepared By: Prof. Amit Rathod Page No.4
<input type="checkbox" name="language" value=".net">.Net
<input type="checkbox" name="language" value=''c++" checked>C++
DropdownList
Dropdown list is used to select one option from given list of choice.
The <select> element is used to create a drop-down list.
The <option> tags inside the <select> element define the available options
in the list.
Attributes of dropdown list:
Attribute Description
Name Defines a name for the drop-down list.
Specifies that the user is required to select a value
Required before submitting the form.
Value Specifies the value for selected element.
When present, it specifies that an option should be
Selected
pre-selected when the page loads.
Example:
<select name="language">
<option> Gujarati </option>
<option selected> English </option>
<option> Hindi </option>
</select>
ListBox
ListBox is used to select single or multiple option from given list of choice.
The <select> element is used to create a listbox.
The <option> tags inside the <select> element define the available options
in the list.
Attributes of listbox:
Attribute Description
Name Defines a name for the listbox.
Required Specifies that the user is required to select a value
before submitting the form.
Value Specifies the value for selected element
When present, it specifies that an option should be pre-
Selected selected when the page loads.
Multiple Specifies that multiple options can be selected at once
Size Defines the number of visible options in a listbox.
Example:
Prepared By: Prof. Amit Rathod Page No.5
<select name="language" size="3" multiple>
<option> Gujarati </option>
<option selected> English </option>
<option> Hindi </option>
<option> Telugu </option>
</select>
Hidden
<input type="hidden"> defines a hidden fields.
Define a hidden field (not visible to a user).
A hidden field often stores a default value, or can have its value changed by
a JavaScript.
Attributes of hidden fields:
Property Description
Name Sets or returns the value of the name attribute of the
hidden input field.
Value Sets or returns the value of the value attribute of
the hidden input field.
Example:
<input type="hidden" name="country" value="India">
Button
<input type="button">defines a button.
Clickable button, that carried some action when it is clicked.
Attributes of button:
Property Description
Name Assigns a name to the given field so that you may
reference it later.
Value Determines the text label on the button.
Example:
<input type="button" name="submit" value="Clickme">
ResetButton
<input type="reset"> defines a reset button.
Resets all form values to default values.
<input type="reset">
SubmitButton
<input type="submit"> defines a button for submitting a form to a form-
handler.
Prepared By: Prof. Amit Rathod Page No.6
The form-handler is typically a server page with a script for processing
input data.
The form-handler is specified in the form's action attribute.
<input type="submit" value="Save">
GET POST
Bookmarked Can be bookmarked Can not be bookmarked
Cached Can be cached Not cached
History Parameters remain in Parameters are not saved
browser history in browser history
Restrictions Yes, when sending data, the No restrictions
on data GET method adds the data to
length the URL; and the length of a
URL is limited (maximum
URL length is 2048
characters)
Restrictions Only ASCII characters allowed No restriction. Binary data
on data type is Also allowed
Security GET is less secure compared POST is a little safer than
to POST because data sent is GET because the
part of the URL Never use GET parameters are Not
when sending passwords or stored in browser history
other sensitive information! or in web server logs
Visibility Data is visible to everyone Data is not displayed in the
in the URL URL
An HTML form contains various input fields such as textbox, checkbox, radio
buttons, submit button, and checklist, etc.
These input fields need to be validated, which ensures that the user has entered
information in all the required fields and also validates that the information
provided by the user is valid and correct.
There is no guarantee that the information provided by the user is always
correct.
PHP validates the data at the server-side, which is submitted by HTML foram.
You need to validate few things.
1) Empty String
2) Validate String
3) Validate Numbers
4) Validate Email
5) Validate URL
6) Input length
1) Empty String
It checks that the field is not empty.
If the user leaves the required field empty, it will show an error message.
Example:
<?php
if(empty($_POST[“txtname”]))
{
$errormsg=“Error! Please , Enter the Name :”;
echo $errormsg;
}
else
{
$name=$_POST[“txtname”];
}
?>
2) Validate String
It will checks that the field will contain only alphabets and whitespace.
ex. Name
Example:
<?php
$name=$_POST[“txtname”];
if(!preg_match(“/^[a-zA-z]*$/”,$name))
Prepared By: Prof. Amit Rathod Page No.11
{
$errormsg=“Error! Only alphabets and whitespace are allowed. :”;
echo $errormsg;
}
else
{
echo $name;
}
3) Validate Numbers
It validates that the field will only contain a numeric value.
ex. Mobile no.
Example:
<?php
$mobileno=$_POST[“txtmobileno”];
if(!preg_match(“/^[0-9]*$/”,$mobileno))
{
$errormsg=“Error! Only Numeric Value is allowed.”;
echo $errormsg;
}
else
{
echo $mobileno;
}
?>
4) Validate Email
A valid email must contain @ and . symbols.
PHP provides various method to validate the email address.
Example:
<?php
$email=$_POST[“txtemail”];
$pattern=”^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-
]+)*(\.[a-z]{2,3})$^”;
if(!preg_match ($pattern, $email) )
{
echo “Email is Not valid.”;
}
else
{
echo “Your valid email address is:”.$email;
}
Prepared By: Prof. Amit Rathod Page No.12
?>
5) Validate URL
It validates the URL of website provided by the user via HTML form.
If the field does not contain a valid URL, the code will display an error
message.
Example:
<?php
$websiteURL = $_POST[“txtwebsite”];
if(!preg_match(“/\b(?:(?:https?|ftp):\/\/www\.)[-a-z0-
9+&@#\/%?=~_|!:,.;]*[-a-z0-9+@@#\/%=~_|]/i”,$website))
{
echo “URL is not Valid..”;
}
else
{
echo “Website URL is: “.$websiteURL;
}
6) Input length
The input length validation restricts the user to provide the value
between the specified ranges.
Example:
<?php
$mobileno=strlen($_POST[“txtmobileno”]);
$length=strlen($mobileno);
if($length<10 && $length>10)
{
$errormsg=“Error! Mobile must have 10 digits..”;
echo $errormsg;
}
else
{
echo “Your mobile number is:”.$mobileno;
}
?>
Session
A session is a way to store information (in the form of variables) to be used
across multiple pages.
A session is the time for which particular user interacts with a web
application.
This is one of the secured ways the variables are passed between pages.
Every client that uses the application will have separate sessions.
During a session the unique identity of the user is maintained internally.
A session ends if there is a session timeout or if you end the visitor session in
code.
Session state is ideal for storing user specific information.
If different users are using your application, each user session will have a
different session state.
In addition, if a user leaves your application and then returns later, the second
user session will have a different session state from the first.
One of the weaknesses of cookies is that the cookie is stored on the user’s
(clients) computer. While the session data is stored on the server.
This provides others the ability to access, view and modify that cookie for misuse.
On the other hand, sessions store only an ID cookie on the user’s system which is
used to reference the session file on the server.
Session also work in disabled cookies browser.
do not store large quantities of information in session state.
Like Querystring we can use session to store value and pass it to another page,
unlike Querystring, session will not display on the end of the URL.
Sessions work by creating a unique identification (UID) number for each visitor
and storing variables based on PHPSESSID.
Creating session:
To creating or starting session we must use the function session_start() before
we send any output to the browser and before we use any session variables.
It’s best to place session_start() at the beginning of your script.
Cookies
A Cookie is small text file that lets you store a small amount of data on the user’s
computer.
They are typically used to keeping track of information such as username that the
site can retrieve to personalize the page when user visit the website next time.
Each time the browser requests a page to the server, all the data in the cookie is
automatically sent to server within the request.
Setting cookies/Creating Cookie
In PHP you can create cookie using setcookie() function.
Syntax:
setcookie(name, value, expire time, path, domain, secure, httponly)
o Name: Specify name of cookie that you want to create.
o Value: Value that is associated with the cookie created by you.
o Expire time: Expire time is time when cookie will expire and deleted. It is
an optional.
o Path: This specifies the directories for which the cookie is valid.
o Domain: The domain represents the Internet domain from which cookie-
based communication is allowed.
o Secure: 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.
Note: setcookie() function must appear BEFORE the <html> tag.
Example:
<?php
setcookie(‘cookiename’,’cookievalue’, time()+60*60*24*5);
echo “Cookie is set”;
?>
Accessing cookies data /Retrieving Cookie:
The $_COOKIE variable is used to retrieve a cookie value.
Example:
<?php
$cookiename=$_COOKE[‘cookiename’];
echo “Cookie Name: “.$cookiename;
?>
In the below example we use the isset() function to find out if a cookie has
been set.
<?php
if(isset($_COOKIE[‘cookiename’]))
{
echo “Cookie”.$_COOKIE[‘cookiename’]. “is not set!”;
}
else
{
echo “Cookie”.$_COOKIE[‘cookiename’]. “is set!”;
}
?>
Destroying cookies/Removing Cookie:
When deleting a cookie you should assure that the expiration date is in the
past.
Cookie Session
Cookies are Client-side files that contain
Session are server-side files that contain
user information. user information.
In PHP $_COOKIE super global variable In PHP $_SESSION super global variable is
is used to manage cookie. used to manage session.
You do not need to start Cookie as it is Before using $_SESSION, you have to
stored in your local machine. write session_start();. in that way session
will start and you can access $_SESSION
variable on that page.
Cookie can have a long lifespan, lasting Sessions have a limited lifespan; they
months or even years. expire when the browser is closed.
Cookies are limited in size depending on Sessions are only limited in size if you
each browser's default settings. limit their size on the server.
Cookies can be disabled if the visitor's Sessions cannot be disabled by the visitor
browser does not allow them. because they are not stored in the
Prepared By: Prof. Amit Rathod Page No.17
browser.
Cookies can be edited by the visitor. (Do
Sessions cannot be edited by the visitor.
not use cookies to store sensitive data.)
Cookie ends depends on the lifetime you Session ends when user closes his
set for it. browser.