| Coding Tutorials

HTML form data can be retrieved and processed in many different ways, for example

  • by using a scripting language,
  • a server-side language such as PHP,
  • or any of the many programming languages of choice.

In this tutorial, we're going to walk you through on how to access or retrieve form data with PHP, and show you the different methods that can be used.

Setting up the HTML form

To set up a form for server processing and data retrieval, two important form attributes that controls how the form data is processed whenever it is submitted must be specified. These two form attributes are:

  • Method Attributes
  • Action Attributes

 <form action="" method=""> ... </form> 

Action Attributes: specifies the PHP script file location for processing when it is submitted. If no script file location is specified, the browser submits the form by using the current PHP script file location ( the self-script in which the form is being called ).

Method Attributes: specifies what type of method the form will use to send the data. We have two methods, the GET and POST.

Note: By default, if no method is specified, the GET method is used.

Setting access keys for the form data by using the element's name attribute

The element's name attribute ( name="unique-name-here" ) value is used by PHP as key to enable access to the data value of the specified form field element when you submit the form. Without the name attribute specified for each element contained in the form, PHP will be unable to create an array automatically with an access key by using the element's name attribute value. This means you can't access that element form data value after the form has been submitted to the server because its key is undefined.

<input type="text" name="unique-name-here" />

How form data is sent

When you submit the form to the server, it encodes it by using a scheme called URL encoding which has a built-in pattern that describes how the form data is parsed and encoded. This scheme parses and encodes the form data as a name/value pairs, and it uses the equal sign (=) to concatenate the name/value pairs together.

name=value

However, if the form data to be sent consists of different pairs, the ampersand character (&) is used to separate them.

 name1=firstValue&name2=secondValue&name3=thirdValue 

Also, if the form data to be sent contains the space character, the scheme replaces it with the plus character (+), and every other non-word characters present is encoded differently.

How send works

Client browsers can send information to a web server in two different ways:

  1. GET Method
  2. POST Method

The GET Method

This method instructs the browser to send the encoded information (the name/value pairs) through the URL parameter by appending it to the page request. The browser implement this method by concatenating the question mark character (?) to the end of the page request since it specifies where the query string (name/values pairs) starts from, and all the form data is visible to everyone as it is displayed in the browser address bar.

Example: How the form GET method data is submitted

how get method is sent

URL parameters explained

  • http://localhost/example.com: Specifies the page request. It is the page the browser is requesting from the server.
  • ?: This character specifies where the query string for the requested page starts from. When it is omitted, the browser won't understand how to handle and send the query string (name/values pairs) to the server.
  • name1, name2: Specifies the form field element's name attribute value. Each is assigned to its corresponding form field data, and it is used as the access key by the server script (PHP), to retrieve its data value when you fill out the form and submit it.
  • firstValue, secondValue: These are the inputted values you entered before submitting the form. Each Value is assigned to its corresponding element's name attribute value.
  • &: This character is used to concatenate the name/value pairs together as one long query string.
  • =: This character is used to assign the name of the form field element to its data value as a name/value pair.

How to retrieve form data sent via GET 

When you submit a form through the GET method, PHP provides a superglobal variable, called $_GET. PHP uses this $_GET variable to create an associative array with keys to access all the sent information ( form data ). The keys is created using the element's name attribute values.

The $_GET Method Script: get-method.php

 // Check if the form is submitted if ( isset( $_GET['submit'] ) ) { // retrieve the form data by using the element's name attributes value as key $firstname = $_GET['firstname']; $lastname = $_GET['lastname']; // display the results echo '<h3>Form GET Method</h3>'; echo 'Your name is ' . $lastname . ' ' . $firstname; exit;
}

The GET method 

 <form action="get-method.php" method="get"> <input type="text" name="firstname" placeholder="First Name" /> <input type="text" name="lastname" placeholder="Last Name" /> <input type="submit" name="submit" /> </form> 

Here is an image showing the code output:

post method code output

Now let's take a look at the code ...

The PHP isset() function is used to determine if a variable is set and is not null.

Firstly, the isset() function checks if the form has been submitted by using the element's name attribute value "submit" (name="submit") as key and pass it to the $_GET[] superglobal variable. This is because the form data are stored in the $_GET[] superglobal array by PHP when it is submitted through the GET method.

Then the form field, first name and last name form data are retrieved by using the same method, passing their respective name attribute values into the $_GET['name as key'] array parameter, and each is assigned to a variable name that was used to display the results.

Using the POST

The form POST method sends information via HTTP header. All name/value pairs sent through this method is invisible to anyone else since all the information are embedded within the body of the HTTP request.

When you submit a form to a server through the POST method, PHP provides a superglobal variable called $_POST. The $_POST variable is used by PHP to create an associative array with an access key ($_POST['name as key']). The key is created automatically by PHP when the form is submitted. PHP uses the form field element name attribute (name="unique-name-here") to create the key.

The $_POST Method Script: post-method.php

// Check if the form is submitted if ( isset( $_POST['submit'] ) ) { // retrieve the form data by using the element's name attributes value as key $firstname = $_POST['firstname']; $lastname = $_POST['lastname']; // display the results
echo '<h3>Form POST Method</h3>'; echo 'Your name is ' . $lastname . ' ' . $firstname; exit; } 

The POST method form

 <form action="post-method.php" method="post">

<input type="text" name="firstname" placeholder="First Name" />

