Working with HTML Form in PHP – Syntax, Example

In this tutorial, we will learn about how to work with an HTML form in PHP. We will explore a detailed explanation of the basic structure of an HTML form and the process of receiving data from the form in PHP.

This process involves understanding the roles of the HTTP request methods, namely GET and POST. Both methods performs the same function but how they handle the input data is different. Let’s start first to understand the basic introduction of an HTML form in PHP.

Introduction to HTML Form in PHP


An HTML form is a basic component of many dynamic websites and web applications. It is the most effective way to collect the user data such as contact information, registration details, login credentials, and other necessary data or inputs.

HTML forms are essential for building dynamic websites where users enter input, and based on that input, the server processes the data and returns a response to the user. They provide a structured and user-friendly interface that enables interactive communication between the user and the server.

Basic Structure of HTML Form

The basic structure of an HTML page with a form that takes two input fields and a submit button is as follows:

<!DOCTYPE html>
<html>
<head>
    <title>Simple HTML Form</title>
</head>
<body>
   <h2>User Input Form</h2>
   <form action="process.php" method="post">
      <label for="firstname">First Name:</label>
      <input type="text" id="firstname" name="firstname"><br><br>

      <label for="lastname">Last Name:</label>
      <input type="text" id="lastname" name="lastname"><br><br>

      <input type="submit" value="Submit">
   </form>
</body>
</html>

Let us take a look at the key elements of the above HTML form structure:

(1) <form>:

A form is defined using the <form> and </form> tags. The <form> is the opening tag, while </form> is the closing tag. The action attribute of  the <form> element specifies the URL, where the form data will be sent when the form is submitted. In the above example, the data will be sent to the process.php file on the server.

The method attribute specifies how data will be sent. It determines HTTP method used to send the form data. The most commonly used methods are GET and POST.

(2) <label>:

The <label> tag is used to add a label to an input element. The attribute for of the <label> element is used to associate the label with a specific input element by matching the input element’s id. This association improves accessibility because when a user clicks on the label, the associated input field is automatically selected or focused.

(3) <input>:

The <input> tag is used to create input fields where a user can enter data or information. The type of input field is defined by the type attribute. In the above example, we have two text input fields (type=”text”). The name attribute is used to identify each input field when the form data is submitted to the server. It acts as the key in the key-value pair sent in the request.

(4) <input type=”submit”>:

This tag defines a submit button in the form. When the user clicks on it, all the form data is collected and sent to the server for processing. The form data is sent to the URL specified in the action attribute of the <form> tag, using the method defined in the method attribute (GET or POST).

The above HTML form is very basic. Depending on your requirements, you may want to add more input fields, such as checkboxes, radio buttons, text areas, data selectors, and many other input fields that HTML provides.

Receiving Form Data in PHP


When a user fills out a form and clicks the submit button, the browser sends the form data or information to the web server using a specific HTTP method for further processing. Processing a form means taking the information provided in the form and performing some action with it, such as displaying it, storing it in a database, etc.

HTTP (HyperText Transfer Protocol) is the standard protocol used for transmitting documents and data over the web. This defines how messages are formatted and transmitted between clients (i.e. browsers) and servers.

In PHP, there are two ways the browser can send the form data to the web server. They are:

  • GET Method
  • POST Method

The GET and POST are the most two common HTTP request methods. These methods perform the same function, but they handle input data differently. So, let’s understand one by one.

GET Method in PHP


The GET method is the simplest type of HTTP method that is mainly used for the simple retrieval of static HTML documents, images, or the results of a database query. This method sends submitted data to the web server by appending it to the end of URL as parameters.


When the user presses the submit button, the browser encodes the form data, and appends it to the URL of requested page as a set of key-value pairs. The key represents the name attribute of the input field, and value (URL encoded) represents data entered by the user in that field.

The page URL and key-value pairs are separated using a question mark (?). Each field is separated by an ampersand &. Let’s take a look at the example below of a page URL used in a GET request.

http://localhost/PHP_Project/FormHandling/process.php?firstname=John&lastname=Smith

When the user submits a form using the GET method, it sends the form data directly at the end of the URL as key-value pairs. Let’s breakdown the URL:

  • http://: This is a protocol used to access the resource (HTTP).
  • localhost: This represents the domain name pointing to your local server (XAMPP).
  • /PHP_Project/FormHandling/: This is the folder path in the htdocs directory where your project files are stored.
  • process.php: This is a PHP file that receives and processes the form data.
  • ?: The question mark indicates the beginning of query parameters (form data).
  • firstname=John: This is the first key-value pair where the key is firstname, and value is John.
  • &: This is a separator used between multiple parameters.
  • lastname=Smith: This is the second key-value pair where the key is lastname, and value is Smith.

$_GET Super Global Variable


PHP provides a built-in super global variable $_GET, which is used to collect form data after submitting an HTML form with the HTTP method GET. This super global variable also collect data sent in the URL. The $_GET variable is not stored on the serve, but it passed with each HTTP request.

In PHP, the data from a submitted form is collected using superglobal arrays. The data is accessed through array keys of the global variables $_GET. The general syntax to access the form data through array keys is as:

$variable_name = $_GET['input_name'];

