Unit-IV Creating and validating forms
Unit-IV Creating and validating forms
UNIT IV
Syllabus
4.1 Creating a webpage using GUI components, Browser Role-GET and POST methods, Server role.
4.2 Form controls: text box, text area, radio button, check box, list, buttons
4.3 Working with multiple forms: A web page having many forms, A forms having multiple submit buttons.
4.5 Cookies: Use of cookies, attributes of cookies, create cookies, modify cookies value and delete cookies
4.6 Session: use of session, start session, get session variables, destroy session
− To run any code on server or to get connected with the PHP on server we need to set up Web pages in a specific
fashion.
− HTML controls like text fields, check boxes, radio buttons etc. enclosed in HTML form are used to collect data from
user.
− We have to indicate location in the form where the data from the controls will be sent.
− Two methods “get” and “post” mentioned in form are commonly used to send data from HTML controls to PHP script
on server.
− URL is used to specify the location, which helps browser understand where to send the data on server mentioned in
the “action” attribute of a form.
− PHP script handles both displaying of HTML controls and then reading of data from HTML controls when the user
clicks on the Submit button.
− Other than html controls like text fields and check boxes we also need submit button, because only by clicking on
submit button data from the form is sent to the PHP script on the server.
− For example, a simple form with a text field and submit button, text field is used to get name from users and we have
to make the browser know where to send the name data when the user clicks on Submit button.
Web Based Application Development using PHP (MSBTE) 4-2 Creating and Validating Forms
Example :
HTML Form
<html>
<head>
<title> Sample PHP Program </title>
</head>
<body>
<form method=”get” action=php_readdata.php>
<input name=”username” type=”text”>
<input type=”submit” value=”Submit”>
</form
</body>
</html>
Browser used one of the two HTTP (Hypertext Transfer Protocol) methods - GET and POST to communicate with the
server. Both methods GET and POST are used to pass the information differently to the server.
− This is the built in PHP super global array variable that is used to get values submitted via HTTP GET method.
− Data in GET method is sent as URL parameters that are usually strings of name and value pairs separated by
ampersands (&).
http://www.abc.com/dataread.php?name=ram&age=20.
− The name and age in the URL are the GET parameters; ram and 20 are the value of those parameters.
− More than one parameter=value can be embedded in the URL by concatenating with ampersands (&).
− Only simple text data can only be sent through GET method.
− Sensitive information such as the username and password can’t be sent through GET method as it will be visible in
the query string and it can store in browser memory as visited page
Syntax :
<?php
$_GET['variable_name'];
?>
Where “$_GET[…]” is the PHP array and “'variable_name'” is the URL variable name.
Example :
Student.html
<html>
<body>
<form action="student.php" method="get">
Name: <input type="text" name="name">
Address: <input type="text" name="address">
<input type="submit">
</form>
</body>
</html>
Student.php
<html>
<body>
Welcome: <?php echo $_GET["name"]; ?>!
Your address is: <?php echo $_GET["address"]; ?>
</body>
</html>
Output :
When the user clicks on the "Submit button", the URL will be something like this :
Web Based Application Development using PHP (MSBTE) 4-4 Creating and Validating Forms
− Since the data sent by the GET method are displayed in the URL, it is possible to bookmark the page with specific
query string values.
− GET requests can be cached and GET requests remain in the browser history.
− The GET method is not suitable for passing sensitive information such as the username and password, because these
are fully visible in the URL query string as well as potentially stored in the client browser’s memory as a visited page.
− Because the GET method assigns data to a server environment variable, the length of the URL is limited. So, there is a
limitation for the total data to be sent.
− This is the built in PHP super global array variable that is used to get values submitted via HTTP POST method.
− Data in POST method is sent to the server in a form of a package in a separate communication with the processing
script.
− User entered Information is never visible in the URL query string as it is visible in GET.
− The POST method can be used to send the much larger amount of data and text data as well as binary data
(uploading a file).
− Data sent by the POST method is not visible in the URL, so it is not possible to bookmark the page with specific query.
− Super global variable $_POST is used to access all the information sent through an HTML form using the post method.
− A good example of using post method is when submitting login details to the server.
Syntax :
<?php
$_POST['variable_name'];
?>
Where “$_POST[…]” is the PHP array and “'variable_name'” is the URL variable name.
Example :
Student.html
<html>
<body>
<form action="student.php" method="post">
Name: <input type="text" name="name" id="name">
Address: <input type="text" name="address" id="address">
<input type="submit" value="submit">
Web Based Application Development using PHP (MSBTE) 4-5 Creating and Validating Forms
</form>
</body>
</html>
student.php
<html>
<body>
Welcome: <?php echo $_POST["name"]; ?>!
<br>
Your address is: <?php echo $_POST["address"]; ?>
</body>
</html>
Output :
When the user clicks on the "Submit button", the URL will be something like this :
− It is more secure than GET because user-entered information is never visible in the URL query string or in the server
logs.
− There is a much larger limit on the amount of data that can be passed and one can send text data as well as binary
data (uploading a file) using POST.
− Since the data sent by the POST method is not visible in the URL, so it is not possible to bookmark the page with
specific query.
Information sent from a form with the GET method Information sent from a form with the POST method is invisible
is visible to everyone (all variable names and values are to others (all names/values are embedded within the body of
displayed in the URL). the HTTP request)
GET has limits on the amount of information to send. The Post has no limits on the amount of information to send.
limitation is about 2048 characters.
$_GET is an array of variables passed to the current script $_POST is an array of variables passed to the current script via
via the URL parameters. the HTTP POST method.
Parameters remain in browser history Parameters are not saved in browser history
GET is less secure compared to POST because data sent is POST is a little safer than GET because the parameters are not
part of the URL. So it's saved in browser history and server stored in browser history or in web server logs
logs in plaintext.
GET method should not be used when sending passwords POST method used when sending passwords or other sensitive
or other sensitive information. information.
− A client (browser) submits an HTTP request using GET and POST method to the server.
− Server processes the request and returns a result, in the form of a response to the client.
− The response from the server contains status information about the request and requested content.
− Here student.html has a static behavior because it delivers same content always. But student.php has a dynamic
behavior because the content it delivers changes according to the time of the day. You can improve this file and have
different greetings for different time periods.
− When PHP interpreter reads a file, it only processes lines between <?php and ?> tags. It outputs rest of the lines
without any processing.
Web Based Application Development using PHP (MSBTE) 4-7 Creating and Validating Forms
1. Client Request
Fig. 4.1.2
− We always start with a browser making a request for a web page. This request is going to hit the web server. The web
server will then analyze it and determine what to do with it.
− If the web server determines that the request is for a PHP file (often index.php), it will pass that file to the PHP
interpreter. The PHP interpreter will read the PHP file, parse it (and other included files) and then execute it. Once the
PHP interpreter finishes executing the PHP file, it will return an output. The web server will take that output and send
it back as a response to the browser.
For Example
a.html
<html>
<head>
<title> PHP Server </title>
</head>
<body>
<form method="post" action="sample.php">
<label>Mail id:</label>
<input type="text" name="mailid" id=" mailid">
<input type="submit" value="Submit">
</form>
</body>
</html>
Web Based Application Development using PHP (MSBTE) 4-8 Creating and Validating Forms
sample.php
<?php
if(isset($_POST["mailid"])){
echo "<p>Mail id : " . $_POST["mailid"] . "</p>";
}
?>
In above example POST method is used to send data to the server as it is POST method data will be invisible to
everyone and embedded within the body of the HTTP request. On the server side a super global variable $_POST is used by
PHP to create an associative array with an access key ($_POST['name as key']). Data is assessed using key and based on
collected data processing takes place and the result is provided as a response to the client.
When we mix PHP and HTML content in a PHP file, we call it as “embedding PHP in HTML”. We could achieve the
same behavior with following PHP file, which contains only PHP content. Embedding PHP blocks in HTML let us get the help
of PHP only where it is necessary. We can add rest of the lines to the output by just keeping them outside of PHP blocks
instead of outputting each of those lines using PHP. This saves PHP processing resources and lets us have clean and
readable files in our development.
Example :
info.php
<html>
<body>
<h1> Using PHP and HTML together </h1>
Here is your PHP information:
<br>
<?php
phpinfo();
?>
</body>
</html>
The isset() function checks whether a variable is set, which means that it has to be declared
and is not NULL. This function returns true if the variable exists and is not NULL,
otherwise it returns false.
Web Based Application Development using PHP (MSBTE) 4-9 Creating and Validating Forms
The HTML <form> element defines a form which contains form controls that are used to collect user input. Form
controls are different types of input elements, like text fields, text area, checkboxes, radio buttons, list, submit buttons and
more
− Text Field is used to take a single line input from the user.
− Text Field will be included in <form> element of a web page that will be used to take user input, which will be sent to
PHP script available on the server.
− Data on the server will be fetched by any one of the super global variable $_GET and $_POST, after receiving it will be
processed and the result will be sent to the user in a form of response.
− For Example a Web page textfielddemo.html has a text field, to get a mobile number from the user, on clicking
Submit Button request will be sent to PHP Script textdemo.php on the server using GET method, PHP script will use
super global variable $_GET to fetch the request and to send a response to the user.
Example 1 :
textfielddemo.html
<html>
<head>
<title> Text Field Demo</title>
</head>
<body>
<form method="get" action="textdemo.php">
<label>Mobile Number:</label>
<input type="text" name="mobileno" id=" mobileno">
<input type="submit" value="Submit">
</form>
</body>
</html>
Output :
Web Based Application Development using PHP (MSBTE) 4-10 Creating and Validating Forms
Example 2 :
textdemo.php
<?php
if(isset($_GET["mobileno"])){
echo "<p>Mobile Number : " . $_GET["mobileno"] . "</p>";
}
?>
Output :
− Text Area is used to take multi line input from the user.
− Text Area will be included in <form> element of a web page that will be used to take multi line input like suggestions,
address, feedback from users, which will be sent to PHP script available on the server.
− Data on the server will be fetched by any one of the superglobal variable $_GET and $_POST, after receiving it will be
processed and the result will be sent to user in a form of response.
− For Example a Web page textareademo.html has a text area to get suggestions from users, on clicking Submit Button
request will be sent to PHP Script phptextareademo.php on the server using GET method, PHP script will use
superglobal variable $_GET to fetch the request and to send a response to the user.
Web Based Application Development using PHP (MSBTE) 4-11 Creating and Validating Forms
Example 1 :
textareademo.html
<html>
<head>
<title>Text Area Demo</title>
</head>
<body>
<form method="get" action="phptextareademo.php">
<label>Suggestion:</label>
<textarea name="data" id="data" cols=”50” rows=”5”>
</textarea>
<input type="submit" value="Submit">
</form>
</body>
</html>
Output :
Example 2 :
phptextareademo.php
<?php
if(isset($_GET["data"])){
echo "<p>Suggestion : " . $_GET["data"] . "</p>";
}
?>
Output :
Web Based Application Development using PHP (MSBTE) 4-12 Creating and Validating Forms
− Radio Button is used to make the user select single choice from a number of available choices.
− Radio Button will be included in <form> element of a web page that will be used single choice input from the user,
which will be sent to PHP script available on the server.
− Data on the server will be fetched by any of the super global variable $_GET and $_POST, after receiving it will be
processed and the result will be sent to the user in a form of response.
− For Example a Web page radiobtndemo.html has a radio button to get gender from the user, on clicking Submit
Button request will be sent to PHP Script phpradiobtndemo.php on the server using GET method, PHP script will use
super global variable $_GET to fetch the request and to send a response to the user.
Example 1 :
radiobtndemo.html
<html>
<head>
<title>Radio Button Demo</title>
</head>
<body>
<form method="get" action="phpradiobtndemo.php">
<label>Select your Gender:</label><br/>
<input type="radio" name="gender" value="male" checked> Male<br/>
<input type="radio" name="gender" value="female"> Female<br/>
<input type="submit" value="Submit">
</form>
</body>
</html>
Web Based Application Development using PHP (MSBTE) 4-13 Creating and Validating Forms
Output :
Example 2 :
phpradiobtndemo.php
<?php
if(isset($_GET["gender"])){
echo "<p>Gender : " . $_GET["gender"] . "</p>";
}
?>
Output :
− Check Box is used to select one or more options from available options displayed for selection.
− Check Box will be displayed as square box which will be activated when ticked (checked).
− Check Box will be included in <form> element of a web page that will be used to take user input, which includes
multiple options like hobbies, where user can select one or more hobby form the multiple hobbies displayed on a
web page, which will be sent to PHP script available on the server.
Web Based Application Development using PHP (MSBTE) 4-14 Creating and Validating Forms
− Data on the server will be fetched by any one of the super global variable $_GET and $_POST, after receiving it will be
processed and the result will be sent to the user in a form of response.
− For Example a Web page checkboxdemo.html has a multiple checkbox displaying the hobbies where users will select
one or more of its choice and on clicking Submit Button request will be sent to PHP Script phpcheckboxdemo.php on
the server using GET method, PHP script will use super global variable $_GET to fetch the request and to send a
response to the user.
Example 1 :
checkboxdemo.html
<html>
<head>
<title> Text Field Demo</title>
</head>
<body>
<form method="get" action="phpcheckboxdemo.php">
<label>Select your Hobbies:</label>
<input type="checkbox" name="cricket" value="Cricket" checked > Cricket
<input type="checkbox" name="football" value="Football"> Football
<input type="checkbox" name="basketball" value="Basket Ball" > Basket Ball
<input type="submit" value="Submit">
</form>
</body>
</html>
Output :
Example 2 :
phpcheckboxdemo.php
<?php
echo "<p>Your Hobbies are : " . $_GET["cricket "] .",". $_GET["football0"] ."," . $_GET["basketball"] . "
</p>";
?>
Output :
− HTML <select> tag will be include in <form>element of a web page that will be used to display dropdown list where
user can select single or multiple options (when multiple attribute is set), which will be send to PHP script available on
server.
− The <option> tag will be used in <select> tag in order to drop list of options.
− Data on the server will be fetched by any one of the super global variable $_GET and $_POST, after receiving it will be
processed and the result will be sent to the user as a response.
− For Example a Web page selectdemo.html has a drop down list having a list of genders where users have to select
one of gender, by clicking Submit Button request will be sent to PHP Script phpselectdemo.php on the server using
GET method, PHP script will use super global variable $_GET to fetch the request and to send a response to the user.
Example 1 :
selectdemo.html
<html>
<head>
<title> List Box Demo</title>
</head>
<body>
Web Based Application Development using PHP (MSBTE) 4-16 Creating and Validating Forms
Example 2 :
phpselectdemo.php
<?php
if(isset($_GET["gender"])){
echo "<p>Your Gender is : " . $_GET["gender"] . "</p>";
}
?>
Output :
4.2.6 Buttons
− Text and Image can be displayed on the button by placing the text or image between the opening and closing tags of
button.
− Buttons has to be added with actions using JavaScript or by associating the button with a form.
− In we are creating button in form <input> tag is used to create a button.
− For Example a Web page buttondemo.html has a two buttons “Save Changes” and “Delete”, by clicking any of the
Button request will be send to PHP Script phpbuttondemo.php on server using GET method, PHP script will use
superglobalvariable $_GET to fetch the request and will display name of the button which is clicked and it will be
send as an response to user.
Example :
buttondemo.html
<html>
<head>
<title> Button Demo</title>
</head>
<body>
<form method="get" action="phpbuttondemo.php">
<input type="submit" name="btnSubmit" value="Save Changes" />
<input type="submit" name="btnDelete" value="Delete" />
</form>
</body>
</html>
Output :
Example 2 :
phpbuttondemo.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
Web Based Application Development using PHP (MSBTE) 4-18 Creating and Validating Forms
if (isset($_GET['btnDelete'])) {
echo "Delete Button is clicked";
} else {
echo "Save Changes Button is clicked";
}
}
?>
Output :
− Hidden Controls are used to store the data in a Web page that user can’t see.
− Hidden Controls will be included in <form> element of a web page that will be used to store data that will not be
visible to the user, which will be sent to PHP script available on the server.
− Data on the server will be fetched by any one of the superglobal variable $_GET and $_POST, after receiving it will be
processed and the result will be sent to the user in a form of response.
− For Example a Web page hiddendemo.html has a hidden control which stores user id of the user, on clicking Submit
Button request will be sent to PHP Script phphiddendemo.php on the server using POST method, PHP script will use
superglobalvariable $_POST to fetch the request and to send a response to the user.
Example 1 :
hiddendemo.html
<html>
<head>
<title> Hidden Control Demo</title>
</head>
<body>
<form method="post" action="phphiddendemo.php">
<input type="hidden" name="user_id" id="user_id" value="101">
<input type="submit" value="Submit">
Web Based Application Development using PHP (MSBTE) 4-19 Creating and Validating Forms
</form>
</body>
</html>
Output :
Example 2 :
phphiddendemo.php
<?php
if(isset($_POST["user_id"])){
echo "<p>User ID : " . $_POST["user_id"] . "</p>";
}
?>
Output :
− Multiple functionality can be provided in a single web page by providing multiple forms in a web page having
different functionality.
Web Based Application Development using PHP (MSBTE) 4-20 Creating and Validating Forms
− Each form on this web page will be given a separate name that will uniquely identify the form in web page with
multiple forms.
− Data from each form should be given to separate PHP script file for processing by specifying PHP script filename in
the action attribute of the forms.
− Each PHP Script should be written in such a fashion that will handle all the data coming from that form.
− Disadvantage of this method is that we have to write separate PHP script for each form, which creates extra files for
handing.
− For Example, a Web page multiformdemo.html has two forms, one for sending mail information and another for
sending mobile number information, each form is having its own PHP script written to handle its own form elements
on the server, on clicking submit button of each form data is sent to its corresponding PHP script which handles the
request and generates response for user.
Example :
multiformdemo.html
<html>
<head>
<title> Multiple Form Demo</title>
</head>
<body>
<form name="mailform" method="post" action="phpemaildata.php">
<input type="text" name="email" id="email" />
<input type="submit" name="mail-submit" value="Send Mail Information" />
</form>
Example 2 :
phpemaildata.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!empty($_POST['mail-submit'])) {
echo "Your mail id is : ".$_POST['email'];
}
}
?>
Output :
Example 3 :
phpmobiledata.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!empty($_POST['mobile-submit'])) {
echo "Your Mobile Number is : ".$_POST['mobileno'];
}
}
?>
Output :
− Multiple functionality can be provided in a single web page by providing multiple forms in a web page having
different functionality.
− Each form on this web page will be given a separate name that will uniquely identify the form in web page with
multiple forms.
− Data from each form should be given to a single PHP script file for processing by specifying PHP script filename in the
action attribute of the forms.
− Each PHP Script should be written in such a fashion that will handle all the data coming from multiple forms.
− Data from multiple forms can be identified by it submit button and the processing each form will be written with help
of if, else and else if conditional statements.
− Advantage of this method is that we have to write a single PHP script for processing of all forms, which saves time in
the creation and handling of extra files.
− For Example, a Web page multiformdemo.html has two forms, one for sending mail information and another for
sending mobile number information, both form are having a single PHP script written to handle data of all forms on
the server, by clicking submit button of each form data is sent to its PHP script which identify the form by its submit
button based on that it fetches the request and a generates a response for the user.
Example :
multiformdemo.html
<html>
<head>
<title> Multiple Form Demo</title>
</head>
<body>
<form name="mailform" method="post" action="phpmultiformdemo.php">
<input type="text" name="email" id="email" />
<input type="submit" name="mail-submit" value="Send Mail Information" />
</form>
Output :
Example 2 :
phpmultiformdemo.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!empty($_POST['mail-submit'])) {
echo "Your mail id is : ".$_POST['email'];
}
else if (!empty($_POST['mobile-submit'])) {
echo "Your Mobile Number is : ".$_POST['mobileno'];
}
}
?>
Output :
− Multiple operations can be provided on a single form by providing a different buttons for different operation.
− Based on which button is clicked, data in the form is processed differently for the operations mentioned on that
button.
− Single PHP Script is sufficient to handle all the operations mentioned on the buttons in the form, PHP Script will
identify the button which is being clicked and will carry out the operations according to it.
Web Based Application Development using PHP (MSBTE) 4-24 Creating and Validating Forms
− Identification of the button is done by its name on the server and corresponding operation is called with the help of
if, else and else if conditional statements.
− For Example a Web page multibuttondemo.html is having two text fields for accepting two numbers from user and
two Submit buttons representing Add and Subtract operation is forms, on clicking each button a corresponding
operation mention in PHP script php multibuttondemo.php on the server will be called.
Example 1 :
multibuttondemo.html
<html>
<head>
<title> Multiple Form Demo</title>
</head>
<body>
<form name="mailform" method="post" action="phpmultibuttondemo.php">
<input type="text" name="no1" id="no1" />
<input type="text" name="no2" id="no2" />
<input type="submit" name="addbtn" value="Add" />
<input type="submit" name="subbtn" value="Subtract" />
</form>
</body>
</html>
Output :
Example 2 :
phpmultibuttondemo.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['addbtn'])) {
echo "Adition of these two numbers is :". ((int) $_POST['no1'] + (int) $_POST['no2']);
} else if (isset($_POST['subbtn'])){
Web Based Application Development using PHP (MSBTE) 4-25 Creating and Validating Forms
echo "Subtraction of these two numbers is :". ((int) $_POST['no1'] - (int) $_POST['no2']);
}
}
?>
Output :
PHP_SELF is a variable that returns the current script being executed. This variable returns the name and path of the
current file (from the root folder). You can use this variable in the action field of the FORM. the $_SERVER["PHP_SELF"]
sends the submitted form data to the page itself, instead of jumping to a different page. This way, the user will get error
messages on the same page as the form.
Example :
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
echo "User Name is:<b> $name </b>";
echo "<br>You can use this form again to enter a new name.";
}
?>
Web Based Application Development using PHP (MSBTE) 4-26 Creating and Validating Forms
− User may by mistakenly submit the data through form with empty fields or in wrong format.
− PHP script must ensure that required fields are complete and submitted data is in valid format.
− PHP provides some inbuilt function using these functions that input data can be validated.
− empty() function will ensure that text field is not blank it is with some data, function accepts a variable as an
argument and returns TRUE when the text field is submitted with empty string, zero, NULL or FALSE value.
− Is_numeric() function will ensure that data entered in a text field is a numeric value, the function accepts a variable
as an argument and returns TRUE when the text field is submitted with numeric value.
− preg_match() function is specifically used to performed validation for entering text in the text field, function accepts
a “regular expression” argument and a variable as an argument which has to be in a specific pattern. Typically it is for
validating email, IP address and pin code in a form.
− For Example a PHP page formvalidation.php is having three text fields name, mobile number and email from user, on
clicking Submit button a data will be submitted to PHP script validdata.php on the server, which will perform three
different validation on these three text fields, it will check that name should not be blank, mobile number should be
in numeric form and the email is validated with an email pattern.
Example 1 :
formvalidation.php
<html>
<head>
<title> Validating Form Data</title>
Web Based Application Development using PHP (MSBTE) 4-27 Creating and Validating Forms
</head>
<body>
<form method="post" action="validdata.php">
Name :<input type="text" name="name" id="name" /><br/>
Mobile Number :<input type="text" name="mobileno" id="mobileno" /><br/>
Email ID :<input type="text" name="email" id="email" /><br/>
<input type="submit" name="submit_btn" value="Submit" />
</form>
</body>
</html>
Output :
Example 2 :
validdata.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if(empty($_POST['name']))
{
echo "Name can't be blank<br/>";
}
if(!is_numeric($_POST['mobileno']))
{
echo "Enter valid Mobile Number<br/>";
}
Web Based Application Development using PHP (MSBTE) 4-28 Creating and Validating Forms
$pattern ='/\b[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}\b/';
if(!preg_match($pattern,$_POST['email']))
{
echo "Enter valid Email ID.<br/>";
}
}
?>
Output :
4.4.1 Superglobals
Q. Describe superglobals.
− The superglobals arrays allow you to specify where the input data came from; that is what method was used.
− superglobals are predefined variables in PHP, 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.
− Superglobals are a type of variables that are available from any part of your code. Some are well known like POST
and GET that are used to pass form values and COOKIE and SESSION that are used to store specific information for
a later use. The superglobals are listed in Table 4.4.1 :
Table 4.4.1
Supreglobal Description
variable
$_SERVER This is an array containing information such as headers, paths and script locations. The entries in this
array are created by the web server. There is no guarantee that every web server will provide any of these
$_REQUEST An associative array consisting of the contents of $_GET, $_POST, and $_COOKIE.
$_GET An associative array of variables passed to the current script via the HTTP GET method.
$_POST An associative array of variables passed to the current script via the HTTP POST method.
$_COOKIE An associative array of variables passed to the current script via HTTP cookies.
Web Based Application Development using PHP (MSBTE) 4-29 Creating and Validating Forms
$_SESSION An associative array containing session variables available to the current script.
$_FILES An associative array of items uploaded to the current script via the HTTP POST method.
$GLOBALS Contains a reference to every variable which is currently available within the global scope of the script.
The keys of this array are the names of the global variables.
$_ENV An associative array of variables passed to the current script via the environment method.
4.5 Cookies
− 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. In short, cookie can be
created, sent and received at server end.
− A cookie is a small file with the maximum size of 4KB that the web server stores on the client computer.
− A cookie can only be read from the domain that it has been issued from. Cookies are usually set in an HTTP header
but JavaScript can also set a cookie directly on a browser.
Fig. 4.5.1
1. Server script sends a set of cookies to the browser. For example : name, age or identification number etc.
3. When next time browser sends any request to web server then it sends those cookies information to the server and
server uses that information to identify the user.
− Cookie is a small piece of information stored in client browser. It is a technique used to identify a user using the
information stored in their browser (if already visited that website)
− When user requests for a page on a Web site data in the cookies which belongs to a same site is send to the server
automatically within the request.
− Expiration period of the cookies can be set, it can be set to seconds, minutes, hours, days or for year, it can also be set
a cookie to expire once browser applications is closed.
− Personalizing the user experience - this is achieved by allowing users to select their preferences. The page requested
that follow are personalized based on the set preferences in the cookies.
Attribute of Description
cookies
Expires The time when a cookie will get expire. When it reaches to its expiration period cookies is deleted from
browser automatically. If value is set to zero, it will only last till the browser is running its get deleted when
the browser exits.
Path The path where browser to send the cookies back to the server. If the path is specified, it will only send to
specified URL else if it is stored with “/” the cookie will be available for all the URL’s on the server.
Domain The browser will send the cookie only for URLs within this specified domain. By default is the server host
name.
Secure If this field is set, the cookie will only be sent over https connection. By default it is set to false, means it is
okay to send the cookie over an insecure connection.
HttpOnly This field, if present, tells the browser that it should only make the cookie assessable only to scripts that run
on the Web server (that is, via HTTP). Attempts to access the cookie through JavaScript will be rejected.
− PHP provides a inbuilt function setcookie(), that can send appropriate HTTP header to create the cookie on the
browser.
− While creating the cookie, we have to pass require arguments with it.
− Only name argument is must but it is better to pass value, expires and path to avoid any ambiguity.
Syntax : setcookie(name, value, expire, path, domain, secure, HttpOnly);
− For Example : setcookie() is used to create a cookie storing the user name with name “username”, abc is the value
stored in the cookie, expires argument uses PHP time() function which returns current time, so the expiry time is
60 * 60 * 24 * 365 seconds after the current time, or one year in future, path argument is set to “/” it means that
cookies can be returned to any URL on the server, domain is set to abc.com, secure flag is set to false and HttpOnly is
too true.
setcookie(“username”, “abc”, time() + 60 * 60 * 24 * 365, “/”, “.abc.com”, false, true);
Web Based Application Development using PHP (MSBTE) 4-31 Creating and Validating Forms
The setcookie() function defines a cookie to be sent along with the rest of the HTTP
headers.
A cookie is often used to identify a user. A cookie is a small file that the server
embeds on the user's computer. Each time the same computer requests a page with a
browser, it will send the cookie too. With PHP, you can both create and retrieve
cookie values.
The name of the cookie is automatically assigned to a variable of the same name. For
example, if a cookie was sent with the name "user", a variable is automatically
created called $user, containing the cookie value.
Example :
cookieexample.php
<html>
<body>
<?php
$cookie_name = "username";
$cookie_value = "abc";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie name '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Output :
Web Based Application Development using PHP (MSBTE) 4-32 Creating and Validating Forms
− We use the isset() function to find out if the cookie is set or not.
− Modification of the cookie can simply be done again by setting the cookie using the setcookie() function.
− Modified cookie can be checked by calling the same cookie with its name to check its modified value.
− Cookie can be deleted from user browser simply by setting expires argument to any past date it will automatically
delete the cookie from user browser.
− Deleted cookie can be checked by calling the same cookie with its name to check if it exists or not.
There is no special dedicated function provided in PHP to delete a cookie. All we
have to do is to update the expire-time value of the cookie by setting it to a past time
using the setcookie() function. A very simple way of doing this is to deduct a few
seconds from the current time.
Syntax:
setcookie(name, time() - 3600);
Example :
<html>
<body>
<?php
setcookie("user"," ",time()-3600);
Web Based Application Development using PHP (MSBTE) 4-33 Creating and Validating Forms
?>
</body>
</html>
Output :
Fig. 4.5.3
For accessing a cookie value, the PHP $_COOKIE superglobal variable is used. It is an associative array that contains a
record of all the cookies values sent by the browser in the current request. The records are stored as a list where cookie
name is used as the key.
Example :
<?php
setcookie("user", "Vijay");
?>
<html>
<body>
<?php
if(!isset($_COOKIE["user"]))
{
echo "Sorry, cookie is not found!";
} else {
echo "<br/>Cookie Value: " . $_COOKIE["user"];
}
?>
</body>
</html>
Firstly cookie is not set. But, if you refresh the page, you will see cookie is set now.
Web Based Application Development using PHP (MSBTE) 4-34 Creating and Validating Forms
Session cookies expire at the end of the session. This means, when you close your browser window, the session
cookie is deleted. This website only uses session cookies. Persistent cookies do not expire at the end of the session.
A session cookie may be created when you visit a site or portion of a site. The cookie exists for the duration of your
visit. For example, a session cookie is created when you use the Personal Login to access secured pages. Depending
on the settings in your browser, you may have the option to deny the session cookie; however, if you deny the cookie
you may have trouble using the site which relies on that cookie.
Isset() function
To read data from a cookie, you first have to check if the cookie actually exists. This is achieved through the isset()
function. The isset() function is used to check for the existence of a variable, in this case, a cookie variable through the use
of the $_COOKIE associative array which stores an array of existing cookies.
Syntax :
isset($_COOKIE['nameOfCookie']);
If the cookie specified in the isset() function exists, then the function will return true, otherwise it will return false.
Example :
<?php
if (isset($_COOKIE['cookie1']))
{
$cookie1 = $_COOKIE['cookie1'];
}
?>
In the above example, an if statement checks for the existence of a cookie named cookie1. If it exists, then its value
will be passed to the variable $cookie1. If it does not, then it will remain empty. The isset() function checks for this.
Advantages of Cookies :
− Occupies less memory, do not require any server resources and are stored on the user’s computer so no extra burden
on the server.
− They are easy to implement : The fact that cookies are supported on the client’s side means they are a lot easier to
implement.
Web Based Application Development using PHP (MSBTE) 4-35 Creating and Validating Forms
− They are domain-specific : Each domain has its own cookies. There is no domain that shares cookies with other
domains. This makes them independent.
− They are simple to use : Cookies are much easier to use. This is the reason why they are enabled and disabled from
the client’s side.
Disadvantages of Cookies :
− They are not secured : As mentioned previously, cookies are not secure as they are stored in the clear text they may
pose a possible security risk as anyone can open and tamper with cookies.
− Difficult to decrypt : You can manually encrypt and decrypt cookies, but it requires extra coding and can affect
application performance because of the time that is required for encryption and decryption.
− There are limitations in size : Several limitations exist on the size of the cookie text (4kb in general), the number of
cookies (20 per site in general). Each site can hold only twenty cookies.
− Can be disabled : User has the option of disabling cookies on his computer from the browser’s setting. This means
that the user can decide not to use cookies on his browser and it will still work.
− Users can delete cookies : The fact that users can delete cookies from their computers gives them more control over
the cookies.
4.6 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.
− Cookies are used to store user data on the client’s browser is not the most secure way of storing data, it can be easily
hacked.
− Cookie data for a website is uploaded every time a request is sent for specify URL on a server. For example 10 cookies
of a site is stored on a client browser then for every request it has to upload 40KB of data for each request done from
server as one cookie is of 4KB.
− Both this problem can be solved by using session to store user data
− Session data is stored on the server side and each Session is assigned with a unique Session ID (SID) for that session
data.
− As session data is stored on the server there is no need to send any data along with the URL for each request to
server.
− More data can be stored in session as compared with cookie because location for storing data is a server.
− PHP stores the session data in a temporary file on the server, the location of the temporary file is specified by the
session.save_path directives in the PHP configuration file
Web Based Application Development using PHP (MSBTE) 4-36 Creating and Validating Forms
− 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.
Fig. 4.6.1
− Session are used to store important information such as the user id more securely on the server where malicious
users cannot temper with them.
− Sessions are the alternative to cookies on browsers that do not support cookies.
− You want to store global variables in an efficient and more secure way compared to passing them in the URL
− You are developing an application such as a shopping cart that has to temporary store information with a capacity
larger than 4KB.
<?php
session_start();
?>
− Session variable can be set with a help of a PHP global variable: $_SESSION.
− Data in the session is stored in the form of keys and values pair.
− We can store any type of data on the server, which include arrays and objects.
− For example, we want to store username in the session so it can be assessed whenever it is required throughout the
session.
Web Based Application Development using PHP (MSBTE) 4-37 Creating and Validating Forms
<?php
session_start();
$_SESSION["username"] = "abc";
?>
Example :
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["Name"] = "Vijay";
$_SESSION["Address"] = "Thane";
echo "Session variables are set.";
?>
</body>
</html>
Output :
− Session variable can be get with a help of a PHP global variable: $_SESSION.
− While accessing the data using $_SESSION variable we have to mention key in the $_SESSION variable.
Example 1 :
<?php
session_start();
echo “User name : ”$_SESSION["username"];
?>
Output :
Web Based Application Development using PHP (MSBTE) 4-38 Creating and Validating Forms
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "User Name: " . $_SESSION["Name"] .".<br>";
echo "User Address: " . $_SESSION["Address"] . ".";
?>
</body>
</html>
Output :
− If someone wants to destroy the session after certain operation example after a logout that can be done using inbuilt
PHP functions.
− A PHP function session_unset() is used to remove all session variables and session_destroy() is used to destroy
session.
<?php
session_unset(); // remove all session variables
session_destroy(); // destroy the session
?>
4.6.6 Session_register()
The function session_register() registers Register one or more global variables with the current session.
session_register() takes two arguments, the string representing the variable name and the value to be assigned to the
variable.
Web Based Application Development using PHP (MSBTE) 4-39 Creating and Validating Forms
Syntax :
Example :
<?php
session_start();
session_register('username', 'John');
function session_is_registered($keyname)
{
echo "Checking if Session exist or not<br/>";
if(isset($_SESSION[$keyname])) {
echo "Session exists<br/>";
return true;
}else {
echo "Session does not exists<br/>";
return false;
}
}
?>
<html>
Output :
Cookie Session
Cookies are stored in browser as text file format. Sessions are stored in server side.
The cookie is a client-side resource. The session is a server-side resource.
It is stored limit amount of data. It is stored unlimited amount of data
It is only allowing 4kb[4096bytes]. It is holding the multiple variable in sessions.
It is not holding the multiple variable in cookies. It is holding the multiple variable in sessions.
We can accessing the cookies values in easily. So We cannot accessing the session values in easily. So it is more secure.
it is less secure.
Remember info until deleted by user or expiry. Remembers info until web site time-out.
Setting the cookie time to expire the cookie. using session_destory(), we will destroyed the sessions.
The setcookie() function must appear BEFORE The session_start() function must be the very first thing in your
the <html> tag. document. Before any HTML tags.
Usually contains an id string. Usually contains more complex information.
Specific identifier links to server. Specific identifier links to user.
o PHP mail is an inbuilt PHP function which is used to send emails from PHP scripts.
o It is a cost effective way of notifying users of important events.
o User’s gets contact you via email by providing a contact us form on the website that emails the provided
content.
o It can also be used to send email, to your newsletter subscribers, password reset links to users who forget their
passwords, activation/confirmation links, registering users and verifying their email addresses
Syntax : mail( to, subject, message, headers, parameters );
Parameters Descriptions
subject Required. Specifies the subject of the email. This parameter cannot contain any newline characters.
Required. Defines the message to be sent. Each line should be separated with a (\n). Lines should not
message
exceed 70 characters.
headers Optional. Specifies additional headers, like From, Cc, and Bcc.
parameters Optional. Additional parameter to the send mail can be mentioned in this section.
Example :
<html>
<head>
<title>Email using PHP</title>
</head>
<body>
<?php
$to = "[email protected]";
$subject = "This is subject";
$message = "<b>This is HTML message.</b>";
$header = "From:[email protected] \r\n";
$header .= "Cc:[email protected] \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retvalue = mail ($to,$subject,$message,$header);
if( $retvalue == true ) {
echo "Message sent successfully...";
}else {
echo "Message could not be sent...";
}
Web Based Application Development using PHP (MSBTE) 4-42 Creating and Validating Forms
?>
</body>
</html>
Output :
Programs
Review Questions
Q. 1 How does the form information get from the browser to the server?
Q. 2 What is the difference between get and post methods?
Q. 3 Explain the superglobals in PHP?
Q. 4 Define session and cookies.
Q. 5 Define coockies. what is the need of it?
Q. 6 Define Coockie. How to create & delete it ? How can we retrieve a Cookie value?
Q. 7 What is the use of isset() function?
Q. 8 How does PHP handle forms with multiple selections?
Q. 9 What is the difference between Session and Cookie?
Q. 10 How can we destroy the cookie?
Q. 11 What is the use of session_start() ?
Q. 12 How to register a variable in PHP session ?
Q. 13 How to validate user input in PHP? Explain
Q. 14 Write a program to create a session, to set a value in session, and to remove data from a session.
Q. 15 Write a PHP code to find greatest of two numbers? Accept numbers from users.
Q. 16 Create Customer form like Customer name, Address, mobile no, item_purchase, Amount using different
form input element & display user inserted values in new PHP form
Q. 17 Create Employee form like Employee name, Address, Mobile no, Date of birth, Post & Salary using
different form input element & display user inserted values in same PHP form
Q. 18 Explain self processing forms in PHP with example
Q. 19 Write a PHP program that demonstrate form element (input elements).
Q. 20 Write a PHP program that demonstrate passing data using GET method.
Q. 21 Write a PHP program that demonstrate passing data using POST method.
Q. 22 A simple calculator web application that takes 2 numbers and an operator (+,-,*,/,%) from an HTML page
and returns the result page with the operation performed on the operands.
Q. 23 Write a program that demonstrate use of cookies.
Q. 24 Write a PHP program that demonstrate use of session.
Q. 25 Write a simple PHP program to check that emails are valid.
❑❑❑