How to handle forms in PHP
One of the most powerful features of PHP is the way it handles HTML forms. In PHP, we collect form data using the $_GET, $_POST, and $_REQUEST.
Capturing form data
| Superglobal | Description |
|---|---|
$_GET |
Associative array containing data of a form submitted with method="get" (URL parameters). |
$_POST |
Associative array containing data of a form submitted with method="post". |
$_REQUEST |
Associative array that, by default, contains the contents of $_GET, $_POST, and $_COOKIE. |
Using $_POST
Let’s see how to handle a form using $_POST first.
In this example, we have a simple HTML form that is submitted using the method="post":
<html>
<body>
<form method="post" action="process-form.php">
<input type="text" name="message">
<input type="submit" name="submit">
</form>
</body>
</html>
When a user submits the above form, the form data is sent to the “process-form.php” file on the server.
Accessing form data in “process-form.php” using $_POST looks like:
<html>
<body>
<p>Submitted message:</p>
<?php echo $_POST["message"]?>
</body>
</html>
Using $_GET
Next, let’s see how to handle a form using $_GET.
In this example, we have a simple HTML form that is submitted using the method="get" via the URL parameters.
<html>
<body>
<form method="post" action="process-form.php">
<input type="text" name="message">
<input type="submit" name="submit">
</form>
</body>
</html>
When a user submits the above form, the form data is available as URL parameters process-form.php?message=Abc and, just like $_POST, it can be accessed using $_GET:
<html>
<body>
<p>Submitted message:</p>
<?php echo $_GET["message"]?>
</body>
</html>
Note: Information sent from a form with the GET method is visible to everyone. Therefore, never use the GET method to send sensitive form data – use the POST method instead.
Free Resources