PHP Form Processing

Introduction
When you submit an HTML form to a PHP page, the data sent by the form can be accessed in a variety of ways. For the purposes of this article, we will assume that the developer has created a very basic form called form.html, which looks like this:  First name: 

Last name: 



Superglobal arrays
PHP automatically creates a superglobal array from which you can access data from a submitted form. Superglobal arrays are automatically global in any scope, which means they can be used inside or outside of functions or methods as needed.

On DreamHost installations of PHP4, the  directive is enabled, meaning that regular global variables are automatically created after receiving form data. On DreamHost installations of PHP5, this directive has been disabled for security reasons, and developers must therefore rely on the superglobal arrays.

If the  attribute of the HTML form was set to , the data will exist in a query string appended to the end of the page's URL: http://example.com/action.php?first_name=James&last_name=Kirk The data in the query string can be accessed from a superglobal array called, and you can convert the data into regular global variables like this: $first_name = $_GET['first_name']; $last_name = $_GET['last_name'];

If the  attribute of the HTML form was set to , the data will be passed in the document headers and be accessible using the   superglobal array. It works in exactly the same way as the $_GET array: $first_name = $_POST['first_name']; $last_name = $_POST['last_name']; Since the  method carries variable values in plain view, it is wiser to use the   method wherever security is a concern.

Checking for variable existence
There are two checks you should perform when processing form data. First of all, it is wise to check that the form data exists at all - the user (or some web bot) may have accessed the page without going through the form. You can check for the existence of any  variables like this:  The user (or bot) is automatically sent to the form if no  variables exist. Secondly, you can check for the existence of specific values prior to assigning them to global variables. It is wise to combine these two checks, and to assign a  value to anything that hasn't been filled-in on the form: 

Working with the data
At this point, the data is available for easy use. After being filtered for exploits and checked for errors, it could be inserted into a database, emailed, or just displayed to the user's browser.

Inserting into a database
Please refer to MySQL and PHP.

Emailing
Please refer to PHP mail.

Displaying in the user's browser
Here is a simple example of how the data can be used immediately: 