0% found this document useful (0 votes)
64 views19 pages

Unit-4 Forms Handling, Sessions, Cookies

Uploaded by

carpluswebsite
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)
64 views19 pages

Unit-4 Forms Handling, Sessions, Cookies

Uploaded by

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

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.

Prepared By: Prof. Amit Rathod Page No.3


Required Specifies that a Textarea is required/must be filled
out.
Rows Specifies the visible number of lines in a textarea.
 Example:
<textarea cols="25" rows="5" maxlength="5O" placeholder="Please Enter
Comment...">
</textarea>

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

Submitting & Retrieving Form values/data, using $_GET and $_POST


method
 There are two ways the browser client can send information to the web
server.
1) The GET Method
2) The POST Method
 Both GET and POST create an array (e.g. array (key=>value, key2=>value2,
key3=>value3, ...)).
 This array holds key/value pairs, where keys are the names of the form controls
and values are the input data from the user.
 Both GET and POST are treated as $_GET and $_POST. These are superglobals,
which means that they are always accessible, regardless of scope-and you can
access them from any function, class or file without having to do anything special.
 $_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.
1) The GET Method
 Information sent from a form with the GET method is visible to
everyone (all variable names and values are displayed in the URL).
 GET also has limits on the amount of information to send. The
limitation is about 2000 characters.
 However, because the variables are displayed in the URL, it is possible to
bookmark the page. This can be useful in some cases.
 GET may be used for sending non-sensitive data.
 GET can't be used to send binary data, like images or word documents,
to the server.
 It is not secure but fast and quick.
 When you are using GET method in the form collection element the
information will be send to the destination file through URL using the
concept of QueryString.
 Collection of names and value pairs is called Querystring. Name and
value separated by ampersand(&) sign.
name1=value1&name2=value2&name3=value3
 Every Querystring starts within URL.
 Data is limited to maxlength of querystring.
Prepared By: Prof. Amit Rathod Page No.7
Note: GET should NEVER be used for sending passwords or other sensitive
information!
 Submitting and accessing form value using GET OR Passing variable
through URL:
 Example
<html>
<body>
<form action="welcome_get.php" method="get">
Name:<input type ="text"name="name"><br>
E-mail:<input type="text"name="email"><br>
<input type="submit">
</form>
</body>
</html>
welcome_get.php
<html>
<body>
<?php
$name=$_GET['name'];
$email=$_GET['email']I;
echo"welcome".$name."<br>";
echo"Your email address is:".$email;
?>
</body>
</html>
 Output:
Welcome Peter
Your email address is: [email protected]
2) The POST Method
 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}.
 POST has no limits on the amount of information to send.
 However, because the variables are not displayed in the URL, it is not
possible to bookmark the page.
 The POST method can be used to send ASCII as well as binary data.
 POST may be used for sending sensitive data.
 It is more secured but slower as compared to GET.
 It can post unlimited form variables.
 Submitting and accessing form value using POST.
 Example:
<html>
Prepared By: Prof. Amit Rathod Page No.8
<body>
<form action="welcome.php" method=''post">
Name:<input type="text" name="name"><br>
E-mail:<input type="text" name="email"><br>
<inputtype="submit">
</form>
</body>
</html>
 When the user fills out the form above and clicks the submit button, the
form data is sent for processing to a PHP file named "welcome.php".
 The form data is sent with the HTTP POST method.
 To display the submitted data you could simply echo all the variables.
The"welcome.php"lookslikethis:
welcome.php
<html>
<body>
<?php
$name=$_POST['name'];
$email=$_POST['email'];
echo"welcome".$name."<br>";
echo"Youremailaddressis:".$email;
?>
</body>
</html>
 Output:
Welcome Peter
Your email address is: [email protected]

The $_REQUEST variable:


 The PHP $_REQUEST variable contains the contents of both $_GET,
$_POST, and $_COOKIE. We will discuss $_COOKIE variable when we will
explain about cookies.
 The PHP$_REQUEST variable can be used to get the result from form
data sent with both the GET and POST methods.
 Example:
<html>
<body>
<form action="Process Request.php" method="POST">
Name:<inputtype="text" name="name"/>
Age:<inputtype="text"name= "age"/>
<inputtype="submit"/>
</form>
Prepared By: Prof. Amit Rathod Page No.9
</body>
</html>
 ProcessRequest.php
<?php
echo"Welcome".$_REQUEST['name']."<br/>";
echo"Youare".$_REQUEST['age']."yearsold.";
?>
 Output:
Welcome Peter
You are 31 years old.

Difference between GET and POST

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

Prepared By: Prof. Amit Rathod Page No.10


Form Validation using PHP:

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

7) Button Click Validation


<?php
if(isset($_POST[‘submit’]))
{
echo “Submit button is clicked.”;
if($_SERVER[“REQUEST_METHOD”]==“POST”)
Prepared By: Prof. Amit Rathod Page No.13
{
echo “Data is sent using POST method”;
}
}
else
{
echo “Data is not submitted”;
}
?>

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.

Prepared By: Prof. Amit Rathod Page No.14


 Syntax:
session_start();
o PHP provides a function called session_start(). This function creates a new
session and subsequently indentifies and establishes an existing one.
o session_start() function creates a session or resumes the current one based
on the current session Identifier that is being passed via a request such as
$_GET,$_POST or a cookie.
 Note: POST vs SESSION
o We can get values across pages with $_SESSION and with $_POST and
$_GET only in second page.
o So lifeline of $_SESSION variables are more.
 Storing and accessing session:
 Before we store information in a session, we have to start PHP’s session
handling using session_start() method then we write any session.
 Syntax:
$_SESSION[‘<variable>’]=<$value>;
 Example:
$_SESSION[‘count’]=1;
 Syntax for accessing session:
 variable_name=$_SESSION[‘<variable>’];
 Example:
 $cnt=$_SESSION[‘count’];
 Data and destroying session:
 To destroy or delete the sessions we can use these two commands.
 It is advisable to use this commands in this sequence to destroy remove
sessions in PHP.
 session_unset()
o session_unset just clears out the session for usage.
o The session is still on the user’s computer.
o Note that by using session_unset, the variable still exists.
o session_unset just remove all session variables.
 session_destroy()
o session_destroy() destroys all of the data associated with the current
session.
 Example:
<?php
session_start();
$_SESSION['name']='Kevin Shah';
if(!isset($_SESSION['name']))
{
$_SESSION['name']='Kevin Shah';
echo "The name ".$_SESSION['name']." is added in session";
Prepared By: Prof. Amit Rathod Page No.15
}
else
{
echo "The name is ".$_SESSION['name'];
}
session_unset();
session_destroy();
?>
 Output:
The name is Kevin Shah

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.

Prepared By: Prof. Amit Rathod Page No.16


 in the below example, we retrieve the value of the cookie name “username”
and display it on a page.

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

Difference between Cookie and Session

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.

Prepared By: Prof. Amit Rathod Page No.18


Prepared By: Prof. Amit Rathod Page No.19

You might also like