Form Handling in PHP – POST vs. GET

PHP

PHP is perfect for handling the data collected by HTML forms. You can process the forms and use the data in PHP. The data can then be emailed or stored in a database. The information then can be processed using POST or GET method. The method is specified when creating the form in HTML. Depending upon this method, you have to write respective PHP codes to get the data.

Here’s how you use HTML and PHP to create forms and process them.

Using POST

<form action="form.php" method="post">
Full Name: <input name="name" type="text"><br />
Email: <input name="email" type="text"><br />
<input type="submit">
</form>

Create a form.php file with the following PHP codes to get the data inputted:

<?php
$name = $_POST['name'];
$email = $_POST['email'];
echo "Your Name : ".$name;
echo "<br />";
echo "Your Email : ".$email;
?>
Output after form submission:
Your Name: Entered Name
Your Email: [email protected]
Note: This is just an example. You can use the collected name and email, and store them in your database or have the PHP mail function email it to you.

Using GET

The same example above, can be processed using GET method as well.

<form action="form.php" method="get">
Full Name: <input name="name" type="text"><br />
Email: <input name="email" type="text"><br />
<input type="submit">
</form>

form.php

<?php
$name = $_GET['name'];
$email = $_GET['email'];
echo "Your Name : ".$name;
echo "<br />";
echo "Your Email : ".$email;
?>
Output after form submission:
Your Name: Entered Name
Your Email: [email protected]

Difference Between POST and GET

Although, POST and GET are quite similar, they have their differences. Besides using different superglobals i.e. $_POST and $_GET to access the values, POST passes variables invisibly while GET passes variables using URL parameters.

In our examples above:
The form using “post” after submission will redirect to: form.php.
The form using “get” after submission will redirect to: form.php?name=Entered+Name&email=example%40gmail.com

So, we can see that GET will display the form information in the URL. If the form contains private or sensitive information like passwords, then GET wouldn’t be the recommended method.

GET is useful for solely getting the parameters for the URL. For example a link is http://www.website.com/agree.php?value=1

If we use $_GET[‘value’] we can access the “1” from the URL. This is useful if you are looking to check form submissions values in the current page.