PHP Form Handling

Form data is collected using the PHP superglobals $_GET and $_POST.

PHP Form Handling-Simple HTML Form

A simple HTML form with two input boxes and a submit button is shown below:

<form action="Result.php" method="post">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
<input type="submit">
</form>
PHP form handling
In

In the above example, when a user fills out the form and clicks the submit button, the information is transferred to a PHP file called “Result.php” for processing. In this example, the HTTP POST method is used to send the form data.

You may simply echo all the variables to display the submitted data. The below file is “Result.php”:

<html>
<body>

Welcome <?php echo $_POST["fname"]; ?>
Your Surname is: <?php echo $_POST["lname"]; ?>

</body>
</html>

After filling out form when user will submit the form then the following output will be shown to user:

Now lets see an example with GET Method:

<form action="Result_get.php" method="get">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
<input type="submit">
</form>

and “Result_get.php” looks like this:

<html>
<body>

Welcome <?php echo $_GET["fname"]; ?>
Your Surname is: <?php echo $_GET["lname"]; ?>

</body>
</html>

The Output will be same but we will see the difference between these two PHP form Method in next Chapter.

Note: This example does not include any form validation; instead, it demonstrates how to send and retrieve data from a form.

The next chapters, on the other hand, will demonstrate how to handle PHP forms while keeping security in mind! Validation of form input is critical for keeping your form safe from hackers and spammers.