PHP Form Handling

PHP Form Handling

Handling HTML forms is one of the most common tasks in PHP web development. Whenever a user submits a login form, a contact form, or a search query, PHP acts as the bridge between the user interface and the backend server.

The PHP superglobals $_GET and $_POST are used to collect form data.


A Simple HTML Form

Let's imagine you have a simple HTML form with two input fields (Name and Email) and a submit button.

<form action="welcome.php" method="post">
  Name: <input type="text" name="name"><br>
  E-mail: <input type="text" name="email"><br>
  <input type="submit">
</form>

When the user fills out this form and clicks the submit button, the form data is sent to a PHP file named welcome.php for processing. The data is sent using the HTTP POST method (because we specified method="post").


Collecting the Data with PHP

To display the submitted data inside welcome.php, you can use the $_POST superglobal array. The keys in the $_POST array match the name attributes of the HTML input fields.

Handling Form Data Example

<?php
// In a real scenario, this data is sent from the HTML form.
// We are simulating the submission here:
$_POST['name'] = "John Doe";
$_POST['email'] = "john@example.com";

echo "Welcome " . $_POST["name"] . "<br>"; echo "Your email address is: " . $_POST["email"]; ?>


GET vs. POST: Which Should You Use?

Both GET and POST create an array of key/value pairs that hold the form data. However, they have completely different use cases:

Now that you know how to collect data, we must learn how to secure it. Let's move on to Form Validation!


Exercise

?

Which superglobal array is used to collect form data sent securely without displaying it in the URL?