PHP Form Handling

In this tutorial, we will discuss PHP form handling. You will learn how to collect user-supplied form data using $_POST, $_GET, and $_REQUEST methods from various form control like text, select, radio, checkbox, and textarea.

Let’s create a simple Contact Form:

Here we are going to create a simple HTML contact form that allows users to enter their comment and feedback then displays it to the browser using PHP.

Open any code editor and create a new PHP file. Now type the following code and save this file as “contact-form.php” in the root directory of your project.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Contact Form</title>
</head>
<body>
    <h2>Contact Us</h2>
    <p>Please fill in this form and send us.</p>
    <form action="process-form.php" method="post">
        <p>
            <label for="inputName">Name:<sup>*</sup></label>
            <input type="text" name="name" id="inputName">
        </p>
        <p>
            <label for="inputEmail">Email:<sup>*</sup></label>
            <input type="text" name="email" id="inputEmail">
        </p>
        <p>
            <label for="inputSubject">Subject:</label>
            <input type="text" name="subject" id="inputSubject">
        </p>
        <p>
            <label for="inputComment">Message:<sup>*</sup></label>
            <textarea name="message" id="inputComment" rows="5" cols="30"></textarea>
        </p>
        <input type="submit" value="Submit">
        <input type="reset" value="Reset">
    </form>
</body>
</html>

Code Explanation

There are two attributes within the opening <form> tag:

  • The action attribute references a PHP file “process-form.php” that receives the data entered into the form when the user submits it by pressing the submit button.
  • The method attribute tells the browser to send the form data through the POST method.

The rest of the elements inside the form are basic form controls to receive user inputs.

To access the value of a particular form field, you can use the following superglobal variables. These variables are available in all scopes throughout a script.

  • $_GET –  Contains a list of all the field names and values sent by a form using the get method (i.e. via the URL parameters).
  • $_POST –  Contains a list of all the field names and values sent by a form using the post method (data will not visible in the URL).
  • $_REQUEST –  Contains the values of both the $_GET and $_POST variables as well as the values of the $_COOKIE superglobal variable.

When a user submits the above contact form through clicking the submit button, the form data is sent to the “process-form.php” file on the server for processing. It simply captures the information submitted by the user and displays it to the browser.

The PHP code of “process-form.php” file will look something like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Contact Form</title>
</head>
<body>
    <h1>Thank You</h1>
    <p>Here is the information you have submitted:</p>
    <ol>
        <li><em>Name:</em> <?php echo $_POST["name"]?></li>
        <li><em>Email:</em> <?php echo $_POST["email"]?></li>
        <li><em>Subject:</em> <?php echo $_POST["subject"]?></li>
        <li><em>Message:</em> <?php echo $_POST["message"]?></li>
    </ol>
</body>
</html>

The PHP code above is quite simple. Since the form data is sent through the post method, you can retrieve the value of a particular form field by passing its name to the $_POST superglobal array, and display each field value using echo() statement.

We will see another example of using GET and POST method:

<!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>

Using POST

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

<?php
print_r($_POST);
?>

How to collect text input using POST

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

For collecting data form the 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 that you may use to collect data from a selection list.

<label>Select Tour Package*:</label>	
   <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 submitted

To detect whether a form is submitted, you may use the 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 a 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. Efficient PHP form handling techniques for seamless data processing. Learn to manage forms effortlessly with PHP’s powerful functionalities.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.