w3resource logo


PHP Tutorial

PHP Form handling

Secondary Nav

Description

This tutorial discusses PHP form handling/processing. You will learn how to collect user-supplied form data using POST and GET method from various from controls like text, select, radio, checkbox and textarea.

This tutorial helps you a lot for learning Form Validation.

Typical structure of an HTML form

Typical structure of an HTML form intended to submit data to a PHP file looks like following:

<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset=utf-8>
<title>Form validation with parsely.js</title>
<link href="../../twitter-bootstrap/twitter-bootstrap-v2/docs/assets/css/bootstrap.css" rel="stylesheet">
<style type="text/css">
h1 {margin-bottom:20px}
form{margin-left:100px}
input, label {margin-top:7px; margin-bottom:7px; color:#000066; font-size: 18px; padding-right: 7px}
input[type='checkbox'] {margin-left: 5px}
</style>
</head>
<body>
<div class="row">
<div class="span12">
<form id="registration_form" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
  <label>Full name<span class="note">*</span>:</label>
  <input type="text" name="full_name" placeholder="FirstName LastName" autofocus="autofocus">   
  <label>Email address<span class="note">*</span>:</label>
  <input type="text" name="email_addr">
  <label>Select Tour Package<span class="note">*</span>:</label>	
   <select name="package">
	<option value="Goa">Goa</options>
	<option value="Kashmir">Kashmir</options>
	<option value="Rajasthan">Rajasthan</options>
   </select>
  <label>Arrival date<span class="note">*</span>:</label>
  <input type="text" name="arv_dt" placeholder="m/d/y">
  <label>Number of persons<span class="note">*</span>:</label>
  <input type="text" name="persons">
   <label>What would you want to avail?<span class="note">*</span></label>  
 Boarding<input type="checkbox" name="facilities[]" value="boarding">
 Fooding<input type="checkbox" name="facilities[]" value="fooding">
 Sight seeing<input type="checkbox" name="facilities[]" value="sightseeing">
 <label>Discout Coupon code:</label>
  <input type="text" name="dis_code">
  <label>Terms and conditions<span class="note">*</span></label>
  <input type="radio" name="tnc" value="agree">I agree<br>
  <input type="radio" name="tnc" value="disagree">I disagree<br>
  <button type="submit" class="btn btn-large btn-primary" name="submit">Complete reservation</button>
</form>
</div>
</div>
<body>
</html>

When user submits data by clicking on "complete reservation", data supplied to various fields of the form goes to the file mentioned as a value of the action attribute specified within the opening tag of the form. For this example, like often developers do, we have used this file itself for processing form data. So, <?php echo $_SERVER['PHP_SELF']; ?> points to the file itself. If you wish to use a PHP file other that this to process form data, you may replace that with filename of your choice.

Form data is submitted to the PHP file for processing using POST here. Other methods you may use instead of POST is GET and REQUEST.

In a moment we will see differences between those three methods.

GET vs POST vs REQUEST

All of these methods create an associative array(e.g. array( key => value, key2 => value2, key3 => value3, ...)). This array holds key-value pairs, where keys are names of the form controls and data supplied to those controls are values.

Both GET, POST and REQUEST are treated as $_GET, $_POST and $_REQUEST. All of these are superglobals,i.e. automatically global variables. So, they can be accessed throughout a script, including within functions or methods, without declaring them explicitly as global $variable;.

$_GET is an associative array of variables passed to the current script via the URL parameters.

$_POST is an associative array of variables passed to the current script via the HTTP POST method.

$_REQUEST is also an associative array. Since it contains the contents of $_GET, $_POST and $_COOKIE automatically, it can be modified remotely and thus can't be trusted. So, it may be not a good idea to use REQUEST when processing form data. so, you may use GET or POST.

Which one shall I use? GET or POST

Sometimes, this may bother a beginner. Let's see both of this methods a bit more in detail, which, hopefully, help you to pick one.

GET appends name/value pairs to the URL and this way passes the values collected from form to the destination PHP file. POST method embeds the name-value pairs inside the body of the HTTP request and the information is sent to the server.

Browsers have limitations when it comes to appending name value pairs to the url, as it happens in case of GET. The effective limitation is about 2000 characters. Some Firewalls or IDS also produce unreliable results because of this. Moreover, name value pairs are also cached in browser. If somebody bookmarks the url containing name value pairs, (s)he can directly get the values passed previously.

Passing the values appended to the url, particularly when sending sensitive information is not a good idea for security reasons.

Limitations of characters does not come to POST since it embeds name-value pairs within the body of the HTTP request. Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.

POST is preferred by developers, in general, to send form data to the server. GET may be used for sending nonsensitive data.

Using POST

Now, we will see how we can send data using POST and how to access data send using POST. We will take the HTML form shown above in this tutorial for demonstration.

When you use POST, the value of the method attribute is POST. And you can collect values send bu POST to the file specified as the value of action attribute. In this example, we are using the file itself, where the code for the HTML form resides.

POST creates an associative array. So, after form is submit, you may access that data using $_POST array. Let's add the following PHP code in that file (say form-handling-example-form.php)to view what we receive after filling our example HTML form with some arbitrary data.

<?php
print_r($_POST);
?>

And following will be output of after form data is submit (with data we supplied to the form for demonstration. You may use your own data).

PHP POST Data

In practice, though, you will need to collect data for individual fields/controls of the form. In a moment, we will discuss that.

How to collect text input using POST

To collect text input data, we use $_POST['fieldname'], where field name is value of the associated field's name attribute. So, for the example form, to collect data supplied by user in Full Name field, we use $_POST['full_name']. You may collect data in this fashion for fields if value of the type attribute is text or email or date.

For collecting data form selection list, radio, and checkbox, we need to be a little tricky, though.

How to collect selection list data/value using POST

Here is a piece of code which you may use to collect data from a selection list.

	
   <select name="package">
	<option value="Goa" <?= ($_POST['package'] == "1")? "selected":"";?>>Goa</options>
	<option value="Kashmir" <?= ($_POST['package'] == "2")? "selected":"";?>>Kashmir</options>
	<option value="Rajasthan" <?= ($_POST['package'] == "3")? "selected":"";?>>Rajasthan</options>
   </select>

This code selects the user selected value for the selection list.

How to collect checkbox data/value using POST

<label<What would you want to avail?<span class="note"<*</span<</label<  
 Boarding<input type="checkbox" name="facilities[]" value="boarding" <?php if(isset($_POST['submit']) && isset($_POST['facilities'][0])) echo "checked" ?< <
 Fooding<input type="checkbox" name="facilities[]" value="fooding" <?php if(isset($_POST['submit']) && isset($_POST['facilities'][1])) echo "checked" ?< <
 Sight seeing<input type="checkbox" name="facilities[]" value="sightseeing" <?php if(isset($_POST['submit']) && isset($_POST['facilities'][2])) echo "checked" ?< <

The code above will collect data/value form a checkbox.

How to collect radio button data/value using POST

Using a simple PHP Switch statement, you may collect data from a radio button.

<label>Terms and conditions<span class="note">*</span></label>
  <input type="radio" name="tnc" value="agree" <?php echo $tncv; ?>>I agree<br>
  <input type="radio" name="tnc" value="disagree" <?php echo $tnc1v; ?>>I disagree<br>
$tnc = $_POST['tnc'];
switch($tnc)
{
case "agree":
$tncv="checked";
$tnc1v="";
break;

case "disagree":
$tncv="";
$tnc1v="checked";
break;

default: // By default 1st option is selected
$tncv="checked";
$tnc1v="";
break;
};

Detecting if the form is submit

To detect whether a form is submitted, you may use following code pattern.

if (isset($_POST['submit'])){
//do something
}

Where submit is the name of the submit button used to submit data.

Using GET

If you wish to collect data using GET instead of POST, you have to change the value of the method attribute of the form in question as GET. User supplied form data can be collected using $_GET associative array in the similar fashion we shown POST to be used to collect data.

For the form in the example in this tutorial, if we use GET instead of POST, and supply some arbitrary data to the form and submit, data will be passed to the url as name-value pairs. Following picture shows you what happens.

PHP GET Data

You may download the form used in this example and try all the options shown in this tutorial.

Form handling/processing is a very important part of learning PHP and hopefully this tutorial is useful for you to do that. If you feel some more relevant stuff can be useful, let us know.



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program