In this syntax,

  • $_GET is a superglobal array in PHP that holds data sent through the GET method.
  • ‘input_name’ is the name attribute of the form field in the HTML form.
  • $variable_name is the PHP variable where you’re storing the input value.

Example :

<input type="text" name="username">
$username = $_GET['username']

Example of Receiving Data from HTML Form in PHP


Let’s take the above example of a simple HTML form and see how the data will be received in the process.php file using the GET method and the $_GET variable.

HTML Code: Simple HTML Form

<!DOCTYPE html>
<html>
<head>
    <title>Simple HTML Form</title>
</head>
<body>
   <h2>User Input Form</h2>
   <form action="process.php" method="get">
     <label for="firstname">First Name:</label>
     <input type="text" id="firstname" name="firstname"><br><br>
     <label for="lastname">Last Name:</label>
     <input type="text" id="lastname" name="lastname"><br><br>
     <input type="submit" value="Submit">
   </form>
</body>
</html>

PHP Code (process.php)

<?php
// Check if the form has been submitted using GET method.
if ($_SERVER["REQUEST_METHOD"] == "GET") {
 // Retrieve the values from the form.
    $firstName = $_GET['firstname'];
    $lastName = $_GET['lastname'];

 // Display the submitted data on the web page.
    echo "<h2>Form Submission Result:</h2>";
    echo "First Name: " . $firstName . "<br>";
    echo "Last Name: " . $lastName;
} else {
 // Handle cases where the form was not submitted properly.
    echo "Form not submitted correctly.";
}
?>

Explanation:

Let’s break down and understand each part of the above PHP code in detail:

(1) The line if ($_SERVER[“REQUEST_METHOD”] == “GET”) { checks if the form has been submitted using the GET method.

(2) Inside the parentheses of If statement, the $_SERVER[“REQUEST_METHOD”] tells you which HTTP method has been used to access the page. It returns the request method used to access page.

(3) The code inside the if block will only execute if the form has submitted using the GET method. Since the condition is true, the script will proceed to retrieve and display the form data.

(4) The line $firstName = $_GET[‘firstname’]; retrieves the value entered in the First Name input field of the HTML form. The $_GET[‘firstname’] accesses the data from the query string in the URL.
For example, the $_GET[‘firstname’] will return “John” from the above URL, which is stored in the variable named $firstName.

(5) Similarly, the line $lastName = $_GET[‘lastname’]; retrieves the value entered in the Last Name input field. The returned value is stored in the variable named $lastName.

(6) After that, we have used the echo statement to display the submitted data on the web page. The <br> tag adds a line break for formatting.

Output: 
     Form Submission Result: 
     First Name: John
     Last Name: Smith

How Does an HTML Form Work in PHP?


An HTML form in combination with PHP allows you to collect the form data from users and process that data on the server side. When a user fills out an HTML form and clicks on the submit button displayed on the web page, the browser sends the entered data and appends them it to the current URL as a set of key-value pairs. The browser sends the data through an HTTP request to the server when the form is submitted.

The server-side PHP script named “process.php” receives the form data using the superglobal variable $_GET. PHP runs on the server to process the form data.

Diagram showing how an HTML form sends data to a PHP script on a web server using an HTTP request and receives a response.

After processing the received data, process.php sends the result back to the browser through an HTTP response and the user sees the output on the web page. In simple terms, the PHP script process.php generates and displays the output based on the user’s input.

The destination file (i.e., process.php) is specified in the action attribute of the <form> tag. The method of transmission is defined by the method attribute, which can be either GET or POST.

Disadvantages of Using Get Method


There are the following disadvantages of using GET method that you should keep in mind while using it. They are:

  • The main disadvantage of using GET method is that all the form data is sent via the URL, which is visible to the user on the browser’s address bar.
  • Browsers and servers often impose size limitations on the length of a URL. For example, some UNIX servers limit the URL length to the size 1240 bytes. This makes GET unsuitable for sending large amounts of data, such as comments, descriptions, or form uploads. In such cases, you should use the POST method, which we will discuss in the next section.
  • Since data is appended to the URL and visible in the address bar, making it easy to read or intercept. You cannot send the sensitive information like passwords, personal details, or banking data.
  • Since browsers may cache GET requests, which can pull previous request results from its cached instead of the most recent one. In simple words, the browser can display the outdated or incorrect results when users revisit the page.
  • Users can bookmark or share URLs with form data, which may unintentionally expose private information.
  • When you refresh a web page submitted using the GET method, the browser may resend the same request. This can be problematic, especially for operations like search or filtering.
  • Since the browser history saves the full URL with data, anyone using that browser can retrieve it later.
  • GET does not support file uploads. For uploading files, you must use the POST method.

When to Use GET Method in PHP?


You can use the GET method when you want the information sent from a form to be visible in the URL. This is because all variable names and values are appended to the URL and can be seen by anyone.

GET is suitable when you want to send a small amount of data, typically for non-sensitive purposes such as search queries, filters, or page navigation.

This method is suitable for sending non-sensitive data where security is not a concern.


Note: The GET method should never be used to send passwords or other sensitive information, as the data is easily visible, logged in browser history, and can be cached or intercepted.