How To Retrieve HTML Form Data With PHP

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.

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).

Author

5 1 vote
Article Rating
Subscribe
Notify of
guest

31 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Vikas
Vikas
6 years ago

Nice explanation john……….thanks bro

Parth
Parth
5 years ago
Reply to  John Zenith

Sorry, But I’m a fresher and I want to sent a particular form data and I also have to retrieve it back. I’ve visited several sites but I found yours very useful. I just want to know that where to write this php code and how to run it and all? Please explain me friend I’m doing a project that’s why!

Habib
Habib
3 years ago
Reply to  Parth

first you should link to the database and then you can retrieve your data from database

Jagan
Jagan
6 years ago

Hi…is there any special requirements for using php???
Im using Sublime and every time i click submit i get the entire code of php file.
the action of the form was my php file..

muhammad
muhammad
3 years ago
Reply to  John Zenith

bro I need help you fit help me?

shashank kurakula
shashank kurakula
5 years ago
Reply to  Jagan

place the code with in the server folder, if you are using xampp place the codes in xampp/htdocs/yourfile.php this should work

megha N shastry
megha N shastry
5 years ago
Reply to  Jagan

Run it in the localhost. Using XAMP  or WAMP 
Your localhost path will be something like this http://localhost/self.php

Md. Shakhowat Hossain
Md. Shakhowat Hossain
5 years ago

I want to pass data from htdocs/skhtml/DataTest.html to htdocs/skphp/DataTest.php. Please help me to send code of html & php.
Thank you.
Shakhowat
My code:

Name:

Tech Guru
Tech Guru
5 years ago

Assuming you already have the DataTest.php file in the same project folder, the below should work

           Name:
           

James Miller
James Miller
4 years ago

This was a very good method of explanation. KUDOS.

sad
sad
4 years ago

finally an actual tutorial not a stupid tutorial  

Nagarj
Nagarj
4 years ago

Hi…is there any special requirements for using php???
Im using visual code and every time i click submit i get the entire code of php file.
the action of the form was my php file..

Shine
Shine
4 years ago

WELL EXPLAINED ❤

Bukola
Bukola
4 years ago

Hi John,

Can I send the data gotten from my form in a table to an email using PHP?

Pravin mandlekar
Pravin mandlekar
4 years ago

Hi John,

Very nicely explained, i need your help for passing HTML INPUT value to server side code specifically SELECT statement to filter out table data based on user input. NOTE: i want input value before form is SUBMITTED. I have tried many ways like :

1) passing thru $_GLOBAL variable from JAVA SCRIPT to PHP function, 
2) thru parameter from JAVA SCRIPT to PHP function as input parameter
3) Passing thru cookie,but it gives previous values of before page refresh.
4) $_POST & $_GET does not work as form is not submitted.

I am working on portal development this is my first project and I want to show city and state with help of PINCODE entered by user. 

sahil
sahil
4 years ago

Sir, I wanted to know that how to get the information on a certain g-mail account if someone has filled the survey form and submitted it.

Sir, if you answer this question it would be a great help

Daniel Friendly
Daniel Friendly
4 years ago
Reply to  sahil

//to send mail to gmail_account@gmail.com create the following variables
$to = “gmail_account@gmail.com”;
$subject = “Data collected thorugh form”;
$message = “

“.$_POST[“firstname”].”

“.$_POST[“firstname”].”

“;
//now send the mail
mail($to,$subject,$message);

Daniel Friendly
Daniel Friendly
4 years ago

to send mail to gmail_account@gmail.com create the following variables
$to = “gmail_account@gmail.com”;
$subject = “Data collected through form”;
$message = “

“.$_POST[“firstname”].”

“.$_POST[“lastname”].”

“;
//now send the mail
mail($to,$subject,$message);

Daniel Friendly
Daniel Friendly
4 years ago

Very good explanation. Thanks.

OnlineMD
OnlineMD
4 years ago

Thanks John….. lovely assistance into dev world

Ritesh Itankar
Ritesh Itankar
3 years ago

Thanks

Negzuu
Negzuu
3 years ago

Sorry, but how can i send this form to many PhP Files?

Michael Scharen
Michael Scharen
3 years ago

It looks all very logical and rational. I’m just trying to figure this stuff out since I would like to test my forms offline. We’ll give it a try!

Brandon
Brandon
3 years ago

Just wanted to say that even though this post is 15 years old – this was the only page I could find that properly explained everything. THANK YOU JOHN!

Mikall Hill
3 years ago
Reply to  Brandon

awesome! So glad you found us, Brandon, and thanks for taking the time to post!

abdulsalam adedibu
abdulsalam adedibu
3 years ago

nice one, Good to know we have a Nigerian who explains well nice one john, you surprised me I didn’t think a Nigerian wrote this article till I saw your name, nice one bro

31
0
Would love your thoughts, please comment.x
()
x