<input type="text" name="lastname" placeholder="Last Name" />

<input type="submit" name="submit" />
</form> 

 

get method code output

Code explained

isset( $_POST['submit'] ) : This line checks if the form is submitted using the isset() function, but works only if the form input type submit has a name attribute (name="submit"). $_POST['firstname']: The form data is stored in the $_POST['name as key'] variable array by PHP since it is submitted through the POST method, and the element name attribute value - firstname (name="firstname") is used to access its form field data. The same procedure is used for $_POST['lastname']. The form data is then assigned to a variable that was used to display the results.

The $_REQUEST variable

The $_REQUEST variable is another PHP superglobal variable that you can use to dynamically retrieve form data sent from both Form GET and POST methods. The $_REQUEST variable contains the content of both $_GET, $_POST and $_COOKIES.

Note: the $_COOKIES superglobal variable is used for creating COOKIES data. We will discuss this in a different tutorial.

Example: request-script.php

The $_REQUEST variable code

 // Check if the form is submitted
if ( isset( $_POST['submit'] ) ) {

// retrieve the form data by using the element's name attributes value as key

echo '<h2>form data retrieved by using the $_REQUEST variable<h2/>'

$firstname = $_REQUEST['firstname'];
$lastname = $_REQUEST['lastname'];

// display the results
echo 'Your name is ' . $lastname .' ' . $firstname;

// check if the post method is used to submit the form

if ( filter_has_var( INPUT_POST, 'submit' ) ) {

echo '<h2>form data retrieved by using $_POST variable<h2/>'

$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];

// display the results
echo 'Your name is ' . $lastname .' ' . $firstname;
}

// check if the get method is used to submit the form

if ( filter_has_var( INPUT_GET, 'submit' ) ) {

echo '<h2>form data retrieved by using $_GET variable<h2/>'

$firstname = $_GET['firstname'];
$lastname = $_GET['lastname'];
}

// display the results
echo 'Your name is ' . $lastname .' ' . $firstname;
exit;
}

The form code

 <form action="demo/request-variable.php" method="post">

<input type="text" name="firstname" placeholder="First Name" />

<input type="text" name="lastname" placeholder="Last Name" />

<input type="submit" name="submit" />
</form> 

request method code output

Code explained

The $_REQUEST variable script code works exactly the same way as the previous $_GET and $_POST code script above. The only task required is to replace the $_GET and $_POST with the $_REQUEST variable.

The filter_has_var() function

It checks if a variable of a specified input type exists. It has two parameters, filter_has_var( type, variable_name ), and both parameters are required. The first parameter type specifies the input type to check for, which can be any of the following constant values ( INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, INPUT_ENV). The second parameter input specifies the variable name (the name attribute of the form input element, name="unique-name-here") to check.

Anatomy of the GET method

  • The GET method produces a long query string that is displayed in the browser's address bar when the form is submitted.
  • The GET method should not be used to send sensitive content/information like password because all of the content/information is displayed in the browser's address bar.
  • When sending form data through the GET method, you can only send a maximum of 2048 characters.
  • The GET method cannot be used to send binary data like images, mp3 or pdf files to the server.
  • When you submit a form through the GET method, PHP creates a $_GET associative array in this format, $_GET['name as key'] to enable you to retrieve the form data.
  • The GET method is suitable to send non-sensitive content/information to the server.

Anatomy of the POST method

  • The POST method sends information via HTTP header, all the information are embedded within the body of the HTTP request.
  • The POST method can be used to send sensitive content/information since all data are sent through the HTTP header.
  • This method has no limit on the amount of information to send to the server.
  • The POST method provides support to send binary data like images, mp3 or pdf files, and also provides enhancement for file uploading to the server.
  • When you submit a form through the POST method, PHP creates a $_POST associative array in this format, $_POST['name as key'] to enable you to retrieve the form data.

Form validation

We are going to filter and sanitize the inputted data by using the PHP preg_replace() function. Although, the PHP filter extension can be used to perform the same task.

 // 

The Preg_replace() function

This function performs a regular expression search and replace.

preg_replace( $pattern, $replacement, $subject, $limit, $count )

Note: The $limit and $count parameters are optional. Both can be omitted.

Example: The preg_replace() function code

 $firstname = preg_replace( "#[^\w]#", "", $_POST['firstname'] );

$lastname = preg_replace( "#[^\w]#", "", $_POST['lastname'] ); 

Code explained

The first parameter: "#[^\w]#" represents a Regular Expression pattern, the function uses this pattern and validates it against a Regular Expression word character (\w). \w is a Regex metacharacter that matches only word characters ( the alphabet A to Z uppercase or a to z lowercase, and the underscore character _ ). The [^\w] matches any non-word characters. The hash character (#) is the regular expression modifier.

The second parameter: "" is what the function will use to replace any non-word characters found in the inputted values. In this case, we're replacing any nonword characters found with an empty string.

The third parameter: $_POST['firstname'] or $_POST['lastname'] represents the inputted values you entered into the form field. The function checks the characters that is contained in this third parameter, and then validates it against the expression (match any non-word character) in the first parameter, if any non-word character is found, the function replaces it with the value in the second parameter (an empty string).


About the author

John Zenith is a front-end developer, writer, speaker, and a code builder who loves Javascript, CSS and PHP. He lives in the southern part of Nigeria.